gpt4 book ai didi

python - Matplotlib 粗动画,显示轨迹

转载 作者:行者123 更新时间:2023-12-01 05:53:17 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com