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:
- A universal way through
.get_window_extent()
method
- 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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…