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()
Optionally, you can enable drawing of an arrow from the text to the annotated point by giving a dictionary of arrow properties in the optional keyword argument arrowprops. In the example below, the xy point is in native coordinates (xycoords defaults to 'data'). For a polar axes, this is in (theta, radius) space.
Annotating with Arrow. The annotate() function in the pyplot module (or annotate method of the Axes class) is used to draw an arrow connecting two points on the plot. This annotates a point at xy in the given coordinate ( xycoords ) with the text at xytext given in textcoords .
The Axes. annotate() function in axes module of matplotlib library is also used to annotate the point xy with text text.In other word, it i used to placed the text at xy.
xytext : (float, float), optional. The position (x,y) to place the text at. If None, defaults to xy. xycoords : str, Artist , Transform , callable or tuple, optional. The coordinate system that xy is given in.
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)
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
You can use the shrink
keyword argument in your arrowprops
dictionary, but unfortunately the FancyArrowPatch
object doesn't support it, so you'd have to remove the arrowstyle='->'
.
The value given with shrink
is a percentage that the tip/base will move away from the xy
and xytext
coordinates.
import matplotlib.pyplot as plt
plt.annotate('Here it is!',xy=(-1,-1),xytext=(0,0),
arrowprops=dict(lw=1.5, shrink=0.15))
plt.xlim(-10,10)
plt.ylim(-10,10)
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