Matplotlib - set pad between arrow and text in annotate function

江枫思渺然 提交于 2021-02-19 01:33:55

问题


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


回答1:


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




回答2:


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()



回答3:


To have full control of the distance, you must combine jrjc and Ffisegydd answers.

The pad property of the Bbox defines the distance between the text and its containing box. The shrink property of the arrow is the distance between the arrow extremity and the box, not the text itself.

Also, to use shrink with FancyArrowPatch you must defined it separately: shrinkA for the origin (extremity of the arrow close to the text) and shrinkB for the destination. From a demo in Matplotlib's website:

 ax.annotate("",
             xy=(x1, y1), xycoords='data',
             xytext=(x2, y2), textcoords='data',
             arrowprops=dict(arrowstyle="->", color="0.5",
                             shrinkA=5, shrinkB=5,
                             patchA=None, patchB=None,
                             connectionstyle=connectionstyle,
                             ),
             )

So the full answer is both:

plt.annotate('Example text',
             xy=(-1,-1), xytext=(0,0),
             arrowprops=dict(arrowstyle='->', shrinkA=0.15),
             bbox=dict(pad=0),
    )

Examples:



来源:https://stackoverflow.com/questions/23344891/matplotlib-set-pad-between-arrow-and-text-in-annotate-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!