我一直在尝试使用matplotlib的动画功能实时绘制arduino的串行数据。数据来自ntc温度传感器。我能够获得的图表始终显示一条单线,并且该线条仅在温度变化时向上或向下平移。我想知道如何查看表示图中变化的曲线。这是代码:
import serial
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
arduino = serial.Serial('COM3', 9600)
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(10, 40))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 10, 1000)
y = arduino.readline()
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=False)
plt.show()
答案 0 :(得分:2)
您正在将y数据设置为单个点(0,y)。你想做类似的事情:
max_points = 50
# fill initial artist with nans (so nothing draws)
line, = ax.plot(np.arange(max_points),
np.ones(max_points, dtype=np.float)*np.nan,
lw=2)
def init():
return line,
def animate(i):
y = arduino.readline() # I assume this
old_y = line.get_ydata() # grab current data
new_y = np.r_[old_y[1:], y] # stick new data on end of old data
line.set_ydata(new_y) # set the new ydata
return line,