如何使用python确定两个图中的峰值,并仅为两个图中的峰值绘制图形

如何使用python确定两个图中的峰值,并仅为两个图中的峰值绘制图形,python,matplotlib,math,time,Python,Matplotlib,Math,Time,在这里,我用两个名为real test和pred value的值绘制图。然后我想检测两个图的峰值,然后我想根据峰值再次绘制这两个图 我试过了,但走错了路 下面是我尝试的代码: 首先绘制图形: fig = plt.figure(figsize=(20,8)) gs = gridspec.GridSpec(2,30) plt.plot(real_test, label='True') plt.plot(pred, label='Predict') plt.legend() plt.show()

在这里,我用两个名为real test和pred value的值绘制图。然后我想检测两个图的峰值,然后我想根据峰值再次绘制这两个图

我试过了,但走错了路

下面是我尝试的代码:

首先绘制图形:

fig = plt.figure(figsize=(20,8))
gs = gridspec.GridSpec(2,30)
plt.plot(real_test, label='True')
plt.plot(pred,  label='Predict')
plt.legend()
plt.show()
图表:

然后我想检测两行的峰值,我编写了代码:

from math import sin
from matplotlib import pylab
from pylab import *

def peakdet(v, thresh):
  maxthresh = []
  minthresh = []
  peaks = []

 for x, y in v:
    if y > thresh:
        maxthresh.append((x, y))
    elif y < -thresh:
        minthresh.append((x, y))

 for x, y in maxthresh:
    try:
        if (v[x - 1][1] < y) & (v[x + 1][1] < y):
            peaks.append((x, y))
    except Exception:
        pass
    return peaks

  arr = [*zip(real_test, pred)]
  thresh = 0.95

  peaks = peakdet(arr, thresh)

  scatter([x for x, y in peaks], [y for x, y in peaks], color = 'red')
  plot(real_test, 184 * [thresh], color='green', linestyle='--', dashes=(5, 3))
  plot(real_test, 184 * [-thresh], color='green', linestyle='--', dashes=(5, 3))
  plot(real_test, pred, 'k')
  show()
从数学导入
从matplotlib导入pylab
从派拉布进口*
def峰值(v,阈值):
maxthresh=[]
minthresh=[]
峰值=[]
对于x,y在v中:
如果y>阈值:
maxthrresh.append((x,y))
elif y<-脱粒:
minthresh.append((x,y))
对于maxthresh中的x,y:
尝试:
如果(v[x-1][1]
获取图形:

但我期望图形的输出是这样的:

在读取两条线的峰值后,我需要再次绘制这两条线的峰值


有人能帮我解决这个问题吗?

一般来说,您需要存储峰值的索引。一旦获得峰值索引,就可以使用散点图覆盖在数据图上。 通常,我使用以下函数来检测峰值:。对于您的情况,您也可以使用此函数来解决您的问题

下面是向量
x
的示例:

从scipy.signal import查找峰值
#x是要从中提取峰值的向量
峰值,u=查找_峰值(x)
平面图(x)
plt.绘图(峰值,x[峰值],“x”)

我没有检查您的函数以检测峰值,但最重要的是您存储了峰值的索引

您的缩进是否错误,或者这只是一个格式化的情况,看起来您只是在for的一次迭代后从函数返回loop@KGS这是,显示在训练模型预测值和实际测试值后,它给了我这个错误,“格式字符串中无法识别的字符e”你能给我们产生这个错误的代码吗?我不知道它是从哪里来的。