49

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)

I have seen variation of above where bbox_to_anchor is used after 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.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
user3897208
  • 693
  • 1
  • 5
  • 7

2 Answers2

69

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')

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).

Gabriel
  • 10,524
  • 1
  • 23
  • 28
  • 1
    Thank you. It works. However it appears to me that fig.legend with bbox_to_anchor does not work very well with savefig with bbox_inches='tight'. It still cuts off a portion of the legend. If I drop the bbox_inches='tight' param from savefig, it works – user3897208 Jul 31 '14 at 23:06
36

The explanation of @Gabriel is slightly misleading. bbox_to_anchor=[x0, y0] will create a bounding box with lower left corner at position [x0, y0]. The extend of the bounding box is zero - being equivalent to bbox_to_anchor=[x0, y0, 0, 0]. The legend will then be placed 'inside' this box and overlapp it according to the specified loc parameter. So loc specifies where inside the box the legend sits.

Also see this question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712