我正在尝试为圆弧和圆圈设置动画。圆圈每帧移动。当弧线正在改变半径,位置和消失作为圆圈位置的函数。
我试图动画这些弧,但它们没有改变。
以下是代码示例:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import patches
import numpy as np
particle_one = np.zeros((10,2)) #10 times steps and x,y positions
particle_two = np.zeros((10,2)) #10 times steps and x,y positions
#the two particles are moving away from each other in the x direction
for i in range(0,10):
particle_one[i,0] = i
particle_two[i,0] = 2-i
particle_one[i,1] = 2
particle_two[i,1] = -2
particle_One_Radius = 1
particle_Two_Radius = 1.5
arc_Center = np.zeros((10,2))
for i in range(0,10):
arc_Center[i,0] = (particle_one[i,0] + particle_two[i,0])/2
#the arc should disappear for frame 5
arc_Center[5,0] = 0
arc_Center[5,1] = 0
fig = plt.figure()
plt.axis([-20,20, -5,5]) #axis that I like
ax = plt.gca()
circle_One = plt.Circle([particle_one[0,0],particle_one[0,1]],particle_One_Radius)
circle_Two = plt.Circle([particle_two[0,0],particle_two[0,1]],particle_Two_Radius)
circles = []
circles.append(circle_One)
circles.append(circle_Two)
arcs = []
#defines the arc
arc_one = patches.Arc([arc_Center[0,0],arc_Center[0,1]],5,3,angle =0 ,theta1 = 0,theta2= 270)
arcs.append(arc_one)
def init():
ax.add_patch(circles[0])
ax.add_patch(circles[1])
ax.add_patch(arcs[0])
return ax
#draw every frame by frame
def animate(m):
circles[0].center=((particle_one[m,0],particle_one[m,1]))
circles[1].center=((particle_two[m,0],particle_two[m,1]))
#the arcs does not change
arcs[0] =patches.Arc([arc_Center[m,0],arc_Center[m,1]],5+m,3+m,angle =0 ,theta1 = 0,theta2= 270)
return ax
#animation function that draws 10 frames
anim = animation.FuncAnimation(fig,animate , init_func= init , frames = 10 , interval = 20)
plt.show()
圆圈正确设置动画,但圆弧不会改变形状或位置
答案 0 :(得分:0)
您的问题是,不是像对待圈子一样修改Arc
补丁,而是在每一步创建一个新补丁,但不要在创建后将其添加到轴。
我已经过简要检查,但我不知道如何修改Arc
个实例的属性,虽然我确定它是可能的。
与此同时,我修改了您的功能,从Arc
列表中移除了之前的patches
,创建了一个新弧,并将其添加回Axes
#draw every frame by frame
def animate(m):
circles[0].center=((particle_one[m,0],particle_one[m,1]))
circles[1].center=((particle_two[m,0],particle_two[m,1]))
ax.patches.remove(arcs[0])
arcs[0] = patches.Arc([arc_Center[m,0],arc_Center[m,1]],5+m,3+m,angle =0 ,theta1 = 0,theta2= 270)
ax.add_patch(arcs[0])
print "step %d: arc = %s" % (m, arcs[0])
return circles,arcs
答案 1 :(得分:0)
我也遇到了弧线不动的问题。尝试按照Diziet的建议去除弧线
错误:“ x不在列表中”。
但是,似乎可行的方法是既完成弧的实例化又将其添加到动画函数中的轴上,但是没有调用将其删除的方法-本质上,Diziet的解决方案减去了线"ax.patches.remove(arcs[0])"
。