如何在 matplotlib 图中为旋转 link 设置动画?

How do I animate a rotating link in matplotlib plot?

我会把问题简单化。

假设我有一个长度为 15 个单位的 link,我想让它在 matplotlib 图中动画化,因为 theta 的值(link 和 x 轴之间的角度)从0 到 90 度。 link 应该围绕 (0,0) 坐标旋转,即 link 固定在 (0,0) 坐标。

显然会应用三角法则求 link 另一端的坐标,而一端固定在 (0,0) 坐标。

我只想使用纯 matplotlib 和 numpy 模块。

您可能已经知道,matplotlib 提供了对动画的内置支持。 FuncAnimation class 是原生 matplotlib 动画最简单的接口。

%matplotlib widget
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np

fig = plt.figure()
ax = plt.subplot(111, projection='polar')

class LinkAnimator:
    # Also check this example from the official documentation for this pattern:
    # https://matplotlib.org/3.3.3/gallery/animation/bayes_update.html

    def __init__(self, ax, link_size=15):
        self._ax = ax
        self._link_size = link_size
        self._link = self._ax.plot([0, 0], [0, 15], lw=1.5)[0]
        
    def __call__(self, theta):
        self._link.set_data([theta] * 2, [0, 15])
        return self._link
    
animator = LinkAnimator(ax, link_size=15)
theta = np.linspace(0, np.pi / 2, 91)
anim = FuncAnimation(fig, animator, frames=theta, blit=True, repeat=False)

# if you want to export the animation as a gif
writer = PillowWriter(fps=25)
anim.save('/tmp/link-anim.gif', writer=writer)

# this shall display your animation in the notebook
plt.show()

冒昧使用极坐标。如果您对此不熟悉,请查看官方文档中的 this 示例。

用户指南: https://matplotlib.org/3.3.3/api/animation_api.html#funcanimation

以上代码生成的内容如下: