我对python很陌生,我刚刚安装了pyCharm,并尝试运行一个测试示例,给出以下问题:How to update a plot in matplotlib?
此示例更新绘图以动画移动正弦信号。它不是重新绘图,而是更新绘图对象的数据。它在命令行中工作,但在PyCharm中运行时没有显示这个数字。在脚本的末尾添加plt.show(block=True)
会显示图形,但这次不会更新。
有什么想法吗?
发布于 2017-05-14 17:54:06
链接问题中的更新是基于这样的假设,即绘图嵌入到tkinter应用程序中,这里的情况并非如此。
对于作为独立窗口的更新绘图,您需要打开交互模式,即plt.ion()
。在PyCharm中,默认情况下这应该是打开的。
要在交互模式下显示图形,您需要绘制它,plt.draw()
。为了让它保持响应性,您需要添加一个暂停,plt.pause(0.02)
。如果您想在循环结束后继续打开它,则需要关闭交互模式并显示图。
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()
发布于 2018-01-09 23:08:45
正如ImportanceOfBeingErnest在a separate question中所指出的,在某些系统中,必须将这两行代码添加到OP示例中的代码开头:
import matplotlib
matplotlib.use("TkAgg")
这可能使对plt.ion
和plt.ioff
的调用变得不必要;在我的系统中,代码现在不用它们就能工作。
https://stackoverflow.com/questions/43966427
复制相似问题