更新 matplotlib 中的箭头位置

Ran*_*son 7 python matplotlib python-2.7

我想在绘图循环中更新箭头位置。我发现这篇文章对补丁是矩形的情况有一个类似的问题。下面,在提到的帖子中提出的解决方案添加了 Arrow 补丁。

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)
Run Code Online (Sandbox Code Playgroud)

箭头补丁的问题在于它显然没有像矩形补丁那样与它的位置相关的设置方法。欢迎任何提示。

Imp*_*est 8

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()
Run Code Online (Sandbox Code Playgroud)

  • 我建议将其添加到 matplotlib 中:) (2认同)