我正在尝试使用matplotlib来使多个点沿着它们自己的圆的圆周移动。
我已经能够让一个点沿着一个圆移动,下面是实现这一点的代码:
import numpy as np
import argparse
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# To make the waving flag, we need N dots moving on a circle
# Each subsequent dot is going to be delayed by a slight time, and the last dot should be the same timing as the first dot
r = 3
def circle(phi, phi_off,offset_x, offset_y):
        return np.array([r*np.cos(phi+phi_off), r*np.sin(phi+phi_off)]) + np.array([offset_x, offset_y])
plt.rcParams["figure.figsize"] = 8,6
# create a figure with an axes
fig, ax = plt.subplots()
# set the axes limits
ax.axis([-30,30,-30,30])
# set equal aspect such that the circle is not shown as ellipse
ax.set_aspect("equal")
# create a point in the axes
point, = ax.plot(0,1, marker="o")
def update(phi, phi_off, offset_x,offset_y):
        # obtain point coordinates
        x,y = circle(phi,phi_off, offset_x,offset_y)
        # set point coordinates
        point.set_data([x],[y])
        return point,
ani = animation.FuncAnimation(fig,update,fargs=(0,8*i,0, ), interval = 2, frames=np.linspace(0,2*np.pi,360, endpoint=False))它看起来是这样的:

为了有多个点,我尝试在循环中做ani.append,也就是让它做这样的事情:
i=0
for i in range(3):
    ani.append(animation.FuncAnimation(fig,update,fargs=(0,8*i,0, ), interval = 2, frames=np.linspace(0,2*np.pi,360, endpoint=False)))它看起来是这样的:

关于如何让多个点在自己的圆圈上平滑移动,有什么想法吗?
发布于 2020-04-20 23:46:30
您应该只定义一个更新函数,该函数用于更新所有点:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
r = 3
def circle(phi, phi_off,offset_x, offset_y):
        return np.array([r*np.cos(phi+phi_off), r*np.sin(phi+phi_off)]) + np.array([offset_x, offset_y])
plt.rcParams["figure.figsize"] = 8,6
fig, ax = plt.subplots()
ax.axis([-30,30,-30,30])
ax.set_aspect("equal")
# create initial conditions
phi_offs = [0, np.pi/2, np.pi] 
offset_xs = [0, 0, 0]
offset_ys = [0, 0, 0]
# amount of points
N = len(phi_offs)
# create a point in the axes
points = []
for i in range(N):
  x,y = circle(0, phi_offs[i], offset_xs[i], offset_ys[i])
  points.append(ax.plot(x, y, marker="o")[0])
def update(phi, phi_off, offset_x,offset_y):
        # set point coordinates
        for i in range(N):
          x, y = circle(phi,phi_off[i], offset_x[i], offset_y[i])
          points[i].set_data([x],[y])
        return points
ani = animation.FuncAnimation(fig,update,
      fargs=(phi_offs, offset_xs, offset_ys), 
      interval = 2, 
      frames=np.linspace(0,2*np.pi,360, endpoint=False),
      blit=True)
plt.show()我还添加了blit=True参数,以使动画更流畅、更快(仅更新必要的美工人员),但要小心,在更复杂的动画中可能需要省略此功能。
https://stackoverflow.com/questions/61326186
复制相似问题