5

I would like to the get the position (x, y of either the axes data or scale) of a matplotlib legend. I have tried the following:

l = ax.legend(...)
l.get_window_extent()
l.legendPatch.get_bbox().inverse_transformed(ax.transAxes) 

My goal would be use the position of the legend to add a text box with additional information next to it.

2 Answers 2

3

The way of getting position of the legend depends on the legend and when do you access it.

It seems like it is best if you access the legend object after you draw the plot, i.e. after calling:

plt.draw()

Accessing legend object position after this will return figure pixels which you can use later.

There are at least two ways to access legend position:

  1. A universal way through .get_window_extent() method
  2. If the legend has a frame through .get_frame().get_bbox().bounds methods

Clearly if the legend has no frame then the 1st method is preferred :-)

You can play with both to see how best to deal with each one.

Here is an example of how you could do it:

import matplotlib.pyplot as plt

x = y = [1,2,3,4,5]

fig, ax = plt.subplots()

ax.plot(x,y)
leg = ax.legend(['line 1'], loc=6, frameon=False)

plt.draw()

p = leg.get_window_extent()

ax.annotate('Annotation Text', (p.p0[0], p.p1[1]), (p.p0[0], p.p1[1]), 
            xycoords='figure pixels', zorder=9)

plt.show()

This yields:

legend annotated

1
  • When I change the location of the legend, the annotation text does not move with the legend for certain locations, e.g. leg = ax.legend(['line 1'], loc='center right', frameon=False) Commented May 5, 2017 at 8:43
-2

on this line of code

leg = ax.legend(['line 1'], loc=6, frameon=False)

Make the loc=0 this makes your plot to stay on the best location where it will not overlap or have the least overlap with your plot diagram.

Not the answer you're looking for? Browse other questions tagged or ask your own question.