使用PyPlot为ScatterPlot设置动画 [英] Animate a ScatterPlot with PyPlot
问题描述
我正试图用pyplot绘制粒子的运动。
问题是我无法弄清楚如何创建动画。
I'm trying to plot the movement of particles with pyplot. The problem is that I can't figure out how to create the animation.
这是笔记本: http://nbviewer.ipython.org/gist/lhk/949c7bf7007445033fd9
显然更新功能无法正常工作,但错误信息对我来说太神秘了。我需要更改什么?
Apparently the update function doesn't work properly, but the error message is too cryptic for me. What do I need to change ?
你有一个关于pyplot动画的好教程吗?
Do you have a good tutorial on animation with pyplot ?
推荐答案
作为@ s0upa1t评论,您应该将数字句柄作为动画的第一个参数。由于动画需要 fig
对象,其属性为 canvas
,而是获得 scatter
,一个 PathCollection
对象,但没有。作为您想要的形式的动画的最小示例,请考虑,
As @s0upa1t comments you should have figure handle as the first argument to animation. The criptic error results from animation expecting a fig
object, which has attribute canvas
but instead gets scatter
, a PathCollection
object, which does not. As a minimal example of animation in the form you want, consider,
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()
There are many good animation tutorials, however the answer here is particularly nice.
这篇关于使用PyPlot为ScatterPlot设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!