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

筅森魡賤 提交于 2019-12-03 21:30:55

问题


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?


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/43966427/matplotlib-does-not-update-plot-when-used-in-an-ide-pycharm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!