0
該程序的目的:我需要在頂部繪製一個信號圖形,並在底部繪製該信號的光譜圖形,只有兩種情況下的y數據會有所不同。如何繪製2個動畫圖形與x軸固定在matplotlib與subplots?
我在輸入上產生一個隨機噪聲的正弦波,並將其繪製在頂部,這是正常工作。
問題是當我嘗試繪製頻譜圖時。由於某些原因,它並未更新,我也不太瞭解matplotlib.animation.FuncAnimation的功能。
代碼:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
dt = 0.01
Fs = 44000.0 # sample rate
timestep = 1.0/Fs # sample spacing (1/sample rate)
t = np.arange(0, 10, dt) # t range
n = 256 # size of the array data
w = 10000 # frequency of the input
data = np.sin(2*np.pi*w*t)
def update(data):
# update the curves with the incoming data
line.set_ydata(data)
#line2.set_ydata(magnitude)
return line,
def generateData():
# simulate new data coming in
while True:
nse = np.random.randn(len(t))
r = np.exp(-t/0.05)
cnse = np.convolve(nse, r)*dt
cnse = cnse[:len(t)]
data = np.sin(2*np.pi*w*(t)) + cnse
magnitude = np.fft.fft(data)/n
magnitude = np.abs(magnitude[range(n//2)])
yield data
fig = plt.figure()
# plot time graph axis
timeGraph = plt.subplot(2, 1, 1)
timeGraph.set_ylim(-0.2, 0.2)
timeGraph.set_xlabel('Time')
timeGraph.set_ylabel('Amplitude')
# plot frequency graph axis
freqGraph = plt.subplot(2, 1, 2)
freqGraph.set_xlabel('Freq (Hz)')
freqGraph.set_ylabel('|Y(freq)|')
# get frequency range
n = len(data) # length of the signal
print(len(data))
k = np.arange(n)
T = n/Fs
freq = k/T # two sides frequency range
freq = freq[range(n//2)] # one side frequency range
# fft computing and normalization
magnitude = np.fft.fft(data)/n
magnitude = np.abs(magnitude[range(n//2)])
line, = timeGraph.plot(np.linspace(0, 1, len(t)), 'b')
line2, = freqGraph.plot(freq, magnitude, 'g')
# animate the curves
ani = animation.FuncAnimation(fig, update, generateData,
interval=10, blit=True)
plt.show() # open window
獎金:我怎麼初始化數據和幅度是否正確?
非常感謝!我對「matplotlib.animationFuncAnimation()」的工作原理有些困惑。 –
此答案解決您的問題嗎?如果是這樣,你可以接受它。如果不是,或者您正在等待更多/更好的答案,您可以使用精確的要求更新您的問題,以便人們知道您在尋找什麼。 – ImportanceOfBeingErnest
Sry,我不知道那個:D接受。 –