matplotlib 如何在已经计算好的图形上画点动画

6gpjuf90  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(134)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)

x, y = [], []
line, = plt.plot([], [], 'bo')
circle = plt.Circle((0,0), 1, color = 'g', fill = False,)

def update(frame):
    x.append(np.cos(frame))
    y.append(np.sin(frame))
    line.set_data(x, y)
    return circle, line,

ani = FuncAnimation(fig, update, frames= np.linspace(0, 2*np.pi, 128), interval = 0.1)
plt.show()

what I want to animate
我试着通过上面的代码来动画匀速圆周运动,但是我只能看到圆点在移动,而看不到圆点下面的圆。我怎么能在动画圆点的同时画圆呢?

qyyhg6bp

qyyhg6bp1#

您可以使用ax.add_artist(circle)将圆圈添加到艺术家。
另外,我重写了update函数,使其只跟踪当前点。
参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.add_artist.html

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

fig, ax = plt.subplots(figsize=(5, 5))

radius = 2

ax.set_xlim(-radius * 1.05, radius * 1.05)
ax.set_ylim(-radius * 1.05, radius * 1.05)

line, = plt.plot([], [], 'bo')
circle = plt.Circle((0, 0), radius, color='k', fill=False)
red_dot = plt.plot(0, 0, 'ro')

ax.set_aspect('equal')
ax.add_artist(circle)
ax.set_axis_off()

def update(i):
    theta = np.deg2rad(i)
    x = [0, radius * np.cos(theta)]
    y = [0, radius * np.sin(theta)]
    line.set_data(x, y)

ani = FuncAnimation(fig, update, frames=360, interval=30)
ani.save('fig_1.gif', writer='pillow', fps=45)

plt.show()

相关问题