如何在matplotlib动画中从串行端口更新值? [英] How to update values from serial port in matplotlib animations?
本文介绍了如何在matplotlib动画中从串行端口更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试使用matplotlib的动画功能实时绘制来自arduino的串行数据。数据来自ntc温度传感器。我能够获得的绘图始终显示一条单线,并且该线仅在温度变化时向上或向下平移。我想知道该怎么做才能查看代表绘图变化的曲线。代码如下:
I've been trying to plot serial data from an arduino in real-time using matplotlib's animation function. The data comes from a ntc temperature sensor. The plot I was able to get displays a sigle line all the time, and the line is only translated up or down as the teperature changes. I'd like to know what can I do to view the curves representing the changes in the plot. Here´s the code:
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()
推荐答案
您正在将y数据设置为单点(0,y)。您想做类似的事情:
You are setting the y-data to be a single point (0, y). You want to do something like:
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,
这篇关于如何在matplotlib动画中从串行端口更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文