我想在绘图循环中更新箭头位置。我发现这个post对于贴片为矩形的情况有类似的问题。下面是提到的帖子中提出的解决方案,其中添加了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)
Arrow贴片的问题在于,显然它没有与Rectangle贴片一样的与其位置相关的set方法。欢迎任何提示。
最佳答案
matplotlib.patches.Arrow
确实没有更新其位置的方法。尽管可以动态更改其变换,但我猜最简单的解决方案是简单地将其删除并在动画的每个步骤中添加一个新的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()
关于python - 在matplotlib中更新箭头位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42868847/