使用 MatPlotLib 绘制连续的数据流

Kar*_*rus 2 python matplotlib

我想使用 MatPlotLib 绘制图形,其中的图形随时间变化。在每个时间步,一个额外的数据点将被添加到图中。但是,应该只显示一个图形,其外观会随着时间的推移而演变。

在我的测试示例中,该图是一个简单的线性图 (y = x)。这是我尝试过的:

for i in range(100):
    x = range(i)
    y = range(i)
    plt.plot(x, y)
    plt.ion()
    plt.show()
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

但是,这里发生的是创建了多个窗口,因此在循环结束时我有 100 个窗口。另外,我注意到对于最近的窗口,它只是一个白色的窗口,并且情节只出现在下一步中。

所以,我的两个问题是:

1) 如何更改我的代码,以便只显示一个窗口,其内容会随着时间而变化?

2)如何更改我的代码,以便在最近的时间步长中,绘图实际显示在窗口上,而不是只显示一个白色窗口?

谢谢!

Imp*_*est 6

(1)

您可以plt.ion()在开始时设置并将所有图形绘制到同一窗口。在循环中使用plt.draw()来显示图形并plt.pause(t)暂停。请注意,t它可能非常小,但该命令需要存在,动画才能在大多数后端工作。
您可能希望在使用 绘制新内容之前清除轴plt.gca().cla()

import matplotlib.pyplot as plt

plt.ion()
for i in range(100):
    x = range(i)
    y = range(i)
    # plt.gca().cla() # optionally clear axes
    plt.plot(x, y)
    plt.title(str(i))
    plt.draw()
    plt.pause(0.1)

plt.show(block=True) # block=True lets the window stay open at the end of the animation.
Run Code Online (Sandbox Code Playgroud)

替代这种非常简单的方法,使用http://matplotlib.org/examples/animation/index.html 中提供的任何动画示例

(2)

为了在新窗口中获取每个图,请使用plt.figure()并删除plt.ion(). 也只显示最后的窗口:

import matplotlib.pyplot as plt

for i in range(100):
    x = range(i)
    y = range(i)
    plt.figure()
    plt.plot(x, y)
    plt.title(str(i))
    
plt.show()
Run Code Online (Sandbox Code Playgroud)

请注意,你可能会发现,在这两种情况下,第一个图是空的,只是因为对i=0range(i) == []是没有任何点空单。即使i=1只绘制了一个点,但当然没有一条线可以将单个点与其自身连接起来。