我正在尝试获得一个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()
发布于 2022-11-09 10:55:13
经过一番刮擦,我得到了正确的答案。问题就出现在这里:
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对象(修补程序)并将添加到axe中的方法。参考文献
绘制FancyArrows对象的正确方法是通过一条命令生成箭头,将其添加到带有另一条命令的目标轴中。
为了动画,每次运行animation.FuncAnimation时,我们都必须安全地修改每个箭头的参数。
箭一代:
def graph_initial_plot():
for i,phase in enumerate(CarthesianLocus_Phases):
ax[0,1].add_patch(patches.FancyArrow(0, 0, phase.phasor.dx, phase.phasor.dy,
head_width = 10/30, head_length = 10/10, width=.1,
length_includes_head = True, color = colour_list[i]))
箭旋转
def animations(t):
def phasor_rotation(t):
for i,arrow in enumerate(ax[0,1].patches):
phase=CarthesianLocus_Phases[i]
arrow.set_data(dx=phase.phasor.dx, dy=phase.phasor.dy)
def wave_displacement(t):
for i,phase in enumerate(CarthesianLocus_Phases):
ax[0,0].lines[i].set_data(phase.wave.t,phase.wave.y)
#we get horizontal waveforms,
#we need to add points to the line (or redefine line)
calculate_next_point(t)
phasor_rotation(t)
wave_displacement(t)
https://stackoverflow.com/questions/74239686
复制相似问题