6

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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
user1850133
  • 2,833
  • 9
  • 29
  • 39

2 Answers2

3

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

Community
  • 1
  • 1
Anake
  • 7,201
  • 12
  • 45
  • 59
1

How about setting the location of the text relative to the legend? The trick is, to find the location of the legend you have to draw it first then get the bbox. Here's an example:

import matplotlib.pyplot as plt
from numpy import random

# Plot some stuff
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(random.rand(10))

# Add a legend
leg = ax.legend('line', loc = 'upper right')

# Draw the figure so you can find the positon of the legend.
plt.draw()  

# Get the Bbox
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)

# Add text relative to the location of the legend.
ax.text(bb.x0, bb.y0 - bb.height, 'text', transform=ax.transAxes)
plt.show()

On the other hand, if you only need to define the location of the text from the right you can set the horizontal alignment to right like this:

plt.text(x, y, 'text', ha = 'right')
Molly
  • 13,240
  • 4
  • 44
  • 45
  • I tried your first suggestion but I get the 'text' at the bottom on the left, out of the plot area and half out from the figure window. The second one is the solution about setting the anchor point of the text box, but I just realised it would not do what I want. The first solution seems the right one, I'll search a bit about this one. – user1850133 Apr 17 '14 at 20:59
  • I picked those coordinates for ax.text as an example. You should be able to do some math with bb.x0, bb.y0, bb.height and bb.width to get the location you want. – Molly Apr 17 '14 at 21:08
  • what are the four numbers we get with leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)? the four corners? I tried with a legend 'upper left', the four numbers are negative! – user1850133 May 21 '14 at 17:26