【问题标题】:Python: animate FancyArrows with matplotlib.animation.FuncAnimationPython:使用 matplotlib.animation.FuncAnimation 为 FancyArrows 设置动画
【发布时间】:2022-11-09 18:55:13
【问题描述】:

我正在尝试获取一个 Python 脚本来可视化 N 个箭头(代表电机中的 N 个相)。 我有一种解决方案,但是在运行代码和动画之后,Python 崩溃了。

这不是严重错误,但将来可能会出现。顺便说一句,任何关于代码的建议都将不胜感激。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.collections as collections


#define the specfications of fasors
t=np.linspace(0,1/50,100)
Iamp=10
f=50
  
N=7
PHIs=[2*np.pi*n/N for n in range(N)]

#PHASOR BUILDER:
def build_Phasor(t,phi0):
    return {"dx":Iamp*np.cos(2*np.pi*f*t+phi0),
            "dy":Iamp*np.sin(2*np.pi*f*t+phi0)}


#DEFINE GRAPHICAL 

fig = plt.figure()    
ax = fig.gca()

ax.set_ylim(top=Iamp,bottom=-Iamp)  # set safe limit to ensure that all data is visible.
ax.set_xlim(right=Iamp,left=-Iamp)  # set safe limit to ensure that all data is visible.
plt.gca().set_aspect('equal', adjustable='box')


arrows=[plt.arrow  (0,0,
                        build_Phasor(t=0,phi0=phi)["dx"],
                        build_Phasor(t=0,phi0=phi)["dy"],
                        head_width=10/30,  head_length=10/10,
                        length_includes_head=True,   animated=False)
            for phi in PHIs]
collection=collections.PatchCollection(arrows)
ax.add_collection(collection)




def animate(t):
    ax.patches.clear()
    arrows=[(  plt.arrow(0, 0,
                            dx=(Iamp*np.cos(2*np.pi*f*t+phi)),  dy=(Iamp*np.sin(2*np.pi*f*t+phi)),  #what if I call buid_Fasor() here?
                            head_width=10/30,  head_length=10/10,
                            length_includes_head=True,   animated=False)) for phi in PHIs]

    # collection.set_paths(arrows)   ## why do i get an output with this line commented?




anim = animation.FuncAnimation(fig, animate, 
                               interval=150, frames=t,
                               )

plt.show()

【问题讨论】:

    标签: python matplotlib animation patch


    【解决方案1】:

    经过一番抓挠,我得到了正确的答案。 问题出现在这里:

    def animate(t):
    ax.patches.clear()
    arrows=[(  plt.arrow(0, 0,
                            dx=(Iamp*np.cos(2*np.pi*f*t+phi)),  dy=(Iamp*np.sin(2*np.pi*f*t+phi)),  #what if I call buid_Fasor() here?
                            head_width=10/30,  head_length=10/10,
                            length_includes_head=True,   animated=False)) for phi in PHIs]
    

    命令 plt.arrow()=matplotlib.pyplot.arrow() 是一种生成 FancyArrow 对象(补丁)和添加把它砍成斧头。 Reference

    正确的方法是生成箭头通过one command,和将其添加到目标轴another command

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多