text boxes automatic position

matplotlib, plot-annotations, python, text

Solution

You can do this with matplotlib's AnchoredText. As shown here:

automatically position text box in matplotlib

In brief:

from matplotlib.offsetbox import AnchoredText
anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)

Each loc number corresponds to a position within the axes, for example loc=2 is "upper left". The full list of positions is given here : http://matplotlib.org/api/offsetbox_api.html

Problem

I would like to position a text box with keyword arguments like those used with legend 'loc' option, i.e. 'upper left', 'upper right', 'lower right', 'lower left'. The basic purpose is to align the text box with legend. I found a suggestion here : automatically position text box in matplotlib but it still uses coordinates with which I have to play to get what I want, especially if I want to put it on the right of the plot area depending on the length of the text put in the box. Unless I can set one of the right corner of the text box as the reference for coordinates.

Original source

Related problems