我遇到了一个python动画,其中我试图为最初按二维六边形网格排列的粒子系统制作动画,并按照规则逐渐展开:xpos1[i]=xpos1[i]+L/10.0
。如果任何粒子超出窗口限制,它们将从另一侧进入
if xpos1[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*3
xpos1[i]=xpos1[i]-L*3
elif xpos1[i]<0:
xpos1[i]=L*3-xpos1[i]
位置的所有更新都存储在两个列表xpos1和ypos1中。这是在几个时间步骤完成的。
我希望通过将系统转换为动画来可视化系统的时间演变。我的代码如下。我之前从未做过matplotlib动画,并且实际上已经复制了动画&#39;部分来自另一个工作正常的程序。但它不适用于我的。
from numpy import*
import matplotlib.pyplot as plt
import matplotlib.animation as animation
sigma=3.4e-10 # dist of closest approach
L=4.8e-10 # lattice constant = sigma*2**0.5 (Let)
xpos1=zeros(18,float)
ypos1=zeros(18,float)
# ~~~~~~~~~~~ Setting up the hexagonal lattice ~~~~~~~~~~~~~~~~~~~~~~
k=0
for x in range(0,6,1):
for y in range(0,6,1):
if (x+y)%2==0:
xpos1[k]=x*L*.5+.25*L
ypos1[k]=y*L*.5+.25*L
k=k+1
#~~~~~~~~~~~~~~~~~~TIME EVOLUTION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
t = 4.5e-12
iteration=1
while t<=1e-9:
for i in range(18):
xpos1[i]=xpos1[i]+L/10.0
ypos1[i]=ypos1[i]+L/10.0
if xpos1[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
xpos1[i]=xpos1[i]-L*3
elif xpos1[i]<0:
xpos1[i]=L*3-xpos1[i]
if ypos1[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
ypos1[i]=ypos1[i]-L*3
elif ypos1[i]<0:
ypos1[i]=L*3-ypos1[i]
t = t + 4.5e-12
#~~~~~~~~~~~~~~~~~ ANIMATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def simData():
for i in range(18):
x=xpos1[i]
y=ypos1[i]
yield x,y
def simPoints(simData):
x,y= simData[0],simData[1]
line.set_data(x,y)
return line
fig = plt.figure()
ax = fig.add_subplot(111)
line,= ax.plot([],[],'bo',ms=8)
ax.set_ylim(0 , L*3)
ax.set_xlim(0 , L*3)
ani = animation.FuncAnimation(fig, simPoints, simData, blit=True , interval=200)
plt.show()
有人可以告诉我如何成功制作动画吗?
答案 0 :(得分:2)
您的动画update
(如果有动画,init
)必须返回iterable
。
def simPoints(simData):
x, y = simData[0], simData[1]
line.set_data(x, y)
return line, # added a comma to return a tuple
如果你在mac os上,你可能还需要设置blit=False
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=200)
这是一个显示18个随机点的最小工作示例 - 您必须将随机生成更改为您希望格子上的点所需的模式。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.random.random(18)
y = np.random.random(18)
def simData():
"""updates the points position on your lattice.
replace with your own code - can call a helper function to accomplish this task
"""
x = np.random.random(18)
y = np.random.random(18)
yield x, y
def simPoints(simData):
"""initializes the points position on your lattice.
replace with your own code - can call a helper function to accomplish this task
"""
x = np.random.random(18)
y = np.random.random(18)
line.set_data(x, y)
return line,
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y,'bo', ms=8)
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=200)
plt.show()