如何在Matplotlib中获取图例位置 [英] How to get legend location in matplotlib
问题描述
我正在尝试在matplotlib中获取图例位置.似乎Legend.get_window_extent()应该提供此功能,但是无论图例位于何处,它都将返回相同的值.这是一个示例:
I'm trying to get the legend location in matplotlib. It seems like Legend.get_window_extent() should provide this, but it returns the same value regardless of where the legend is located. Here is an example:
from matplotlib import pyplot as plt
def get_legend_pos(loc):
plt.figure()
plt.plot([0,1],label='Plot')
legend=plt.legend(loc=loc)
plt.draw()
return legend.get_window_extent()
if __name__=='__main__':
# Returns a bbox that goes from (0,0) to (1,1)
print get_legend_pos('upper left')
# Returns the same bbox, even though legend is in a different location!
print get_legend_pos('upper right')
获取图例位置的正确方法是什么?
What is the correct way to get the legend location?
推荐答案
您需要将plt.draw()
替换为
plt.gcf().canvas.draw()
,或者,如果有图形手柄,则为fig.canvas.draw()
.这是必需的,因为图例位置仅在绘制画布时才确定,而预先将其放置在同一位置.
or, if you have a figure handle, fig.canvas.draw()
. This is needed because the legend position is only determined when the canvas is drawn, beforehands it just sits in the same place.
仅使用plt.draw()
是不够的,因为绘制图例需要使用中的后端提供有效的渲染器.
Using plt.draw()
is not sufficient, because the drawing the legend requires a valid renderer from the backend in use.
这篇关于如何在Matplotlib中获取图例位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!