python - Matplotlib 粗动画,显示轨迹

标签 python matplotlib plot particles

我刚刚启动一个小型粒子模拟器,我希望扩展它来解决一些物理问题,但在尝试为它们设置动画时遇到问题。本质上取决于您选择的随机分布类型,粒子将在给定长度的区域中“振荡”。我想显示粒子在前 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)

我想要的是行更新不清除 Canvas 并在每次迭代时重新绘制,我只是希望它每 10 帧(迭代)执行一次,这将使我更容易跟踪粒子视觉上。

还有一件事我想实现,但并不是绝对必要的,是否可以在每个“o”周围画一个盒子(正方形)或一个圆形或一个三角形?这样该点就位于该框/圆/三角形的中心?这将再次使追踪粒子变得更加容易。如果我可以指定哪个“o”(点)获得此属性(正方形),那就更好了。

最佳答案

尝试animation module 。另请参阅这个很棒的tutorial , Matplotlib 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)

对于盒子,使用 Rectangle ( Draw rectangle (add_patch) in pylab mode ),以及传递给 FuncAnimation 的可选参数。

这并不完美,它有一些奇怪的细节循环回到它的自身(一个循环中的第 50 帧与下一次它经过的第 50 帧不一样),前 10 帧有一个 transient 当历史中有一堆零时(您可以通过将历史数组初始化为初始点的 10 个副本来修复该问题)

关于python - Matplotlib 粗动画,显示轨迹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13476032/

相关文章:

python - 使用 matplotlib 在股票图表上跳过周末

matplotlib - 为 pyplot 对象设置 alpha channel ?

python + matplotlib : how to insert more space between the axis and the tick labels in a polar chart?

python - Bokeh 概念验证有效的动态图更新?

r - 具有相应颜色的两个图例的散点图

python - 在 pysftp get 中指定文件模式

python - 无法使用 PIP 和 setup.py 安装 Python Cryptography 包

python - 如何拥有兼具元组和字典特性的数据结构

java - 在 python 和 java 中设置线程关联

plot - 牛虻的颜色不透明度