matplotlib 文本仅在绘图区域

Mig*_*imo 6 python matplotlib

我使用 matplotlib 库在 python 中绘制数据。在我的图中,我也有一些文字来区分数据。问题是文本越过图形窗口中的边框。是否可以使绘图的边框在相应位置切断文本,并且仅当我在绘图内平移时,其余文本才可见(但仅当在绘图区域内时)。我使用 text() 函数来显示文本

[编辑:]

代码如下所示:

fig = plt.figure()
ax = fig.add_subplot(111)
# ...
txt = ax.text(x, y, n, fontsize=10)
txt.set_clip_on(False) # I added this due to the answer from tcaswell
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 3

你只需要告诉文本艺术家不要剪辑:

txt = ax.text(...)

txt.set_clip_on(False)  # this will turn clipping off (always visible)
# txt.set_clip_on(True) # this will turn clipping on (only visible when text in data range)
Run Code Online (Sandbox Code Playgroud)

然而,matplotlib 有一个错误(https://github.com/matplotlib/matplotlib/pull/1885现已修复),这使得它不起作用。另一种方法(如评论中提到的)是使用

txt = ax.text(..., clip_on=True)
Run Code Online (Sandbox Code Playgroud)