如何为圆设置水平动画?

时间:2020-05-23 13:14:01

标签: matplotlib

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

xvalues = np.arange(4000000, 6000000+1000, 1000).tolist()
yvalues = [5000000]*2001

Acc_11 = xvalues
Acc_12 = yvalues

fig = plt.figure(figsize = (5,5))
axes = fig.add_subplot(111)
axes.set_xlim((0, 10000000))
axes.set_ylim((0, 10000000))

point, = plt.Circle((4000000, 5000000), 60000, color = "black")


def ani(coords):
    point.set_data([coords[0]],[coords[1]])
    return point

def frames():
    for acc_11_pos, acc_12_pos in zip(Acc_11, Acc_12):
        yield acc_11_pos, acc_12_pos

ani = FuncAnimation(fig, ani, frames=frames, interval=10)

plt.show()

我收到TypeError:“ Circle”对象不可迭代。我需要做什么?圆的大小必须可变并且与轴有关,所以matplotlib圆是唯一的选择(我想)。

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案(假设您在jupyter笔记本电脑中运行):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

xvalues = np.arange(4000000, 6000000+1000, 1000).tolist()
yvalues = [5000000]*2001

Acc_11 = xvalues
Acc_12 = yvalues

fig = plt.figure(figsize = (5,5))
axes = fig.add_subplot(111)

axes.set_xlim((0, 10000000))
axes.set_ylim((0, 10000000))

point = plt.Circle((4000000, 5000000), 60000, color = "black")

def init():
    point.center = (5, 5)
    axes.add_patch(point)
    return point,

def ani(i):    
    point.center = (Acc_11[i],Acc_12[i])
    return point

anim = FuncAnimation(fig, 
                     ani, 
                     init_func=init, 
                     frames=200, #len(Acc_11), 
                     interval=10)

HTML(anim.to_html5_video())

您可能希望将frames=200更改为frames=len(Acc_11),但要花一些时间才能运行。