中使用时不会更新绘图

中使用时不会更新绘图

本文介绍了Matplotlib 在 IDE (PyCharm) 中使用时不会更新绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于Matplotlib 在 IDE (PyCharm) 中使用时不会更新绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 04:25