如何为围绕圆的圆周移动的点设置动画?

时间:2018-07-11 13:15:56

标签: python matplotlib

使用此代码,如何为一个点设置动画以跟踪圆?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1.0, 1.0, 100)
y = np.linspace(-1.0, 1.0, 100)
X, Y = np.meshgrid(x,y)
F = X**2 + Y**2 - 0.6
plt.contour(X,Y,F,[0])
plt.gca().set_aspect('equal')
plt.show()

我需要它看起来像this。 (很抱歉,找不到更好的动画来描述我想要的东西)。我要描述的点将是月亮绕其旋转的圆的中心点。

1 个答案:

答案 0 :(得分:1)

您需要参数化圆,以便每个时间步在该圆上给出不同的坐标。最好在极坐标中完成此操作,在该坐标中,角度直接为您提供了变化的参数。

r = 1 # radius of circle
def circle(phi):
    return np.array([r*np.cos(phi), r*np.sin(phi)])

然后,您需要设置一个matplotlib图形和轴并定义一个更新函数,如果调用该函数,则将点的位置设置为从上述circle函数接收的值。 然后,您可以通过FuncAnimation为整个动画制作动画,该动画反复调用该更新函数。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 4,3
from matplotlib.animation import FuncAnimation

r = 1 # radius of circle
def circle(phi):
    return np.array([r*np.cos(phi), r*np.sin(phi)])

# create a figure with an axes
fig, ax = plt.subplots()
# set the axes limits
ax.axis([-1.5,1.5,-1.5,1.5])
# 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")

# Updating function, to be repeatedly called by the animation
def update(phi):
    # obtain point coordinates 
    x,y = circle(phi)
    # set point's coordinates
    point.set_data([x],[y])
    return point,

# create animation with 10ms interval, which is repeated,
# provide the full circle (0,2pi) as parameters
ani = FuncAnimation(fig, update, interval=10, blit=True, repeat=True,
                    frames=np.linspace(0,2*np.pi,360, endpoint=False))

plt.show()

enter image description here