在Python中,使用matplotlib库画图时,可以通过调整`loc`和`bbox_to_anchor`参数来设置图例的位置。以下是具体的方法和参数说明:
使用`loc`参数
`loc`参数接受字符串或数字,用于指定图例的大致位置。
字符串参数包括:
`upper right` (右上角)
`upper left` (左上角)
`lower left` (左下角)
`lower right` (右下角)
`right` (与`center right`位置相同)
`center left` (中间偏左)
`center right` (中间偏右)
`lower center` (中间偏下)
`upper center` (中间偏上)
`center` (正中间)
数字参数对应的位置如下:
`1`:右上角
`2`:左上角
`3`:左下角
`4`:右下角
`5`:正右(与`center right`相同)
`6`:正左(与`center left`相同)
`7`:正下(与`lower center`相同)
`8`:正上(与`upper center`相同)
`9`:正中央
`10`:自动寻找最佳位置
使用`bbox_to_anchor`参数
`bbox_to_anchor`参数是一个二元组,用于微调图例的位置。
`num1`:控制图例的左右移动,值越大越向右移动。
`num2`:控制图例的上下移动,值越大越向上移动。
示例代码
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in range(5):
ax.plot(x, i * x, label=f'$y = {i}x$')
设置图例位置
plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1.05)) 将图例放置在右上角外部
plt.show()
通过上述代码,你可以根据需要调整图例的位置。如果需要将图例放置在图像外侧,可以通过设置`bbox_to_anchor`参数中的`num1`和`num2`值来实现。