程序的目的:我需要在顶部绘制一个信号图,在底部绘制这个信号的频谱图,只有两种情况下的y数据是不同的。在
我在输入端生成一个带有随机噪声的正弦波,并将其绘制在顶部,效果很好。在
问题是当我试图绘制光谱图时。由于某些原因它没有更新,而且我对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
另外:如何正确初始化数据和震级?在
为了同时更新时间和频率图,您需要在
update
函数中将两者的数据设置为各自的绘图。当然,您还需要在生成函数中提供这些数据。因此生成函数应该yield (data, magnitude)
,更新函数应该接受这个元组作为输入。在为频率图设置一些限制也是一个好主意,
freqGraph.set_ylim([0, 0.006])
这样它就不会保持为空。在我不知道你说的是什么意思,如何正确初始化数据和震级?。我认为它们的初始化是正确的,因为它们是为每一帧计算的,包括第一帧。在
这是一个工作代码。在
相关问题 更多 >
编程相关推荐