【问题标题】:Matplotlib - How can I animate change of line as slope and intercept changeMatplotlib - 如何将线的变化动画化为斜率和截距变化
【发布时间】:2017-06-13 13:54:38
【问题描述】:

我正在使用梯度体面的线性回归将值拟合到一条线。在每次迭代中,这条线越来越接近最佳拟合。

现在我只显示最后一行。但我想说明随着迭代的进行,这条线如何越来越好地拟合数据。

我查看了一些示例,但它们似乎只是在现有线中添加新的 x,y 点。每次迭代我都想删除旧线,并用最新数据绘制一条新线。

有什么想法吗?

【问题讨论】:

  • 您可以替换绘图中的所有数据 - Matplotlib 页面上甚至还有示例:matplotlib.org/1.5.1/examples/animation/simple_anim.html
  • matplotlib 中有an example on how to use FuncAnimation。在每个迭代步骤中向一行添加一个新值或向该行添加所有新值之间没有区别。所以这个例子对你的情况完全有效。如果您有具体问题,您应该提供minimal reproducible example,因为没有任何代码和/或详细说明,无法为您提供帮助。
  • 谢谢大家。我看到了我的错误。我从提到的示例 furas 开始,但误解了他们在 animate() 中所做的事情

标签: python animation matplotlib


【解决方案1】:

使用上面提供的提示,我创建了这个示例代码,向我展示了如何在 Jupyter Notebook 中为拟合设置动画。它既有固定数据也有动画数据。

%matplotlib notebook
# A simple example of an animated plot
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

# Initial plot
x = np.arange(0., 10., 0.2)
y = np.arange(0., 10., 0.2)
line, = ax.plot(x, y)

plt.rcParams["figure.figsize"] = (10,8)
plt.ylabel("Price")
plt.xlabel("Size (sq.ft)")
plt.plot([1, 1.2, 3], [3, 3.5, 4.7], 'go', label='Training data')
#ax.plot(test_house_size, test_house_price, 'mo', label='Testing data')

def animate(i):
    print(i)    
    x = np.arange(0., 6, 0.05)
    line.set_xdata(x)  # update the data
    line.set_ydata( x ** (1 + (i/10.0)))  # update the data

    return line,


# Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(y)
    return line,

ani = animation.FuncAnimation(fig, animate, frames=np.arange(1, 10), init_func=init, interval=1000, blit=True)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-17
    • 2021-09-06
    • 2010-11-30
    • 1970-01-01
    • 2018-04-30
    • 2022-08-06
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多