![](/img/trans.png)
[英]Avoid slow looping when plotting irregular raster plot using patches.Rectangle
[英]How to trace the path of a patches.Rectangle object in matplotlib animation?
我正在嘗試使用 matplotlib 為簡單的 patch.Rectangle object 設置動畫。 我想 plot 由 animation 中的所述 object (或被它刷過的區域)跟蹤的路徑。 我可以看到人們通過將其所有先前位置附加到列表來跟蹤單個粒子的路徑,但我不確定如何為矩形執行此操作。
做到這一點的一種方法(我猜)是將 plot 矩形放在新位置,而不會從前一幀中清除矩形。 但我不知道該怎么做。
我正在使用以下代碼:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]
# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
patch = patches.Rectangle((0, 0), 0, 0, fc='r')
def init():
ax.add_patch(patch)
return patch,
def animate(i):
patch.set_width(5.0)
patch.set_height(2.0)
patch.set_xy([x[i], y[i]])
patch.angle = np.rad2deg(orientation[i])
return patch,
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x),
interval=5, blit=True, repeat_delay=500)
plt.show()
換句話說,除了矩形移動之外,我還想看到矩形移動時的軌跡。 理想情況下,該解決方案也應該很容易適用於其他補丁對象(多邊形、橢圓等)。
要將 object 保留在 animation 中,不需要初始化,只需將 object 添加到空列表中,指定為 Patch_collection,並將其設置為 () 我相信這也可以轉移到其他對象上; 可以在此處找到 PatchCollection 的參考示例。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
from matplotlib.collections import PatchCollection
# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]
# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
patch = patches.Rectangle((0, 0), 0, 0, fc='r')
def init():
ax.add_patch(patch)
return patch,
items = []
def animate(i):
patch.set_width(5.0)
patch.set_height(2.0)
patch.set_xy([x[i], y[i]])
patch.angle = np.rad2deg(orientation[i])
items.append(patch)
fig = ax.add_collection(PatchCollection(items, fc='r', ec='white', alpha=x[i]))
return fig,
anim = animation.FuncAnimation(fig, animate, frames=len(x), interval=200, blit=True, repeat=False)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.