【问题标题】:Matplotlib pyplot in real timeMatplotlib pyplot 实时
【发布时间】:2014-06-26 23:02:13
【问题描述】:

我有一个生成两个数字列表的 while 函数,最后我使用 matplotlib.pyplot 绘制它们。

我在做

while True:
    #....
    plt.plot(list1)
    plt.plot(list2)
    plt.show()

但为了查看进度,我必须关闭绘图窗口。 有没有办法每 x 秒用新数据刷新一次?

【问题讨论】:

    标签: python graph matplotlib plot


    【解决方案1】:

    做你想做的最可靠的方法是使用matplotlib.animation。下面是动画两条线的示例,一条代表正弦,一条代表余弦。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    fig, ax = plt.subplots()
    sin_l, = ax.plot(np.sin(0))
    cos_l, = ax.plot(np.cos(0))
    ax.set_ylim(-1, 1)
    ax.set_xlim(0, 5)
    dx = 0.1
    
    def update(i):
        # i is a counter for each frame.
        # We'll increment x by dx each frame.
        x = np.arange(0, i) * dx
        sin_l.set_data(x, np.sin(x))
        cos_l.set_data(x, np.cos(x))
        return sin_l, cos_l
    
    ani = animation.FuncAnimation(fig, update, frames=51, interval=50)
    plt.show()
    

    对于您的特定示例,您将摆脱 while True 并将逻辑放在 update 函数中的 while 循环中。然后,您只需确保拨打set_data 而不是拨打全新的plt.plot 电话。

    更多详情请见this nice blog postthe animation APIthe animation examples

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是“动画”功能。

      这里是an example

      This example 是第二个。

      【讨论】:

        猜你喜欢
        • 2017-02-28
        • 1970-01-01
        • 1970-01-01
        • 2015-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多