correia55 correia55 - 3 months ago 11
Python Question

Can I change the arrowprops (properties) of an annotation in an animation?

I have been looking for a way to change the properties of an arrow created using the arrowprops argument of an annotation in an animation (matplotlib).

The arrow was created like this:

axes.annotate('', xy=(-1, -1), xytext=(-1, -1), xycoords='data', textcoords='data',
arrowprops=dict(arrowstyle='<-', color='blue', linewidth=2))


And I want to be able to change the color of the arrow during an animation.

Answer Source

The arrow of the annotation is stored in the arrow_patch attribute. You can set it's color via set_color.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
ax.axis([-2,2,-2,2])

arrowprops=dict(arrowstyle='<-', color='blue', linewidth=10, mutation_scale=150)
an = ax.annotate('Blah', xy=(1, 1), xytext=(-1.5, -1.5), xycoords='data', 
                 textcoords='data', arrowprops=arrowprops)

colors=["crimson", "limegreen", "gold", "indigo"]
def update(i):
    c = colors[i%len(colors)]
    an.arrow_patch.set_color(c)

ani = animation.FuncAnimation(fig, update, 10, interval=1000, repeat=True)
plt.show()

enter image description here