【问题标题】:Python FuncAnimation not recognizing updatePython FuncAnimation 无法识别更新
【发布时间】:2016-08-23 18:09:52
【问题描述】:

我正在学习如何在 python 中为我的一个项目制作动画,并且我的代码基于来自here 的以下示例。

我对他们的代码的改编如下:

import numpy as np
import h5py, os, glob, sys, time
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def update(i):
    for j in np.arange(0,10):
        for k in np.arange(0,10):
            for channel in ["N","E"]:
                x = some_x_value
                y = some_y_value
                line = plt.loglog(x,y)
                ax.set_xlabel(label)
    return line, ax


if __name__ == "__main__":
    fig, ax = plt.subplots()
    anim = FuncAnimation(fig, update, frames=np.arange(0,10), interval=200)
    anim.save('Test.gif', dpi=80, writer='imagemagick')

当我尝试运行我的脚本时,我收到以下错误: 名称错误:未定义名称“更新”。

正如我之前所说,我仍在学习如何制作动画,并不了解我找到的代码教程中的所有内容。但是,我很困惑为什么根本无法识别 update,因为我调用 update 的方式似乎与教程中的完全相同。

【问题讨论】:

  • 里面还有一堆其他未定义的名字(比如ssPlot)。
  • @tcaswell 我没有发布我定义的所有函数,因为我不想弄乱我的问题,但是像 ssPlot 这样的东西已经在其他地方为我定义了,并且以前运行良好。现在只是更新返回名称错误。
  • 您能否将示例简化为演示您所问问题的代码?
  • 并且可以被其他开发者复制粘贴运行。
  • @tcaswell 我压缩了我的代码。 Python 不想在 FuncAnimation 中调用 update 时识别它,即使我在上面(简化)代码中定义了它。

标签: python animation matplotlib


【解决方案1】:
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


def update(i, ln):
    i = i+1
    x = i
    y = i ** 2
    x_data = ln.get_xdata()
    y_data = ln.get_ydata()
    ln.set_data(np.concatenate(([x], x_data)),
                np.concatenate(([y], y_data)))
    return ln


if __name__ == "__main__":
    fig, ax = plt.subplots()
    ax.set_xlim(1, 10)
    ax.set_ylim(1, 100)
    line, = ax.loglog([1], [1])
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200,
                         fargs=(line, ))
    anim.save('Test.gif', dpi=80, writer='imagemagick')

按预期工作。这让我觉得您的代码中还有其他一些错误被掩盖了。

【讨论】:

  • 我成功地重新创建了教程示例,但仍然无法让我的实际代码生成动画。我将回顾我的代码并尝试逐步对其进行逆向工程。感谢您调查我的问题。
猜你喜欢
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
相关资源
最近更新 更多