Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib does not update plot when used in an IDE (PyCharm)

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 updates the plot to animate a moving sine signal. Instead of replotting, it updates the data of the plot object. It works in command line but the figure does not show up when run in PyCharm. Adding plt.show(block=True) at the end of the script brings up the figure but this time it wont update.

Any ideas?

like image 212
hko Avatar asked May 14 '17 16:05

hko


2 Answers

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.

like image 82
Peter Drake Avatar answered Oct 17 '22 16:10

Peter Drake


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()
like image 39
ImportanceOfBeingErnest Avatar answered Oct 17 '22 18:10

ImportanceOfBeingErnest