Animated functions with matplotlib
Steve Keller
keller at no.invalid
Wed Jun 3 08:57:19 EDT 2020
I am trying to plot a live signal using matplotlib and it really
drives me crazy. I have tried dozens of variants, with and without
interactive (plt.ion()), with animation.FuncAnimation and doing things
by hand, calling plt.show() and/or plt.draw() but nothing works as
expected. One problem is that running commands in the interactive
python shell behaves differently from the behavior when using the same
commands in a script, so trying out different versions is very
confusing.
I'd like to do something like this:
fig, ax = plt.subplots()
ival = .1
now = 0
t = list(numpy.linspace(now, now, 500))
y = [0] * len(t)
while True:
time.sleep(ival)
now += ival
val = get_sample_from_some_signal()
t = t[1:] + [now]
y = y[1:] + [val]
ax.clear()
ax.plot(t, y)
plt.pause(1e-9)
This works but is *very* slow and it seems the plot window is closed
and opened again or raised for each new value to plot.
I have tried to call plt.show(block=False) only once and then
repeatedly only change data with ax.lines[0].set_xdata(),
ax.lines[0].set_ydata(), and ax.set_xlim() and then calling
plt.draw(). That works in the interactive python shell but not in a
script. When calling set[xy]_data() and set_xlim() in an amimate()
function passed to animation.FuncAnimation, but I haven't managed to
redraw the x scale values (although ax.xlim() is called).
Also, with animation.FuncAnimation() I loose control of the main
thread of execution. When calling plt.show() the function doesn't
return.
I may want to change the loop so that instead of
time.sleep(ival)
val = get_sample_from_some_signal()
I would have
val = wait_for_next_same_from_some_signal()
and I think this doesn't work with FuncAnimation since that calls the
passed function with a fixed time interval.
I am completely lost, can someone help?
Steve
More information about the Python-list
mailing list