Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
plotting data from serial port with matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(-5000, 5000)
xdata, ydata = [0]*100, [0]*100
raw = serial.Serial("/dev/ttyUSB1",9600)
def update(data):
return line,
def run(data):
t,y = data
del xdata[0]
del ydata[0]
line.set_data(xdata, ydata)
return line,
def data_gen():
t = 0
while True:
dat = int(raw.readline())
dat = 0
yield t, dat
ani = animation.FuncAnimation(fig, run, data_gen, interval=0, blit=True)
Copy link

Amazing man!
There is only a problem, when I start the script the plot is showed correctely, in a first moment, but after any seconds it is eraised by itself. How can I resolve this issue? Thanks a lot!

Copy link

Rainald62 commented Sep 28, 2018

It seems that updating data by one line and updating the plot by one frame is linked. That way, it won't work for data rate > max frame rate, which is rather slow compared to other solutions using plt.ion(). It might be an inherent problem with animation.FuncAnimation(), as I havn't seen a working solution yet.
P.S.: A working solution with animation.FuncAnimation() and threads on reddit.

Copy link

what if I need a y scale that goes from 0 0.1 0.2 0.3 to 13 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment