在matplotlib中刷新图

问题描述

作为显示线性回归模型拟合的过程的一部分,我需要能够更新/刷新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()

解决方法

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

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

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,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()