Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib text boxes automatic position

Tags:

matplotlib

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.

like image 899
user1850133 Avatar asked Oct 01 '22 00:10

user1850133


2 Answers

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

like image 96
Anake Avatar answered Oct 12 '22 10:10

Anake


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')
like image 27
Molly Avatar answered Oct 12 '22 11:10

Molly