代码崩溃是因为您以错误的方式“混合”了matplotlib的“pyplot”和“面向对象”方法。这是工作代码。请注意,我创建了
ax
,将要添加艺术家的轴。在这个轴上,我还应用了轴限制。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Circle
N = 360
df = pd.DataFrame({
"x1": np.linspace(0, 60, N),
"y1": np.linspace(0, 60, N),
"x2": np.flip(np.linspace(0, 60, N)),
"y2": np.linspace(0, 60, N),
})
fig = plt.figure()
ax = fig.add_subplot()
ax.set_xlim(0, 60)
ax.set_ylim(0, 60)
patch = Circle((5, -5), 6, fc='y')
patch2 = Circle((5, -5), 6, fc='y')
ax.add_artist(patch)
ax.add_artist(patch2)
def init():
patch.center = (df["x1"][0], df["y1"][0])
patch2.center = (df["x2"][0], df["y2"][0])
return patch, patch2
def animate(i):
x, y = patch.center
x2, y2 = patch2.center
x = df["x1"][i]
y = df["y1"][i]
x2 = df["x2"][i]
y2 = df["y2"][i]
patch.center = (x, y)
patch2.center = (x2, y2)
i += 1
return patch, patch2,
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=N,
interval=20,
blit=True)
plt.show()