Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Get Matplotlib legend location?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...