 # Legend in X coordinates

Hi,

How can I get the position, in x coordinates/units, of the legend? Specifically, I'd like to get the center of the legend box, because I want to add some text that is centered-aligned with the legend. Thanks.

···

--
Christopher Brown, Ph.D.
Department of Speech and Hearing Science
Arizona State University

The exact location of the legend is known at drawing time. Thus, the
location of the text needs to be calculated at the drawing. I may help
you with this but it is quite tricky and you need some knowledge on
internals of the mpl.

Or, you may simply draw the figure twice (with same renderer), where
the first one is just to calculate the location of the text.
Here is an example.

···

------------------
import matplotlib.pyplot as plt
plt.plot([1, 3, 2], label="test2")
l = plt.legend()
plt.draw() # the location of the legend is now known

ax = gca()
bbox = l.legendPatch.get_bbox().inverse_transformed(ax.transAxes) #
bbox in axes coordinate.
x = bbox.x0+bbox.width/2. # center

ax.text(x, 0, "test", va="bottom", ha="center", transform=ax.transAxes)
plt.draw()
---------------------

Note that if you want save the figure, you need to save it with a same
dpi, or save the figure twice as above.

-JJ

On Tue, Dec 30, 2008 at 5:16 PM, Christopher Brown <c-b@...1861...> wrote:

Hi,

How can I get the position, in x coordinates/units, of the legend?
Specifically, I'd like to get the center of the legend box, because I
want to add some text that is centered-aligned with the legend. Thanks.

--
Christopher Brown, Ph.D.
Department of Speech and Hearing Science
Arizona State University

------------------------------------------------------------------------------
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Hi Jae-Joon,

Your simpler suggestion of drawing the fig twice is just fine for my needs. Thank you.

···

The exact location of the legend is known at drawing time. Thus, the
location of the text needs to be calculated at the drawing. I may
help you with this but it is quite tricky and you need some
knowledge on internals of the mpl.

Or, you may simply draw the figure twice (with same renderer), where
the first one is just to calculate the location of the text.
Here is an example.

------------------
import matplotlib.pyplot as plt
plt.plot([1, 3, 2], label="test2")
l = plt.legend()
plt.draw() # the location of the legend is now known

ax = gca()
bbox = l.legendPatch.get_bbox().inverse_transformed(ax.transAxes) #
bbox in axes coordinate.
x = bbox.x0+bbox.width/2. # center

ax.text(x, 0, "test", va="bottom", ha="center",
transform=ax.transAxes) plt.draw()
---------------------

Note that if you want save the figure, you need to save it with a
same dpi, or save the figure twice as above.

-JJ

--
Christopher Brown, Ph.D.
Department of Speech and Hearing Science
Arizona State University