2016-05-05 38 views
1

我试图在时间和频率范围内绘制我自制的四分之一波形。 如何在频域图中打印我最高峰的值?打印频域图的最高峰值

代码:

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() 

结果是这样的:

enter image description here

感谢, 肖恩

回答

4

由于您使用numpy,只是简单地使用numpy.maxnumpy.argmax确定峰值以及峰值的位置,以便您可以打印t他出去了你的屏幕。一旦找到这个位置,索引到你的频率数组中以获得最终的坐标。

假设当你运行你的代码,所有的变量都被创建,只需做到以下几点:

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 

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() 
0
print("maximum of |Y| is: %.4g" % np.max(np.abs(Y))) 

其他建议:使用数组切片:Y = Y[:n/2+1],而不是Y = Y[range(n/2)]。具有n个输入(n为偶数)的实值数据集的傅里叶变换将具有n/2 + 1个频率分量。您的索引错过了最后一点。如果n是奇数(就像你的情况),它变得更加棘手。

备注:最好为问题提供一个独立的示例,即不依赖于计算机上的文件的示例。