Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bbox_to_anchor and loc in matplotlib

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.

like image 601
user3897208 Avatar asked Jul 31 '14 20:07

user3897208


People also ask

How do I control the Legend position in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

What is a legend in Matplotlib?

Matplotlib has native support for legends. Legends can be placed in various positions: A legend can be placed inside or outside the chart and the position can be moved. The legend() method adds the legend to the plot. In this article we will show you some examples of legends using matplotlib. Related course.

How do I make the legend horizontal in Matplotlib?

Set the figure size and adjust the padding between and around the subplots. Using plot() method, plot lines with the labels line1, line2 and line3. Place a legend on the figure using legend() method, with number of labels for ncol value in the argument.


1 Answers

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

like image 88
Gabriel Avatar answered Oct 07 '22 09:10

Gabriel