在 Matplotlib 中动画甜甜圈

时间:2021-03-23 00:02:32

标签: python matplotlib animation

我正在为一门教学课程制作一个小动画,其中我需要绘制一个沿着轨迹移动的甜甜圈。但是,我遇到了 funcAnimation 问题,因为我无法使用 blit 来刷新位置。这是我的带有示例数据集的代码

 import numpy as np

 
 x1 = np.random.randint(1,101,10)
 y1 = np.random.randint(1,101,10)

动画本身由

完成
%matplotlib inline  

import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML



fig, ax = plt.subplots()

def make_circle(r,x_c,y_c):
    t = np.arange(0, np.pi * 2.0, 0.01)
    t = t.reshape((len(t), 1))
    x = r * np.cos(t) + x_c
    y = r * np.sin(t) + y_c
    return np.hstack((x, y))

def draw_donut(r_o,r_i,x_c,y_c):
    Path = mpath.Path
    inside_vertices = make_circle(r_i,x_c,y_c)
    outside_vertices = make_circle(r_o,x_c,y_c)
    codes = np.ones(len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
    codes[0] = mpath.Path.MOVETO
    vertices = np.concatenate((outside_vertices[::1],inside_vertices[::-1]))
    all_codes = np.concatenate((codes, codes))
    path = mpath.Path(vertices, all_codes)
    patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
    return patch

def animate(i):
    return ax.add_patch(draw_donut(10,5,x1[i],y1[i]))

anim = animation.FuncAnimation(fig, animate, frames = 10, interval=100, blit = False)

ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)
ax.set_aspect(1.0)

HTML(anim.to_jshtml())  

如果我设置了 blit = True,我会收到错误

TypeError: 'PathPatch' object is not iterable

blit = False 只是继续绘制更多的甜甜圈。知道如何解决这个问题吗?

0 个答案:

没有答案
相关问题