2016-05-05 43 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是奇數(就像你的情況),它變得更加棘手。

備註:最好爲問題提供一個獨立的示例,即不依賴於計算機上的文件的示例。