Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting Matplotlib Legend Best Location options

In Matplotlib, the legend has a parameter loc that allows to specify the location of the legend.

The user can force the legend to be in 9 different locations or let matplotlib decide where is the best location for the Legend.

From the documentation:

The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure.

The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure.

The string 'center' places the legend at the center of the axes/figure.

The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists.

Now, I want to force the legend to be on the right part of the plot, but depending on the data, the best location could be 'upper right' or 'lower right'.

I don't want the legend to be placed on the left or on the center, but I still want the best location between 'upper right' or 'lower right' to be calculated.

According to the documentation the Best location is calculated by calculating the minimum overlap with other drawn artists

Is there a way of limiting the best option to take only certain options in account and not among the nine locations? Or to manually call the function that calculates this overlap with only the desired options?


1 Answers

You can restrict the area that matplotlib considers for the calculation of the best position by using the bbox_to_anchor keyword:

import matplotlib.pyplot as plt
import numpy as np


fig, (ax1, ax2) = plt.subplots(2)

x = np.arange(10)
ax1.plot(x, x**2, label="best location")
ax1.legend(loc="best")    

ax2.plot(x, x**2, label="best right location")
#bbox signature (left, bottom, width, height) 
#with 0, 0 being the lower left corner and 1, 1 the upper right corner
ax2.legend(loc="best", bbox_to_anchor=(0.6, 0., 0.4, 1.0)) 

plt.show()

Sample output:

enter image description here

like image 152
Mr. T Avatar answered Oct 31 '25 12:10

Mr. T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!