问题描述
我会让问题简单化。
假设我有一个长度为 15 个单位的链接,我想让它在 matplotlib 图中动画化,因为 theta(链接和 x 轴之间的角度)的值在 0 到 90 度之间变化。链接应围绕 (0,0) 坐标旋转,即链接固定在 (0,0) 坐标处。
显然,将应用三角规则来找到链接另一端的坐标,而一端固定在 (0,0) 坐标处。
我只想使用纯粹的 matplotlib 和 numpy 模块。
解决方法
您可能已经知道,matplotlib 提供对动画的内置支持。 FuncAnimation
类是原生 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,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