team
team

Reputation: 526

How to determine the peak values in two graphs and plot graph for only peak values in two graphs using python

Here I plot the graph with two values named real test and pred value. Then I want to detect the peak values of both graph and then I want to plot it again that two graph according to the peak values.

I tried it , but I got wrong way.

Here what I tried the code:

First plot the graph:

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

graph :

enter image description here

Then I want to detect the peak values of both lines, I wrote the code :

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

Got graph:

enter image description here

But what I expected output of graph be like this:

enter image description here

After reading the peak values of both lines I need to plot again that two lines only with peak values.

Can anyone help me to solve this problem?

Upvotes: 0

Views: 1723

Answers (1)

Thombou
Thombou

Reputation: 407

In general, you want to store the index of the peaks. Once you have the index of the peaks, you can use a scatter plot to overlay on your data plot. Usually, I use the following function to detect the peaks: scipy.signal.find_peaks. It looks like for your case, you could also use this function to solve your problem.

Here is an example for a vector 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")

I have not checked your function to detect the peaks, but the most important is that you store the index of the peaks

Upvotes: 0

Related Questions