问题
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()
回答1:
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,
来源:https://stackoverflow.com/questions/20572815/how-to-update-values-from-serial-port-in-matplotlib-animations