Home > Software engineering >  Matplotlib plots based on index not value
Matplotlib plots based on index not value

Time:04-04

I'm trying to create a function that plots the peaks of a function. It works when I don't give the plot a range (i.e. 100 time steps from 0 to 99) but doesn't work when I give a range (i.e. 100 time steps from -2pi to 4pi). Any ideas on how to fix this? Thanks!

def findpeaks(f,x,basicplot=True,plotit=False):

    dx = x[1] - x[0]
    
    gradfunc = np.gradient(f,dx)
    signgrad = np.sign(gradfunc)
    gradsign = np.gradient(signgrad,dx)
    peaks = np.where(-gradsign > 0)[0][::2] 
    peaksnew = peaks   x[0]
    
    if basicplot:
        plt.plot(x,f,'b')
        plt.plot(peaks,f[peaks],'ok')
    
    if plotit:
        plt.plot(x,f,'b')
        plt.plot(x,gradfunc,'y')
        plt.plot(x,signgrad,'g')
        plt.plot(x,-gradsign,'r')
        plt.plot(peaks,f[peaks],'ok')
        
    return peaks
x = np.linspace(-2*np.pi,4*np.pi,100)
f = 0.5*x   2*np.sin(x)

'time steps from 0 to 99' 'time steps from -2pi to 4pi'

CodePudding user response:

It looks like you just need to linearly rescale the x-axis for your black dots: 0 -> -2 pi and 99 -> 4 pi gives a = 6pi/100 and b =-2pi. So writing

plt.plot(a*peaks b,f[peaks],'ok')

with these values should fix this problem.

  • Related