Matplotlib 在 IDE (PyCharm) 中使用时不会更新绘图

2022-01-20 00:00:00 python matplotlib plot ide show

问题描述

我是 python 新手,刚刚安装了 pyCharm,并尝试运行针对以下问题的测试示例:How to update a plot在matplotlib中?

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?

此示例更新绘图以动画化移动正弦信号.它不是重新绘制,而是更新绘图对象的数据.它在命令行中工作,但在 PyCharm 中运行时该图不显示.在脚本末尾添加 plt.show(block=True) 会显示图形,但这次它不会更新.

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.

有什么想法吗?


解决方案

链接问题中的更新是基于情节嵌入在tkinter应用程序中的假设,此处并非如此.

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.

对于作为独立窗口的更新绘图,您需要打开交互模式,即 plt.ion().在 PyCharm 中,这应该默认开启.

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.

要以交互模式显示图形,您需要绘制它,plt.draw().为了让它保持响应,您需要添加一个暂停,plt.pause(0.02).如果要在循环结束后保持打开状态,则需要关闭交互模式并显示图形.

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

相关文章