2017-03-17 94 views
0

我想更新箭頭位置,而在一個循環的情節。我發現這個post對於其中貼片是矩形的情況有類似的問題。下面,在提到的帖子中提出的解決方案中增加了Arrow補丁。更新matplotlib中的箭頭位置

from matplotlib import pyplot as plt 
from matplotlib.patches import Rectangle, Arrow 
import numpy as np 

nmax = 10 
xdata = range(nmax) 
ydata = np.random.random(nmax) 


fig, ax = plt.subplots() 
ax.plot(xdata, ydata, 'o-') 
ax.xaxis.set_ticks(xdata) 
plt.ion() 

rect = plt.Rectangle((0, 0), nmax, 1, zorder=10) 
ax.add_patch(rect) 

arrow = Arrow(0,0,1,1) 
ax.add_patch(arrow) 

for i in range(nmax): 
    rect.set_x(i) 
    rect.set_width(nmax - i) 

    #arrow.what --> which method? 

    fig.canvas.draw() 
    plt.pause(0.1) 

Arrow補丁的問題在於,它顯然沒有像Rectangle補丁那樣與其位置相關的設置方法。歡迎提供任何提示。

回答

1

matplotlib.patches.Arrow確實沒有更新其位置的方法。儘管動態改變它的轉換是可能的,但我想最簡單的解決方案是簡單地將其刪除並在動畫的每個步驟中添加一個新的箭頭。

from matplotlib import pyplot as plt 
from matplotlib.patches import Rectangle, Arrow 
import numpy as np 

nmax = 9 
xdata = range(nmax) 
ydata = np.random.random(nmax) 

plt.ion() 
fig, ax = plt.subplots() 
ax.set_aspect("equal") 
ax.plot(xdata, ydata, 'o-') 
ax.set_xlim(-1,10) 
ax.set_ylim(-1,4) 


rect = Rectangle((0, 0), nmax, 1, zorder=10) 
ax.add_patch(rect) 

x0, y0 = 5, 3 
arrow = Arrow(1,1,x0-1,y0-1, color="#aa0088") 

a = ax.add_patch(arrow) 

plt.draw() 

for i in range(nmax): 
    rect.set_x(i) 
    rect.set_width(nmax - i) 

    a.remove() 
    arrow = Arrow(1+i,1,x0-i+1,y0-1, color="#aa0088") 
    a = ax.add_patch(arrow) 

    fig.canvas.draw_idle() 
    plt.pause(0.4) 

plt.waitforbuttonpress()  
plt.show()