繁体   English   中英

FuncAnimation 被调用太多次

[英]FuncAnimation being called too many times

这是我之前问过的一个问题的延续。 我注意到用于更新饼图的值不正确。 我有一个列表z ,它正在我的 FuncAnimation 函数中使用num迭代器更新,该函数名为update 这是我正在使用的代码:

import numpy as np
import matplotlib.animation as animation
from matplotlib import pyplot as plt 

numbers = [[6.166, 5.976, 3.504, 7.104, 5.14],
 [7.472, 5.888, 3.264, 6.4825, 7.168],
 [7.5716, 9.936, 3.6, 8.536, 2.808],
 [2.604, 2.296, 0.0, 6.144, 4.836],
 [7.192, 4.932, 0.0, 6.016, 8.808],
 [7.192, 5.5755, 3.694, 9.376, 9.108],
 [7.63616, 5.912, 3.968, 6.672, 3.192],
 [3.41049, 5.44, 4.004, 7.212, 3.6954],
 [4.3143, 6.364, 3.584, 7.44, 5.78],
 [4.992, 3.9692, 4.272, 0.0, 2.528]]
numbers = np.array(numbers)

colors = ["yellow", "red", "purple", "blue", "green"]
explode = [0.01, 0.01, 0.01, 0.01, 0.01]
labels = ["DM", "Bard", "Warlock", "Paladin", "Ranger"]
z = np.array([0,0,0,0,0]).astype(np.float)

fig,ax = plt.subplots()
y = []
def update(num):
    global y
    global z
    ax.clear()
    ax.axis('equal')     
    z += numbers[num]
    y.append(z)
    
    #output of different vairables#
    print(num, z, sum(z), len(y))

    pie = ax.pie(z, explode=explode, labels=labels, colors=colors, 
                 autopct='%1.1f%%', shadow=True, startangle=140)
    ax.set_title(sum(z))    
    
ani = animation.FuncAnimation(fig, update, frames=range(10), repeat=False)
ani.save('test.gif', writer='pillow', fps=1)

print()函数的输出如下所示:

0 [6.166 5.976 3.504 7.104 5.14 ] 27.89 1
0 [12.332 11.952  7.008 14.208 10.28 ] 55.78 2
1 [19.804  17.84   10.272  20.6905 17.448 ] 86.05450000000002 3
2 [27.3756 27.776  13.872  29.2265 20.256 ] 118.5061 4
3 [29.9796 30.072  13.872  35.3705 25.092 ] 134.3861 5
4 [37.1716 35.004  13.872  41.3865 33.9   ] 161.3341 6
5 [44.3636 40.5795 17.566  50.7625 43.008 ] 196.27959999999996 7
6 [51.99976 46.4915  21.534   57.4345  46.2    ] 223.65975999999995 8
7 [55.41025 51.9315  25.538   64.6465  49.8954 ] 247.42165 9
8 [59.72455 58.2955  29.122   72.0865  55.6754 ] 274.90395 10
9 [64.71655 62.2647  33.394   72.0865  58.2034 ] 290.66515 11
0 [70.88255 68.2407  36.898   79.1905  63.3434 ] 318.55514999999997 12

打印输出显示在num迭代器增加 1之前numbers[0]被添加到自身。之后,它按预期工作,将numbers[1]numbers[9]加在一起。 但同样,由于某种原因, numbers[0]被添加到numbers[9]

生成的 gif 的第一帧显示此数据: [12.332 11.952 7.008 14.208 10.28 ] 55.78和最后一帧显示此数据: [64.71655 62.2647 33.394 72.0865 58.2034 ] 290.66515停止循环[64.71655 62.2647 33.394 72.0865 58.2034 ] 290.66515中的 5 是可以的。

我想知道在这种情况下我做错了什么; 如何纠正num的意外行为?

如果没有init_func=传递给FuncAnimation ,它将使用动画函数本身作为初始状态,这会导致您的 doublet 0 该文件指出

init_func : 可调用,可选

用于绘制清晰框架的函数。 如果未给出,则将使用从帧序列中的第一项绘制的结果。 此函数将在第一帧之前调用一次。

您可以简单地传递一个空函数来解决问题。

def init():
    pass

(...)

ani = animation.FuncAnimation(fig, update, frames=range(10), init_func=init, repeat=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM