gpt4 book ai didi

python - 如何使用 matplotlib 在 Python 中为沿圆周移动的多个点设置动画?

转载 作者:行者123 更新时间:2023-12-04 10:11:11 24 4
gpt4 key购买 nike

我正在尝试使用 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))

它看起来像这样:

single moving dot in circle

为了有多个点,我尝试在循环中执行 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)))

这是它的样子:

multiple moving dots

关于如何让多个点在自己的圆上平滑移动的任何想法?

最佳答案

你应该只定义一个更新函数,它更新所有点:

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参数使动画更流畅和更快(只有必要的艺术家会被更新)但要小心,你可能不得不在更复杂的动画中省略这个功能。

关于python - 如何使用 matplotlib 在 Python 中为沿圆周移动的多个点设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61326186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com