我需要你的帮助来用 Python 编写一个脚本,该脚本将获取动态变化的数据,数据源在这里无关紧要,并在屏幕上显示图形。
我知道如何使用 matplotlib,但 matplotlib 的问题是我只能在脚本末尾显示一次图形。我不仅需要能够一次显示图形,而且还需要在每次数据更改时即时更新它。
我发现可以使用带有 matplotlib 的 wxPython 来执行此操作,但对我来说这样做有点复杂,因为我根本不熟悉 wxPython。
因此,如果有人能向我展示如何使用带有 matplotlib 的 wxPython 来显示和更新简单图形的简单示例,我将非常高兴。或者,如果有其他方法可以做到这一点,那对我也有好处。
附言:
好的,因为没有人回答并查看@janislaw 注意到的 matplotlib 帮助并编写了一些代码。这是一些虚拟示例:
import time
import matplotlib.pyplot as plt
def data_gen():
a=data_gen.a
if a>10:
data_gen.a=1
data_gen.a=data_gen.a+1
return range (a,a+10)
def run(*args):
background = fig.canvas.copy_from_bbox(ax.bbox)
while 1:
time.sleep(0.1)
# restore the clean slate background
fig.canvas.restore_region(background)
# update the data
ydata = data_gen()
xdata=range(len(ydata))
line.set_data(xdata, ydata)
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
fig.canvas.blit(ax.bbox)
data_gen.a=1
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], animated=True)
ax.set_ylim(0, 20)
ax.set_xlim(0, 10)
ax.grid()
manager = plt.get_current_fig_manager()
manager.window.after(100, run)
plt.show()
这个实现有问题,比如如果你试图移动窗口,脚本就会停止。不过基本上是可以用的。
原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我写的一个类来处理这个问题。它需要一个你传递给它的 matplotlib 图,并将它放在一个 GUI 窗口中。它在自己的线程中,因此即使您的程序很忙,它也能保持响应。
在您的代码中,您需要像这样初始化绘图仪:
然后你可以像这样绘制它: