微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 matplotlib 图中为旋转链接设置动画?

我会让问题简单化。

假设我有一个长度为 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

以上代码生成的内容如下: Here's what the above code generates

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。