【问题标题】:Matplotlib animation not adding the counter from inside the animate functionMatplotlib 动画未从动画函数内部添加计数器
【发布时间】:2019-11-03 13:11:34
【问题描述】:

我不明白为什么 de animate 函数中的计数器没有被添加到自身。

我尝试使用动画来打印两个值列表的新值,每个值每个轴,每秒一个。

已编辑:代码:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 12, 10, 1, 5, 3, 5, 7, 4, 4]

x_vals = []
y_vals = []

cnt = 0
def animate(i, cnt):
    print(cnt)
    print('loop ' + str(cnt))

    x_vals.append(x[cnt])
    y_vals.append(y[cnt])

    print(x_vals, y_vals)
    cnt += 1  # this is not happening
    plt.plot(x_vals, y_vals, label='Price')

ani = FuncAnimation(plt.gcf(), animate, fargs=(cnt,), interval=1000)

# plt.tight_layout()
plt.show()

我在 animate 函数之外声明 cnt 并得到此输出(感谢PartialOrder 用户):

0
loop 0
[1] [1]
0
loop 0
[1, 1] [1, 1]
0
loop 0
[1, 1, 1] [1, 1, 1]
....

这表明 animate 函数中的循环每秒执行一次,但由于在每个循环中重置为零,因此未添加计数器。 如果在函数之前声明 cnt 计数器(未传入参数),我得到:

File "test3.py", line 13, in animate
    print('loop ' + str(cnt))
UnboundLocalError: local variable 'cnt' referenced before assignment

我得到一个空图的两种方式:

enter image description here

为什么没有添加计数器,以及如何将外部计数器传递给函数?

谢谢!

【问题讨论】:

  • 您在每次调用 animate 时重新初始化 cnt
  • 是的,但是如果我在分配之前声明会出错..我将编辑以发布使用的所有其他代码
  • 您可以使用 fargs 将其他参数传递给 FuncAnimation。例如,ani = FuncAnimation(plt.gcf(), animate, fargs=(cnt,), interval=1000)。见:matplotlib.org/3.1.1/api/_as_gen/…
  • 阅读“python中的全局变量”。

标签: python matplotlib data-science


【解决方案1】:

是的!!!!...全球工作!谢谢!!! @ImportanceOfBeingErnest

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 12, 10, 1, 5, 3, 5, 7, 4, 4]

x_vals = []
y_vals = []

cnt = 0
def animate(i):
    global cnt
    if cnt == 10:
        exit('Finished')
    print('loop ' + str(cnt))

    x_vals.append(x[cnt])
    y_vals.append(y[cnt])

    print(x_vals, y_vals)
    cnt += 1  # this is not happening
    plt.plot(x_vals, y_vals, label='Price')

ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2015-04-29
    • 2014-10-14
    • 1970-01-01
    相关资源
    最近更新 更多