How could I get a list of all the zeroes of a matplotlib graph? By zeroes I mean every coordinate where the y-value of my function is at 0 (very close to zero also works for what I'm trying to accomplish). My code and the graph it generates are down below.
CodePudding user response:
I believe you want to find all times where the y-value is zero.
What about finding zero-crossings of the array data[:, 1]
(here a
), and use the returned indices to find the interpolated time values where y-value is zero.
CODE
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
# load data
samplerate, data = wavfile.read(r'C:\Users\jack_l\Downloads\louduntitled.wav')
length = data.shape[0] / samplerate
time = np.linspace(0., length, data.shape[0])
a = data[:, 1] # here put your data
zc_idxs = np.where(np.diff(np.sign(a)))[0] # indices of element before zero crossing
t_zero = []
for zc_i in zc_idxs: # interpolate each zero crossing
t1 = time[zc_i]
t2 = time[zc_i 1]
a1 = a[zc_i]
a2 = a[zc_i 1]
t_zero.append(t1 (0 - a1) * ((t2 - t1) / (a2 - a1)))
plt.plot(time, a, label="Right channel")
plt.plot(t_zero, np.zeros((len(t_zero), 1)), 'o')
CodePudding user response:
We can't access to your data, so I used the cos function to have a similar shape.
Here is my code that perform a linear interpolation (there's a small error due to the non-linear behavior of the cos function)
import numpy as np
n = 2000
x = np.linspace(0, 10, n)
y = np.cos(x)
res = []
is_positive = y[0] > 0
for i in range(n):
if y[i] == 0:
res.append(x[i])
elif (is_positive and y[i] < 0) or (not is_positive and y[i] > 0):
x_gap = x[i] - x[i-1]
coef_gap = y[i]/(y[i] - y[i-1])
res.append(x[i] x_gap*coef_gap)
is_positive = not is_positive
analytic_res = [i*np.pi/2 for i in range(1,6,2)]
print(res)
print(analytic_res)
Output :
[1.5807794610537442, 4.722328378160516, 7.863877295269648]
[1.5707963267948966, 4.71238898038469, 7.853981633974483]
NB : if the very first value is zero, the code could have a weird behavior