Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting peaks in python plots

My data file is shared in the following link.

We can plot this data using the following script.

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook

def read_datafile(file_name):

    data = np.loadtxt(file_name, delimiter=',')
    return data

data = read_datafile('mah_data.csv')


fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Data")    
ax1.set_xlabel('t')
ax1.set_ylabel('s')

ax1.plot(x,y, c='r', label='My data')

leg = ax1.legend()

plt.show()

How can we detect peaks in python? I can't find a suitable peak detection algorithm in Python.

like image 744
Mahsolid Avatar asked Sep 18 '25 22:09

Mahsolid


1 Answers

You can use the argrelextrema function in scipy.signal to return the indices of the local maxima or local minima of an array. This works for multi-dimensional arrays as well by specifying the axis.

from scipy.signal import argrelextrema

ind_max = argrelextrema(z, np.greater) # indices of the local maxima
ind_min = argrelextrema(z, np.less)  # indices of the local minima

maxvals = z[ind_max]
minvals = z[ind_min]

More specifically, one can use the argrelmax or argrelmin to find the local maximas or local minimas. This also works for multi dimensional arrays using the axis argument.

from scipy.signal import argrelmax, argrelmin

ind_max = argrelmax(z, np.greater) # indices of the local maxima
ind_min = argrelmin(z, np.less)  # indices of the local minima

maxvals = z[ind_max]
minvals = z[ind_min]

For more details, one can refer to this link: https://docs.scipy.org/doc/scipy/reference/signal.html#peak-finding

like image 121
Arun Avatar answered Sep 20 '25 11:09

Arun