Mr. T
Mr. T

Reputation: 12410

Prevent that an annotation is shown outside the graph area

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.

Upvotes: 4

Views: 932

Answers (1)

DavidG
DavidG

Reputation: 25362

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

Upvotes: 5

Related Questions