【问题标题】:Refreshing plot in matplotlibmatplotlib 中的刷新图
【发布时间】:2020-11-10 10:20:20
【问题描述】:

作为显示线性回归模型拟合进展的一部分,我需要能够更新/刷新 xy 图。下面是 3 组 y 数据的简单脚本,需要按顺序显示。但是,它们是堆叠在一起的。当 fig.canvas.flush_events() 被 fig.clear() 或 fig.clf() 替换时,结果是一个空白图。我 - 作为一个新手 - 缺少什么?

import torch as tc
import matplotlib.pyplot as plt

tc.manual_seed(1)

X=tc.linspace(-3,3,30)

y0=X.pow(2)+0.5*tc.randn(X.shape[0])
y1=y0/1.3
y2=y0/1.6

y=[y0,y1,y2]


fig=plt.figure()
ax=fig.add_subplot()
ax.set_xlim(-3.3,3.3)
ax.set_ylim(-0.5,9.5)

for i in range(3):
    y_new=y[i]
    ax.plot(X,y_new,'db')
    fig.canvas.draw()
    fig.canvas.flush_events()
    plt.pause(1)

fig.show()

【问题讨论】:

    标签: matplotlib linear-regression real-time


    【解决方案1】:

    在您的循环中,每次调用ax.plot 时都会创建一个新行。更好的方法是创建 Line2D 艺术家并更新循环中点的坐标:

    (注意,我已将您的示例转换为使用 numpy 而不是 torch)

    import matplotlib.pyplot as plt
    import numpy as np
    
    X = np.linspace(-3, 3, 30)
    
    y0 = np.power(X, 2) + 0.5 * np.random.randn(X.shape[0])
    y1 = y0 / 1.3
    y2 = y0 / 1.6
    
    y = [y0, y1, y2]
    
    fig = plt.figure()
    ax = fig.add_subplot()
    l, = ax.plot(X, y0, 'db')
    ax.set_xlim(-3.3, 3.3)
    ax.set_ylim(-0.5, 9.5)
    
    
    for i in range(3):
        y_new = y[i]
        l.set_ydata(y_new)
        fig.canvas.draw()
        plt.pause(1)
    
    plt.show()
    

    对于这种事情,你最好使用 maptlotlib 提供的 FuncAnimation 模块:

    import matplotlib.pyplot as plt
    from matplotlib import animation
    import numpy as np
    
    X = np.linspace(-3, 3, 30)
    
    y0 = np.power(X, 2) + 0.5 * np.random.randn(X.shape[0])
    y1 = y0 / 1.3
    y2 = y0 / 1.6
    
    y = [y0, y1, y2]
    
    fig = plt.figure()
    ax = fig.add_subplot()
    l, = ax.plot(X, y0, 'db')
    ax.set_xlim(-3.3, 3.3)
    ax.set_ylim(-0.5, 9.5)
    
    
    def animate(y_new):
        l.set_ydata(y_new)
        return l,
    
    
    ani = animation.FuncAnimation(fig, func=animate, frames=y, interval=1000)
    fig.show()
    

    【讨论】:

    • 非常感谢 Diziet。您关于创建新行的评论(将添加到之前的行之上)是黄金!我现在意识到我的愚蠢。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2011-01-27
    相关资源
    最近更新 更多