如何使用python确定两个图中的峰值并只绘制两个图中的峰值

2024-06-23 19:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我用两个名为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()

图表:

enter image description here

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

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()

获取图表:

enter image description here

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

enter image description here

在读取了两条线的峰值之后,我需要再次绘制两条只有峰值的线。你知道吗

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


Tags: infromtestimportforplot图表绘制
1条回答
网友
1楼 · 发布于 2024-06-23 19:25:11

通常,您需要存储峰值的索引。一旦有了峰值的索引,就可以使用散点图覆盖在数据图上。 通常,我使用以下函数来检测峰值:scipy.signal.find_peaks。对于您的案例,您也可以使用此函数来解决您的问题。你知道吗

以下是向量x的示例:

    from scipy.signal import find_peaks
    # x is the vector from which you want to extract the peaks
    peaks, _ = find_peaks(x)
    plt.plot(x)
    plt.plot(peaks, x[peaks], "x")

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

相关问题 更多 >

    热门问题