简体   繁体   中英

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

我的matplotlib示例

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

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

在此输入图像描述

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