简体   繁体   中英

matplotlib: add annotation outside of figure

I would like to add an annotation outside of the axes of my figure. It consists of a colored rectangle and a short text.

For the rectangle, I can set clip_on=False and it is drawn even outside of the axes. The text is added with axes.annotate and I can't find the corresponding setting. Even the global axes.set_clip_on(False) doesn't prevent the text from being clipped away:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

plt.figure()
ax = plt.subplot(111)
plt.plot([0,1], [0,1])

ax.set_clip_on(False)

ax.annotate("test", (0.5, 0.5), fontsize="x-large")
ax.annotate("outside", (0.5, 1.1), fontsize="x-large")

p1 = mpatches.Rectangle([0.6, 0.5], *[0.1, 0.1], color="blue")
p2 = mpatches.Rectangle([0.6, 1.1], *[0.1, 0.1], color="red", clip_on=False)

ax.add_patch(p1)
ax.add_patch(p2)

plt.show()

it looks like this:

带有剪裁文本的绘图

How can I prevent text from outside my figure to be clipped away?

The corresponding setting you are looking for is called annotation_clip and can be set to False in the same manner as clip_on . Full code would look like this:

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

plt.figure()
ax = plt.subplot(111)
plt.plot([0,1], [0,1])

ax.set_clip_on(False)

ax.annotate("test", (0.5, 0.5), fontsize="x-large")
ax.annotate("outside", (0.5, 1.1), fontsize="x-large", annotation_clip=False)

p1 = mpatches.Rectangle([0.6, 0.5], *[0.1, 0.1], color="blue")
p2 = mpatches.Rectangle([0.6, 1.1], *[0.1, 0.1], color="red", clip_on=False)

ax.add_patch(p1)
ax.add_patch(p2)

plt.show()

And the result is:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM