限制 Matplotlib 图例最佳位置选项

Restricting Matplotlib Legend Best Location options

在 Matplotlib 中,图例有一个参数loc,允许指定图例的位置。

用户可以强制图例位于 9 个不同的位置,或者让 matplotlib 决定图例的最佳位置。

来自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.

现在,我想强制图例位于图的右侧,但根据数据,最佳位置可能是 'upper right' 或 'lower right'。

我不希望图例放在左边或中间,但我仍然希望计算'upper right'或'lower right'之间的最佳位置。

根据文档,最佳位置是通过计算 the minimum overlap with other drawn artists

有没有办法限制 best 选项只考虑某些选项,而不考虑九个位置?或者手动调用仅使用所需选项计算此重叠的函数?

您可以使用 bbox_to_anchor 关键字限制 matplotlib 为 calculation of the best position 考虑的区域:

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

示例输出: