使用 Python 创建动态更新图

Ale*_*lex 6 python graph dynamic

我需要你的帮助,用 Python 编写一个脚本,该脚本将获取动态更改的数据,这里的数据源无关紧要,并在屏幕上显示图形。

我知道如何使用 matplotlib,但是 matplotlib 的问题是我只能在脚本末尾显示一次图形。我不仅需要能够一次性显示图形,而且还需要在每次数据更改时即时更新它。

我发现可以使用 wxPython 和 matplotlib 来做到这一点,但对我来说这样做有点复杂,因为我根本不熟悉 wxPython。

因此,如果有人向我展示如何使用 wxPython 和 matplotlib 来显示和更新简单图形的简单示例,我会非常高兴。或者,如果有其他方法可以做到这一点,这对我也有好处。

PS:
好的,因为没有人回答并查看@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()
Run Code Online (Sandbox Code Playgroud)

这个实现有问题,比如如果你试图移动窗口,脚本就会停止。不过基本可以用。

Isa*_*ton 2

作为 matplotlib 的替代品,Chaco 库提供了很好的绘图功能,并且在某些方面更适合实时绘图。

请参阅此处的一些屏幕截图,特别是请参阅以下示例:

Chaco 有 qt 和 wx 的后端,因此大多数时候它可以很好地为您处理底层细节。