'scipy.signal peak_widths not evaluating at correct index
I'm trying to find the FWHM of a curve I've generated. This is the code for the curve and a picture of what it looks like.
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.signal import peak_widths, find_peaks
k = np.load('/data/Var/test.npy')
x = np.load('/data/Var/sigrng.npy')
peakk = find_peaks(k)
kfwhm = peak_widths(k, peakk[0], rel_height=0.5)
plt.plot(x, k, ls='--', color='red')
plt.show()
Which produces this curve:
However, when I print out the output from what is supposed to be the FWHM and plot it on the curve it's not evaluating on the actual curve and is giving values much larger than what I expect.
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.signal import peak_widths, find_peaks
k = np.load('/data/Var/test.npy')
x = np.load('/data/Var/sigrng.npy')
peakk = find_peaks(k)
kfwhm = peak_widths(k, peakk[0], rel_height=0.5)
plt.plot(x, k, ls='--', color='red')
plt.hlines(*kfwhm[1:], color="red")
plt.show()
Can anyone see anything I'm doing wrong that could cause this? When checking where the peak in the curve is manually the find_peaks function is working correctly.
Solution 1:[1]
I worked out the problem. It is due to the fact that when it calculates the FWHM it does not take into account the x values that you plot the curve against. Since my plots are supposed to go between 0 and 1 I simply divide the values by the size of the array on the y axis (here the array k) and it fixes the issue. Code below:
peakk, _ = find_peaks(k)
kfwhm = peak_widths(k, peakk, rel_height=0.5)
kfwhm = np.asarray(kfwhm)
plt.plot(x_k, k, ls='--', color='red')
plt.hlines(0.5, *(kfwhm[2:]/k.size), color="blue")
plt.show()
Giving:
and a FWMH of:
print(kfwhm[0]/k.size)
Out[384]: array([0.02415405])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yikesthisisamess |



