Python 更新matplotlib中的行循环打印

Python 更新matplotlib中的行循环打印,python,matplotlib,Python,Matplotlib,在我的程序中,您有保持不变的特定数据点。我试图通过迭代更新来适应贯穿数据的行。我想看看在更新这条线的参数时,这条线是如何变化(移动)的 具体来说,我在做梯度下降,我试图看到每次更新如何改变角度和线的位置,以最适合的数据 现在我知道了: fig = plt.figure() ax1 = fig.add_subplot(211) ax1.scatter(xs, ys) plt.plot(xs, thetas[0] + thetas[1] * xs, color='red') plt.show()

在我的程序中,您有保持不变的特定数据点。我试图通过迭代更新来适应贯穿数据的行。我想看看在更新这条线的参数时,这条线是如何变化(移动)的

具体来说,我在做梯度下降,我试图看到每次更新如何改变角度和线的位置,以最适合的数据

现在我知道了:

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
plt.show()
其结果如下:


正如你所看到的,我也很难画出一条连续的线。现在我需要更新红线。有什么想法吗<代码>θ[0]和
θ[1]
是for循环中的更新,之后还需要更新绘图。

您需要使用matplotlib的交互模式(请参阅)

特别是,您需要使用plt.ion()打开交互模式,使用fig.canvas.draw()使用最新更改更新画布,使用ax.clear()删除以前绘制的内容

您的代码如下所示:

plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Draw.
fig.canvas.draw()

# Do your updates on thetas.
# ...

# Clear the current plot.
ax1.clear()
# Plot your data again.
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Update the figure.
fig.canvas.draw()

您需要使用matplotlib的交互模式(请参见)

特别是,您需要使用plt.ion()打开交互模式,使用fig.canvas.draw()使用最新更改更新画布,使用ax.clear()删除以前绘制的内容

您的代码如下所示:

plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Draw.
fig.canvas.draw()

# Do your updates on thetas.
# ...

# Clear the current plot.
ax1.clear()
# Plot your data again.
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Update the figure.
fig.canvas.draw()

看起来你在找动画。你需要重新排列你的代码 因此,您可以使用
matplotlib.animation.FuncAnimation

这是一个基本的例子:

您似乎在寻找动画。你需要重新排列你的代码 因此,您可以使用
matplotlib.animation.FuncAnimation

这是一个基本的例子: