【问题标题】:Updating arrow position in matplotlib更新 matplotlib 中的箭头位置
【发布时间】:2017-08-09 16:18:48
【问题描述】:

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

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 补丁那样具有与其位置相关的 set 方法。欢迎任何提示。

【问题讨论】:

    标签: python python-2.7 matplotlib


    【解决方案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()
    

    【讨论】:

    • 我建议把这个加入matplotlib :)
    • 当您想要从静态图像移动到动画时,另一个必须解决的 API 不一致...
    猜你喜欢
    • 1970-01-01
    • 2016-02-10
    • 2014-11-20
    • 2022-10-13
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多