我是 python 的 matplotlib 的新手,我想制作一個 1x1 正方形的影片,該正方形在網格空間中對角線移動。我已經撰寫了這段代碼,幾乎可以完成我想要它做的事情,但是矩形的先前位置仍然可見。
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
from matplotlib.patches import Rectangle
moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]
fig, ax = plt.subplots()
#set gridlines and lines every one unit
ax.grid(which='both')
ax.axis([0,5,0,5])
rectangle = Rectangle(moving_block[0], 1,1)
ax.add_patch(rectangle)
def animate(i):
ax.add_patch(Rectangle(moving_block[i], 1,1))
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=len(moving_block), interval=300, repeat=True)
plt.show()
如何僅使當前矩形可見?我應該使用這個 ax.add_patch(Rectangle) 函式以外的東西嗎?
uj5u.com熱心網友回復:
在函式“animate”的每次迭代中添加了清理“ax”。如果您對答案感到滿意,請不要忘記投票 :-)
import matplotlib.pyplot as plt
import matplotlib.animation
from matplotlib.patches import Rectangle
moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]
fig, ax = plt.subplots()
#set gridlines and lines every one unit
ax.grid(which='both')
ax.axis([0, 5, 0, 5])
rectangle = Rectangle(moving_block[0], 1,1)
ax.add_patch(rectangle)
def animate(i):
ax.clear()
ax.axis([0, 5, 0, 5])
ax.grid(which='both')
ax.add_patch(Rectangle(moving_block[i], 1,1))
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=len(moving_block), interval=300, repeat=True)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451525.html
