Note: this is not about "animating" charts; rather, updating and extending the data of the plot.
I have seen a lot of PyPlot S.O. questions about how to update PyPlot in a loop, but many of these answers either outdated, or beyond the simplicity I seek.
The closest example I have seen is this:
import pylab as pl
from IPython import display
for i in range(10):
pl.plot(pl.randn(100))
display.clear_output(wait=True)
display.display(pl.gcf())
but it plots new data on top of the old at each loop iteration and when finished, produces two charts, where I only want one.
So lets say I have two lines:
l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]
and I am going to add new data to each line at each loop iteration:
for i in range(11, 20):
l1.append(i)
l2.append(i^2)
all I want is to see a single plot that is showing the updated lines.
some posts suggest using the set_ydata
function of a subplot, but this doesnt seem to work for me. Example from https://stackoverflow.com/a/4098938/5623899
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)
# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
for phase in np.linspace(0, 10*np.pi, 500):
line1.set_ydata(np.sin(x + phase))
fig.canvas.draw()
only produces the plot once the entire thing is done.
changing that example towards the one I postulated fails
l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]
print([i^2 for i in range(10)])
print(l2)
import pylab as pl
from IPython import display
fig = plt.figure()
ax = fig.add_subplot(111)
line1 = ax.plot(l1)
line2 = ax.plot(l2)
for i in range(11, 20):
l1.append(i)
l2.append(i^2)
line1.set_ydata(l1)
line2.set_ydata(l2)
fig.canvas.draw()
as having only a singluar array in plt.plot(arr) results in the method set_ydata
not being present.
so how do I do this?