Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib text not clipped

When drawing text in matplotlib with text(), and then interactively panning the image, the resulting drawn text is not clipped to the data window. This is counter to how plotting data or drawing text using annotate() works, and doesn't make intuitive sense as text() uses data window coordinates.

import matplotlib.pyplot as plt

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

ax.text(0.5, 0.2, 'text')
ax.annotate('anno', (0.5, 0.3))

plt.draw()

Interactively pan the text out of the data window on all sides. The annotate() drawn 'anno' is clipped when the reference point crosses the data window boundary, while the text() drawn 'text' is not.

I'm not sure if this behavior a feature or a bug, but sure seems like the latter, as this text interferes with axis labels, etc. Using 1.2.1 with TkAgg backend.

An additional question would be how to properly clip all text from going outside the data window, not just when the reference coordinate does.

Thanks!

like image 248
CNK Avatar asked Apr 05 '13 20:04

CNK


People also ask

How do I offset text in Matplotlib?

Use xytext=(x,y) to set the coordinates of the text. You can provide these coordinates in absolute values (in data, axes, or figure coordinates), or in relative position using textcoords="offset points" for example.

How do I show text in Matplotlib?

The matplotlib. pyplot. text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes.

What is ha in Matplotlib?

horizontalalignment or ha. [ 'center' | 'right' | 'left' ] label. any string. linespacing.


1 Answers

This behavior can be controled by the kwarg clip_on:

import matplotlib.pyplot as plt

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

txt = ax.text(0.5, 0.2, 'text')
anno = ax.annotate('anno', (0.5, 0.3))
txt_clip = ax.text(0.5, 0.5, 'text-clip', clip_on=True)

plt.draw()

axes.text doc. There are arguments both for and against clipping the text to the data area.

There was a bug in mpl that made txt.set_clip_on(True) not work as expected.

like image 197
tacaswell Avatar answered Oct 10 '22 01:10

tacaswell