4

I create a scatter plot with an annotation with the following code:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12)
plt.scatter(np.random.random(10), np.random.random(10), zorder = 2)
bbox_props = dict(boxstyle = "circle, pad = 10", fc = "w", ec = "k")
plt.annotate("interesting", (0.6, 0.8), bbox = bbox_props, zorder = 1)
plt.show()

Sample output:

enter image description here

How do you prevent that the annotation is shown outside the graph? I searched for it but could only find the opposite case that people want to print an annotation/text/legend outside the graph.

Mr. T
  • 11,960
  • 10
  • 32
  • 54

1 Answers1

5

You need to use the clip_on argument of plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12)
plt.scatter(np.random.random(10), np.random.random(10), zorder = 2)
bbox_props = dict(boxstyle = "circle, pad = 10", fc = "w", ec = "k")
plt.annotate("interesting", (0.6, 0.8), bbox = bbox_props, zorder = 1, clip_on=True)
plt.show()

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82