pythonmatplotlibscipy

Set pad between arrow and text in annotate function


How do I set the distance (padding) between the arrow and the text in matplotlib's annotate function? Sometimes the text ends up being too close to the arrow and I would like to move them a little further apart.

Basic example:

import matplotlib.pyplot as plt

plt.annotate('Here it is!',xy=(-1,-1),xytext=(0,0),
             arrowprops=dict(arrowstyle='->',lw=1.5))

plt.xlim(-10,10)
plt.ylim(-10,10)

plt.show()

enter image description here


Solution

  • For fancy arrows you can play with the bbox properties:

    fig, ax = plt.subplots(1, 3, figsize=(7, 3))
    pad_val = [-5, 0, 5]
    for a,p in zip(ax, pad_val):
        a.annotate('Here it is!\npad={}'.format(p),xy=(-1,-1),xytext=(1,1),
                    arrowprops=dict(arrowstyle='-|>', fc="k", ec="k", lw=1.5),
                    bbox=dict(pad=p, facecolor="none", edgecolor="none"))
        a.set_xlim(-10,10)
        a.set_ylim(-10,10)
    

    set pad between arrow and text in matplotlib annotate

    Here the drawback is that you can't add a color behind the annotation (facecolor="none" is mandatory), or the arrow will always stick to the border of the frame and it might be ugly.

    HTH