使用 PyPlot 为散点图制作动画
Animate a ScatterPlot with PyPlot
我正在尝试使用 pyplot 绘制粒子的运动。
问题是我不知道如何创建动画。
这是笔记本:http://nbviewer.ipython.org/gist/lhk/949c7bf7007445033fd9
显然更新功能无法正常工作,但错误消息对我来说太神秘了。我需要更改什么?
你有关于 pyplot 动画的好教程吗?
正如@s0upa1t 评论的那样,您应该将图形句柄作为动画的第一个参数。错误是由于动画需要一个 fig
对象,该对象具有 canvas
属性,但却得到 scatter
,一个 PathCollection
对象,而后者没有。作为您想要的动画形式的最小示例,请考虑
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
dt = 0.005
n=20
L = 1
particles=np.zeros(n,dtype=[("position", float , 2),
("velocity", float ,2),
("force", float ,2),
("size", float , 1)])
particles["position"]=np.random.uniform(0,L,(n,2));
particles["velocity"]=np.zeros((n,2));
particles["size"]=0.5*np.ones(n);
fig = plt.figure(figsize=(7,7))
ax = plt.axes(xlim=(0,L),ylim=(0,L))
scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1])
def update(frame_number):
particles["force"]=np.random.uniform(-2,2.,(n,2));
particles["velocity"] = particles["velocity"] + particles["force"]*dt
particles["position"] = particles["position"] + particles["velocity"]*dt
particles["position"] = particles["position"]%L
scatter.set_offsets(particles["position"])
return scatter,
anim = FuncAnimation(fig, update, interval=10)
plt.show()
还有many good animation tutorials, however the answer here特别好。
我正在尝试使用 pyplot 绘制粒子的运动。 问题是我不知道如何创建动画。
这是笔记本:http://nbviewer.ipython.org/gist/lhk/949c7bf7007445033fd9
显然更新功能无法正常工作,但错误消息对我来说太神秘了。我需要更改什么?
你有关于 pyplot 动画的好教程吗?
正如@s0upa1t 评论的那样,您应该将图形句柄作为动画的第一个参数。错误是由于动画需要一个 fig
对象,该对象具有 canvas
属性,但却得到 scatter
,一个 PathCollection
对象,而后者没有。作为您想要的动画形式的最小示例,请考虑
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
dt = 0.005
n=20
L = 1
particles=np.zeros(n,dtype=[("position", float , 2),
("velocity", float ,2),
("force", float ,2),
("size", float , 1)])
particles["position"]=np.random.uniform(0,L,(n,2));
particles["velocity"]=np.zeros((n,2));
particles["size"]=0.5*np.ones(n);
fig = plt.figure(figsize=(7,7))
ax = plt.axes(xlim=(0,L),ylim=(0,L))
scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1])
def update(frame_number):
particles["force"]=np.random.uniform(-2,2.,(n,2));
particles["velocity"] = particles["velocity"] + particles["force"]*dt
particles["position"] = particles["position"] + particles["velocity"]*dt
particles["position"] = particles["position"]%L
scatter.set_offsets(particles["position"])
return scatter,
anim = FuncAnimation(fig, update, interval=10)
plt.show()
还有many good animation tutorials, however the answer here特别好。