在 Python 的绘图库 Matplotlib 中,图例的位置可以通过 legend()
函数的 loc
参数来设置。loc
参数指定图例放置的位置,支持多种方式定义位置。
常用方法
-
使用预定义位置代码:
Matplotlib 提供了多个预定义的位置代码,可以直接传入loc
参数。'best'
或0
: 自动选择最佳位置(默认)。'upper right'
或1
: 右上角。'upper left'
或2
: 左上角。'lower left'
或3
: 左下角。'lower right'
或4
: 右下角。'right'
或5
: 图形右侧中间。'center left'
或6
: 图形左侧中间。'center right'
或7
: 图形右侧中间。'lower center'
或8
: 图形底部中间。'upper center'
或9
: 图形顶部中间。'center'
或10
: 图形正中心。
示例代码:
import matplotlib.pyplot as pltx = [1, 2, 3] y1 = [1, 4, 9] y2 = [2, 3, 8]plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2')# 设置图例位置为右上角 plt.legend(loc='upper right')plt.show()
-
自定义位置:
如果需要更精确地控制图例的位置,可以使用bbox_to_anchor
参数。这个参数允许将图例放置在轴外的任意位置。示例代码:
import matplotlib.pyplot as pltx = [1, 2, 3] y1 = [1, 4, 9] y2 = [2, 3, 8]plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2')# 使用 bbox_to_anchor 自定义图例位置 plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))plt.show()
在这个例子中,
bbox_to_anchor=(1.05, 1)
将图例放在图形的右上角之外。 -
调整图例样式:
除了位置,还可以通过其他参数调整图例的样式,例如:fontsize
: 设置字体大小。frameon
: 是否显示图例边框。ncol
: 设置图例的列数。
示例代码:
import matplotlib.pyplot as pltx = [1, 2, 3] y1 = [1, 4, 9] y2 = [2, 3, 8]plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2')# 调整图例样式 plt.legend(loc='upper right', fontsize=12, frameon=False, ncol=2)plt.show()
- 使用
loc
参数选择预定义的图例位置。 - 使用
bbox_to_anchor
参数实现更灵活的自定义位置。 - 结合其他参数(如
fontsize
和ncol
)进一步优化图例的外观。