7

I use the matplotlib library for plotting data in python. In my figure I also have some text to distinguish the data. The problem is that the text goes over the border in the figure window. Is it possible to make the border of the plot cut off the text at the corresponding position and only when I pan inside the plot the the rest of the text gets visible (but only when inside plot area). I use the text() function to display the text

[EDIT:]

The code looks like this:

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
Miguellissimo
  • 473
  • 2
  • 4
  • 11
  • possible duplicate of [matplotlib text not clipped](http://stackoverflow.com/questions/15843340/matplotlib-text-not-clipped) – tacaswell Feb 17 '14 at 19:22

2 Answers2

4

I think that your text goes over the border because you didn't set the limits of your plot. Why don't you try this?

 fig=figure()
 ax=fig.add_subplot(1,1,1)
 text(0.1, 0.85,'dummy text',horizontalalignment='left',verticalalignment='center',transform = ax.transAxes)

This way your text will always be inside the plot and its left corner will be at point (0.1,0.85) in units of your plot.

Brian
  • 13,996
  • 19
  • 70
  • 94
3

You just need to tell the text artists to not clip:

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)

However, there is a bug matplotlib (https://github.com/matplotlib/matplotlib/pull/1885 now fixed) which makes this not work. The other way to do this (as mentioned in the comments) is to use

txt = ax.text(..., clip_on=True)
tacaswell
  • 84,579
  • 22
  • 210
  • 199