Matplotlib原始动画

2024-09-30 12:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始一个小粒子模拟器,我想扩展以解决一些物理问题,但我有一个问题,试图动画他们。基本上取决于你选择的随机分布,粒子会在给定长度的区域内“振荡”。我想展示粒子的“历史”,比如前面的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”(点)得到这个属性(平方),那就更好了。在


Tags: importtimeline物理粒子动画pltrandom
1条回答
网友
1楼 · 发布于 2024-09-30 12:25:59

试试^{} module。也可以看看这个很棒的tutorialMatplotlib animate over an image(大部分是我对Animate drawing networkx edges的回答的副本和过去)

要获得所需的时间延迟,需要设置一个历史数据结构,如下所示:

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)

对于这些框,使用RectangleDraw rectangle (add_patch) in pylab mode),以及传递给FuncAnimation的可选参数。在

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

相关问题 更多 >

    热门问题