matplotlib 中的 bbox_to_anchor 和 loc [英] bbox_to_anchor and loc in matplotlib
问题描述
我遇到了 matplotlib
代码,它使用关键字 loc
和 bbox_to_anchor
自定义图例位置.例如:
I came across matplotlib
code which customizes legend location using keywords loc
and bbox_to_anchor
. For example :
fig.legend([line1, line2], ['series1', 'series2'], bbox_to_anchor=[0.5, 0.5],
loc='center', ncol=2)
我看到了上面的变体,其中 loc
之后使用了 bbox_to_anchor
.
I have seen variation of above where bbox_to_anchor
is used after loc
.
我了解分别使用 bbox_to_anchor
和 loc
的目的.但是,在同一个图例规范中同时使用两者有什么好处吗?根据我的理解和使用,在我看来,如果指定了 bbox_to_anchor
,那么 loc
参数几乎不在乎.
I understand the purpose of using bbox_to_anchor
and loc
separately. However, is there any benefit of using both in the same legend specification? From my understanding and usage, it appears to me that if bbox_to_anchor
is specified, then the loc
parameter is pretty much don't care.
谁能确认一下?我没有看到任何关于此的文档.
Can anyone confirm this? I don't see any documentation regarding this.
推荐答案
当 bbox_to_anchor
和 loc
一起使用时,loc
参数将通知 matplotlib 图例的边界框的哪一部分应该放在 bbox_to_anchor
的参数处.例如(我稍微简化了命令),下面的三个选项将为您的图例生成不同的位置,
When bbox_to_anchor
and loc
are used together, the loc
argument will inform matplotlib which part of the bounding box of the legend should be placed at the arguments of bbox_to_anchor
. For example (I've simplified the command a bit), the three options below will produce different locations for your legend,
fig.legend([line1], ['series1'], bbox_to_anchor=[0.5, 0.5], loc='center')
fig.legend([line1], ['series1'], bbox_to_anchor=[0.5, 0.5], loc='center left')
fig.legend([line1], ['series1'], bbox_to_anchor=[0.5, 0.5], loc='center right')
第一个命令将把边界框的中心放在坐标轴0.5,0.5处.第二个将把边界框的中心左边缘放在相同的坐标上(即向右移动图例).最后,第三个选项会将边界框的中心右边缘置于坐标处(即,将图例向左移动).
The first command will put the center of the bounding box at axes coordinates 0.5,0.5. The second will put the center left edge of the bounding box at the same coordinates (i.e. shift the legend to the right). Finally, the third option will put the center right edge of the bounding box at the coordinates (i.e. shift the legend to the left).
这篇关于matplotlib 中的 bbox_to_anchor 和 loc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!