In this Python tutorial, we will learn about the “**Scipy Find Peaks**” and also discuss its usability with the help of a variety of examples. Additionally, cover the following topics.

- Scipy Find Peaks
- Scipy Finds Peaks of Prominence
- Scipy Find Peaks cwt
- Scipy Find Peaks and Valleys
- Scipy Find Peaks Minima
- Scipy Finds Peak Width

Also, check the latest Python Scipy tutorial: Python Scipy Curve Fit

## Scipy Find Peaks

The Python Scipy has a method

within a module *find_peaks()*

that returns all the peaks based on given peak properties. Peaks are not merely the peaks of an electric signal, maxima and minima in a mathematical function are also considered peaks.*scipy.signal*

The syntax is given below.

`scipy.signal.find_peaks(x, height=1, prominence=4, distance=2, width=2, threshold=1, rel_height=0.5, wlen=1, )`

Where parameters are:

It is used to accept the signal whose peaks need to be found.*x(sequence):*It might be an integer or an array, and it’s used to set the minimum height for a peak to be recognized.*height (sequence, ndarray, number):*The required vertical distance between a peak and its neighbors is known as the threshold, and it’s highly beneficial in the situation of noisy functions when we don’t want to pick out peaks from the noise.*threshold(sequence, ndarray, number):*It is the required minimum horizontal distance (number) between nearby peaks. It can be quite valuable in circumstances where the periodicity of the peaks is known.*distance(number):*It is used to provide peak prominence.*prominence(sequence,ndarray, number):*It is used to provide the width of the peak.*width(sequence,ndarray, number):*It is used to calculate the peak prominence.*wlen(int):*It is used to calculate the peak height.*rel_height(int):*

Let’s take an example by following the below steps:

Import the required library using the below python code.

```
from scipy.signal import find_peaks
from scipy.misc import electrocardiogram
import matplotlib.pyplot as plt
%matplotlib inline
```

Generate an electrocardiogram using the below code.

`value = electrocardiogram()[1000:5000]`

Now the peaks using the below code.

```
peak, _ = find_peaks(value, height=0)
plt.plot(value)
plt.plot(peak, value[peak], "*")
plt.plot(np.zeros_like(value), "--", color="green")
plt.show()
```

This is how to find the peaks of the signal using the method

of Python SciPy.*find_peaks()*

Read: Scipy Misc + Examples

## Scipy Find Peaks Prominence

The Python SciPy has a method

that computes the vertical distance between the peak and its lowest contour line in comparison to the surrounding baseline of the signal.*peak_prominence()*

The syntax is given below.

`scipy.signal.peak_prominences(x, wlen=None, peaks)`

Where the parameters are:

It is used to accept the signal whose peaks need to be found.*x(sequence):*It is used to specify the sample window length.*wlen(int):*Peak indices in x.*peaks(sequence):*

The method

return the *peak_prominence()*

(each peak) and the *prominences*of type ndarray.

`left-right bases`

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

```
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
%matplotlib inline
```

Generate a signal using the below code.

```
array_data = np.linspace(0, 5 * np.pi, 1100)
sig = np.sin(array_data) + 0.5 * np.sin(1.7 * array_data)
```

Determine the prominences of all peaks using the below code.

```
sig_peaks, _ = signal.find_peaks(sig)
promin = signal.peak_prominences(sig, sig_peaks)[0]
promin
```

Now compute and graph the height of each peak’s contour line using the below code.

```
contur_height = sig[sig_peaks] - promin
plt.plot(sig)
plt.plot(sig_peaks, sig[sig_peaks], "*")
plt.vlines(x=sig_peaks, ymin=contur_height, ymax=sig[sig_peaks])
plt.show()
```

This is how to find the prominences of peaks using the method

of Python SciPy.*peak_prominences()*

Read: Scipy Sparse – Helpful Tutorial

## Scipy Find Peaks cwt

The Python SciPy has a method

that uses the *find_peaks_cwt()*

to find peaks in a 1-D array. But *Wavelet transformation*** “What is Wavelet transformation?”** A signal of N samples is decomposed into low and high-frequency bands using a pair of filters. Each band is two-fold undersampled, with N/2 samples in each.

The syntax is given below.

`scipy.signal.find_peaks_cwt(vector, wavelet=None, widths, max_distances=None, window_size=None, gap_thresh=None, min_snr=0, min_length=None, noise_perc=9)`

Where the parameters are:

Find the peaks in a 1-D array.*vector(ndarray):*It must return a 1-D array to convolve with the vector after taking two arguments. The first argument specifies the number of points in the output wavelet array, while the second specifies the wavelet’s scale.*wavelet(callable):*To calculate the CWT matrix, utilize a single width or a one-dimensional array of widths.*widths():*A ridgeline is connected at each row only if the relative maximum at row[n] is within max distances[n] of the relative maximum at row[n+1].*max_distances(ndarray):*To calculate the noise floor, specify the size of the window.*window_size(int):*There will be a gap if a relative maximum is not found inside max distances. If there’s more than the*gap_thresh(float):*point without a new relative maximum, the ridgeline is terminated.*gap_thresh*Minimum signal-to-noise ratio.*min_snr(float):*A ridge line’s minimum length must be acceptable.*min_length(int):*The noise floor is calculated using the percentile of data points below which noise is considered.*noise_perc(float):*

The method

returns te*find_peaks_cwt()*** **.

`peak_indices`

Let’s understand with an example by following the below steps:

Import the required libraries using the below python code.

```
from scipy.signal import find_peaks_cwt
import numpy as np
```

Generate the array elements and apply the function sin on that array using the method

using the below code.*np.sin()*

```
x_data = np.arange(0, np.pi, 0.06)
sin_data = np.sin(x_data)
```

Calculate the peak indices or peaks using the below code.

```
peak_indices = signal.find_peaks_cwt(sin_data, np.arange(2,11))
peak_indices, x_data[peak_indices], sin_data[peak_indices]
```

This is how to find the peaks using the method

of Python SciPy.*find_peaks_cwt*

Read: Scipy Optimize – Helpful Guide

## Scipy Finds Peak Width

The Python SciPy has a method

that determines the width of each signal’s peak.*peak_widths()*

The syntax is given below.

`scipy.signal.peak_widths(x, rel_height=0.3, peaks, wlen=None, prominence_data=None)`

Where the parameters are:

It is used to accept the signal.*x(sequence):*It is used to specify the sample window length.*wlen(int):*Peak indices in x.*peaks(sequence):*Selects the relative height at which the peak breadth is expressed as a percentage of its prominence. The breadth of the peak is calculated at its lowest contour line at 1.0, and half the prominence height is calculated at 0.5.*rel_height(float):*When invoked with the same parameters x and peaks, a tuple of 3 arrays matches the result of peak prominences.*prominence_data(tuple):*

The method

returns*peak_widths()*** **,

`widths`

(sample peak widths)**and**

`widths_height`

(the height of the contour lines used to calculate the widths.)**.**

`right_ips, left_ips`

(Interpolated positions of a horizontal line’s left and right junction points at each evaluation height)Let’s see with an example by following the below steps:

Import the required libraries using the below python code.

```
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
%matplotlib inline
```

Generate a signal using the below code.

```
array_data = np.linspace(0, 5 * np.pi, 1100)
sig = np.sin(array_data) + 0.5 * np.sin(1.7 * array_data)
```

Determine the width of all peaks using the below code.

```
sig_peaks, _ = signal.find_peaks(sig)
promin = signal.peak_prominences(sig, sig_peaks)[0]
promin
```

Plot the widths of the signal, peaks, and contour lines using the below code.

```
plt.plot(sig)
plt.plot(sig_peaks, sig[sig_peaks], "*")
plt.hlines(*half_peak_res[1:], color="C4")
plt.hlines(*full_peak_res[1:], color="C5")
plt.show()
```

This is how to compute the width of the peak using the method

of Python SciPy.*peak_widths()*

Read: Python Scipy FFT [11 Helpful Examples]

## Scipy Find Peaks and Valleys

In the Python SciPy, there is no inbuilt method to find peaks and valleys of signal, here we will perform this task manually by using the method

that exists within the module *argrelextrema()*`scipy.signal`

.

To find the peaks and valleys of the signal flow the below steps:

Import the required libraries using the below python code.

```
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from scipy.signal import argrelextrema
%matplotlib inline
```

Generate the data using the below code.

```
x_data = np.arange(start = 0, stop = 30, step = 1, dtype='int')
y_data = np.random.random(30)*5
```

Compute the peaks using the below code.

```
peaks_ind = argrelextrema(y_data, np.greater)
peaks_ind = peaks_ind[0]
```

Compute the valleys using the below code.

```
valleys_ind = argrelextrema(y_data, np.less)
valleys_ind = valleys_ind[0]
```

Plot the graph with peak and valleys data that we have generated using the below code.

```
(fig, ax) = plt.subplots()
ax.plot(x_data, y_data)
x_peak = peaks_ind
y_peak = y_data[peaks_ind]
ax.plot(x_peak, y_peak, marker='*', linestyle='dashed', color='orange', label="peaks")
x_valley = valleys_ind
y_valley = y_data[valleys_ind]
ax.plot(x_valley, y_valley, marker='*', linestyle='dashed', color='blue', label="Valleys")
```

This is how to find the peak and valleys of the signal in Python SciPy.

Read: Scipy Linalg – Helpful Guide

## Scipy Find Peaks Minima

We have learned how to find the peaks or the maximum value of the signal using the method

of the Python Scipy library. But here in this section, we are going to find the Minima or the valleys of a given signal.*find_peaks()*

To find the minima of the signal or the given data follow the below steps:

Import the required libraries using the below python code.

```
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from scipy.signal import argrelextrema
```

Create a signal using the random data by following the below code.

```
array_data = np.arange(start = 0, stop = 40, step = 1, dtype='int')
y_array_data = np.random.random(40)*5
```

Calculate the minima of the signal using the below code.

```
minima_ind = argrelextrema(y_array_data, np.less)
minima_ind = minima_ind[0]
minima_ind
```

Plat the calculated minima on the graph using the below code.

```
(fig, ax) = plt.subplots()
ax.plot(array_data, y_array_data)
x_minima = minima_ind
y_minima = y_array_data[minima_ind]
ax.plot(x_minima, y_minima, marker='*', linestyle='dashed', color='green', label="Minima")
```

This is how to find the minima of the signal or data using the method

of Python SciPy.*argrelextrema()*

Also, take a look at some more Python Scipy tutorials.

- Python Scipy Chi-Square Test
- Python Scipy Lognormal
- Python Scipy Exponential
- Scipy Stats Zscore + Examples
- Scipy Convolve – Complete Guide
- Scipy Signal – Helpful Tutorial
- Scipy Integrate + Examples

So, in this tutorial, we have learned about the “**Scipy Find Peaks**” and covered the following topics.

- Scipy Find Peaks
- Scipy Finds Peaks of Prominence
- Scipy Find Peaks cwt
- Scipy Find Peaks and Valleys
- Scipy Find Peaks Minima
- Scipy Finds Peak Width

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.