I'm trying to create a plot in Python where the data that is being plotted gets updated as my simulation progresses. In MATLAB, I could do this with the following code:
t = linspace(0, 1, 100);
figure
for i = 1:100
x = cos(2*pi*i*t);
plot(x)
drawnow
end
I'm trying to use matplotlib's FuncAnimation function in the animation module to do this inside a class. It calls a function plot_voltage which recalculates voltage after each timestep in my simulation. I have it set up as follows:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def __init__(self):
ani = animation.FuncAnimation(plt.figure(2), self.plot_voltage)
plt.draw()
def plot_voltage(self, *args):
voltages = np.zeros(100)
voltages[:] = np.nan
# some code to calculate voltage
ax1 = plt.figure(2).gca()
ax1.clear()
ax1.plot(np.arange(0, len(voltages), 1), voltages, 'ko-')`
When my simulation runs, the figures show up but just freeze. The code runs without error, however. Could someone please let me know what I am missing?
count()which simply counts up the positive integers, and I run this afterplt.show(),count()won't run until I close the plot. Replacingplt.show()withplt.draw()causes the plot not to show up at all, but thencount()runs. How can I have the plot update while the program continues andcount()runs? My backend is Qt5Agg with interactive mode on.update()would call both yourcount(), so the plotting continues.count()function inupdate(), the code runs and the plot shows up, but the window just freezes and nothing is displayed. My code is here.while Truein a program that requires user interaction.