[英]How to trace the path of a patches.Rectangle object in matplotlib animation?
[英]Matplotlib crude animation, show trace
我剛剛開始一個小粒子模擬器,我希望擴展以解決一些物理問題,但我在嘗試為它們設置動畫時遇到了問題。 基本上取決於您選擇什么樣的隨機分布,粒子將在給定長度的區域內“振盪”。 我想在前面的 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 在圖像上設置動畫(主要是我對Animate 繪制 networkx 邊緣的回答的副本和過去)
為了獲得你想要的時滯,你需要設置一個歷史數據結構,比如:
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 ( 在 pylab 模式下繪制矩形(add_patch) ),以及傳遞給FuncAnimation
的可選參數。
這並不完美,有一些奇怪的細節會在它自身上循環(一個循環中的第 50 幀與下次經過時的第 50 幀不同),前 10 幀有一個瞬態,當有歷史中的一堆零(您可以通過將歷史數組初始化為初始點的 10 個副本來解決這個問題)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.