Python find x value to corresponding max y value in plot

klayfiel picture klayfiel · Aug 8, 2012 · Viewed 43.1k times · Source

I've plotted a moving average from about 300,000 data points and I need to find the maximum y-value for the peak in the signal and its corresponding x-value, which would be its frequency. I'd like for it to give me the coordinates on the plot itself but if I can get it to at least print them out I'd be satisfied. Excuse my programming skills as they are not the strongest. Here's the section of the code I'm working on and a link to the plot that it generates. I don't have enough points to post the image.

def movingaverage(interval, window_size):
    window= np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

x = freq[0:300000]
y = fft
pylab.plot(x,y,"k.")
y_av = movingaverage(y, 30)
pylab.plot(x, y_av,"r")
pylab.xlim(0,10)
pylab.ylim(0,1500)
pylab.xlabel("Frequency")
pylab.ylabel("Moving Average Magnitude")
pylab.grid(True)
pylab.show() 

Moving Average Plot

Answer

Sam Mussmann picture Sam Mussmann · Aug 8, 2012

You should be able to do something like:

max_y = max(y_av)  # Find the maximum y value
max_x = x[y_av.index(max_y)]  # Find the x value corresponding to the maximum y value
print max_x, max_y

Edit

numpy arrays do not have an index method, so we should use argmax, as pointed out in the comments:

max_y = max(y_av)  # Find the maximum y value
max_x = x[y_av.argmax()]  # Find the x value corresponding to the maximum y value
print max_x, max_y

I think this API should work to let you draw text onto your image. You could do that like so:

pylab.text(max_x, max_y, str((max_x, max_y)))