打印频域图的最高峰值

Sha*_*ney 1 python matlab numpy matplotlib scipy

我试图在时域和频域中绘制我自制的四边形的振荡。如何在频域图中打印最高峰的值?

代码:

import matplotlib.pyplot as plt
import numpy as np
from scipy import fft, arange

csv = np.genfromtxt ('/Users/shaunbarney/Desktop/Results/quadOscillations.csv', delimiter=",",dtype=float)
x = csv[:,0]
y = csv[:,1]
x = x - 6318        #Remove start offset
av=0
for i in xrange(1097):      #Calculate average sampling time in seconds oscillations 
    if i == 1076:
        avSampleTime = av/1097000     # 
        break
    av = av + (x[i+1]-x[i])

Fs = 1/avSampleTime   #Average sampling freq.
n = 1079              #no.Samples
k = arange(n)
Ts = n/Fs
frq = k/Ts            #Frequency range two sided
frq = frq[range(n/2)] #Frequency range one sided
Y = fft(y)/n          #Fast fourier transfors
Y = Y[range(n/2)]     #Normalise

#        PLOTS

plt.subplot(2,1,1)
plt.plot(frq,abs(Y),'r') # plotting the spectrum
plt.xlabel('Freq (Hz)')
plt.ylabel('|Y(freq)|')
plt.grid('on')
plt.subplot(2,1,2)
plt.plot(x,y)
plt.xlabel('Time (ms)')
plt.ylabel('Angle (degrees)')
plt.grid('on')
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

谢谢,肖恩

ray*_*ica 5

由于您正在使用numpy,只需简单地使用numpy.maxnumpy.argmax来确定峰值以及峰值的位置,以便您可以将其打印到屏幕上。找到该位置后,索引到频率数组以获得最终坐标。

假设在运行代码时已创建所有变量,只需执行以下操作:

mY = np.abs(Y) # Find magnitude
peakY = np.max(mY) # Find max peak
locY = np.argmax(mY) # Find its location
frqY = frq[locY] # Get the actual frequency value
Run Code Online (Sandbox Code Playgroud)

peakY包含图形中最大的幅度值,并frqY包含该最大值(即峰值)所在的频率。作为奖励,您可以用不同的颜色和更大的标记将其绘制在图表上,以将其与主震级图区分开来。请记住,调用多个plot调用只会附加到当前焦点的顶部。因此,绘制频谱,然后将该点绘制在频谱顶部。我将使点的大小大于绘图的厚度,并用不同的颜色标记该点。您也许还可以制作一个反映该最大峰值和相应位置的标题。

另请记住,这是根据震级完成的,因此在绘制实际震级之前,只需执行以下操作:

#        PLOTS
# New - Find peak of spectrum - Code from above
mY = np.abs(Y) # Find magnitude
peakY = np.max(mY) # Find max peak
locY = np.argmax(mY) # Find its location
frqY = frq[locY] # Get the actual frequency value

# Code from before
plt.subplot(2,1,1)
plt.plot(frq,abs(Y),'r') # plotting the spectrum

# New - Plot the max point
plt.plot(frqY, peakY, 'b.', markersize=18)

# New - Make title reflecting peak information
plt.title('Peak value: %f, Location: %f Hz' % (peakY, frqY))

# Rest of the code is the same
plt.xlabel('Freq (Hz)')
plt.ylabel('|Y(freq)|')
plt.grid('on')
plt.subplot(2,1,2)
plt.plot(x,y)
plt.xlabel('Time (ms)')
plt.ylabel('Angle (degrees)')
plt.grid('on')
plt.show()
Run Code Online (Sandbox Code Playgroud)