我的程序中的特定数据点保持不变。我试图通过迭代更新来填充数据。我想看看在更新此行的参数时线条如何变化(移动)。
具体而言,我正在做渐变下降,我试图看看每个更新如何改变线的角度和位置以最佳地适合数据。
现在我明白了:
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
plt.show()
正如你所看到的,我也很难画出连续的线条。现在我需要更新红线。有任何想法吗? thetas[0]
和thetas[1]
是for循环中的更新,之后需要更新绘图。
答案 0 :(得分:3)
您需要使用matplotlib的交互模式(请参阅documentation)。
特别是,您需要使用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()
答案 1 :(得分:1)
好像你正在寻找动画。您需要重新排列代码
所以你可以使用matplotlib.animation.FuncAnimation
。
这是一个基本的例子: http://matplotlib.org/examples/animation/animate_decay.html