Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping text on matplotlib plot

I am making a plot and I want the text to crop at the edge. Right now it hangs over the edge, which is great for readability, but not what I actually want.

Here's a toy version of what I'm doing:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax = fig.add_subplot(111)

ax.scatter(np.random.random(10), np.random.random(10))
ax.text(0.8, 0.5, "a rather long string")

plt.show()

my matplotlib example

Just to be clear, I want to crop my text element, but not anything else — e.g. I want to leave the 0.9 in the x-axis alone.

like image 896
Matt Hall Avatar asked Sep 20 '26 22:09

Matt Hall


1 Answers

You should set a clipbox for the text as described in the documentation:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax = fig.add_subplot(111)

ax.scatter(np.random.random(10), np.random.random(10))
ax.text(0.8, 0.5, "a rather long string",
        clip_box=ax.clipbox, clip_on=True)
ax.set_xlim(0, 1)

plt.show()

This results in

enter image description here

like image 91
David Zwicker Avatar answered Sep 22 '26 11:09

David Zwicker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!