I am new to python and just installed pyCharm and tried to run a test example given to the following question: How to update a plot in matplotlib?
This example upda
As noted by ImportanceOfBeingErnest in a separate question, on some systems, it is vital to add these two lines to the beginning of the code from the OP's example:
import matplotlib
matplotlib.use("TkAgg")
This may render the calls to plt.ion
and plt.ioff
unnecessary; the code now works without them on my system.
The updating in the linked question is based on the assumption that the plot is embedded in a tkinter application, which is not the case here.
For an updating plot as a standalone window, you need to have turned interactive mode being on, i.e. plt.ion()
. In PyCharm this should be on by default.
To show the figure in interactive mode, you need to draw it, plt.draw()
. In order to let it stay responsive you need to add a pause, plt.pause(0.02)
. If you want to keep it open after the loop has finished, you would need to turn interactive mode off and show the figure.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-')
plt.draw()
for phase in np.linspace(0, 10*np.pi, 500):
line1.set_ydata(np.sin(x + phase))
plt.draw()
plt.pause(0.02)
plt.ioff()
plt.show()