Matplotlib粗糙的动画,显示痕迹



我刚刚开始一个小型粒子模拟器,我想扩展它来解决一些物理问题,但我在尝试动画化它们时遇到了问题。本质上取决于你选择的随机分布类型,粒子将在给定长度的区域内"振荡"。我想展示粒子的"历史",比如前面的10个步骤。

这是代码

from numpy import *
import matplotlib.pyplot as plt
import pylab
import time
pylab.ion()
N = 10
r = random.randint(-100,100,2*N).reshape(N,2)
line, = plt.plot(r[:,0], r[:,1],'o')
for i in range(100000):
newdatax = r[:,0] + random.rand(N)
newdatay = r[:,1] + random.rand(N)
line.set_ydata(newdatay)
line.set_xdata(newdatax)
plt.title("At timestep: %d" %i)
plt.hold(True)
plt.draw()
time.sleep(1.0/30)

我想要的是,线更新不是在每次迭代时清除画布并重新绘制,我只希望它这样做,比如说,每10帧(迭代),这将使我更容易视觉跟踪粒子。

我还想实现另一件事,但这并不是绝对必要的,有可能在每个"o"周围画一个方框(正方形)、一个圆或一个三角形吗?这样点就在那个方框/圆/三角形的中心?这将再次使跟踪粒子变得更加容易。如果我能指定哪个"o"(点)得到这个属性(平方),那就更好了。

尝试animation模块。另请参阅这个很棒的教程,Matplotlib在图像上动画(主要是我对动画绘制网络x边的回答的副本和过去)

为了得到你想要的时间滞后,你需要设置一个历史数据结构,比如:

from matplotlib import animation
fig = figure()
N = 10
r = random.randint(-100,100,2*N).reshape(N,2)
line, = plt.plot(r[:,0], r[:,1],'o')

lag_len = 10
history_x = np.zeros((N,lag_len))
history_y = np.zeros((N,lag_len))
trails = [plot(hx,hy)[0] for hx,hy in zip(history_x,history_y)]
def update_frame(i):
frame_num = i
newdatax = r[:,0] + random.rand(N)
newdatay = r[:,1] + random.rand(N)
line.set_ydata(newdatay)
line.set_xdata(newdatax)
history_x[:,frame_num%lag_len] = newdatax
history_y[:,frame_num%lag_len] = newdatay
for hx,hy,ln_h in zip(history_x,history_y,trails):
ln_h.set_xdata(hx)
ln_h.set_ydata(hy)
plt.title("At timestep: %d" %i)
plt.hold(True)
return (line,) + tuple(trails)
anim = animation.FuncAnimation(fig, update_frame, 
frames=100, interval=20)

对于方框,请使用矩形(在pylab模式下绘制矩形(add_patch)),以及要传递给FuncAnimation的可选参数。

这并不完美,有一些奇怪的细节表明它在自己身上循环(一个循环中的帧50与下一次循环时的帧50不同),当历史中有一堆零时,前10帧会有一个瞬态(你可以通过将历史数组初始化为初始点的10个副本来解决这个问题)

最新更新