I would like to update the arrow position while in a loop of plots. I found this post that has an analogous question for the situation in which the patch is a rectangle. Below, the solution proposed in the mentioned post with the addition of the Arrow patch.
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)
The problem with the Arrow patch is that apparently it does not have a set method related with its position as the Rectangle patch has. Any tip is welcome.
The matplotlib.patches.Arrow
indeed does not have a method to update its position. While it would be possible to change its transform dynamically, I guess the easiest solution is to simply remove it and add a new Arrow in each step of the animation.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With