Matplotlib系列之图例设置

当一张图中有多根曲线时,我们可以通过图例legend来对曲线进行注释区分。本文主要介绍matplotlib包的图例legend用法。

数据准备

本文的示例数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

x = np.linspace(-2,2,20)
y1 = 2*x+1
y2 = x**2

fig, ax = plt.subplots()

l1, = ax.plot(x, y1, color = sns.xkcd_rgb["pale red"], linestyle = '-', label = '2*x+1')
l2, = ax.plot(x, y2, color = sns.xkcd_rgb["denim blue"], linestyle = '-', label = 'x**2')

ax.legend()
plt.show()

图例位置

loc参数快速调整

我们可以通过loc参数进行快速放置:

1
ax.legend(loc = 0)

loc不同的值代表不同的位置,具体对应表如下:

Location String Location Code
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

bbox_to_anchor参数手动控制

不过loc没有选项可以直接将legend放置到坐标轴外侧,这时候,我们可以用bbox_to_anchor参数来手动控制。

注意:直接将图例放置到坐标轴之外也会直接放置到绘图区外了,因而我们需要先调整坐标轴在绘图区的位置

1
2
3
4
5
# 首先调整坐标轴在绘图区的位置  
ax.set_position([0.1,0.1,0.6,0.9])

# 图例放置
ax.legend(bbox_to_anchor=(1.05,0.8))

全部代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

x = np.linspace(-2,2,20)
y1 = 2*x+1
y2 = x**2

fig, ax = plt.subplots()

# 首先调整坐标轴在绘图区的位置
ax.set_position([0.1,0.1,0.6,0.9])

l1, = ax.plot(x, y1, color = sns.xkcd_rgb["pale red"], linestyle = '-', label = '2*x+1')
l2, = ax.plot(x, y2, color = sns.xkcd_rgb["denim blue"], linestyle = '-', label = 'x**2')

# 图例放置
ax.legend(bbox_to_anchor=(1.05,0.8))

plt.show()

我们可以通过ncol这个参数来调整图例的列数

1
ax.legend(bbox_to_anchor=(0.8,1.2), ncol = 2)

实现多个图例

不带参数调用legend()会自动获取图例句柄及其相关标签。此函数等同于:

1
2
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

因此,如果我们想要实现多个图例,我们可以手动控制handles参数。

首先,我试试直接采用多次调用legend()函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

x = np.linspace(-2,2,20)
y1 = 2*x+1
y2 = x**2

fig, ax = plt.subplots()

l1, = ax.plot(x, y1, color = sns.xkcd_rgb["pale red"], linestyle = '-', label = '2*x+1')
l2, = ax.plot(x, y2, color = sns.xkcd_rgb["denim blue"], linestyle = '-', label = 'x**2')

ax.legend(handles = [l1], loc = 1)
ax.legend(handles = [l2], loc = 2)

plt.show()

我们发现轴域上只存在一个图例。这样做是为了可以重复调用legend(),将图例更新为轴域上的最新句柄。因此,如果我们要保留旧的图例实例,必须将它们手动添加到轴域中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

x = np.linspace(-2,2,20)
y1 = 2*x+1
y2 = x**2

fig, ax = plt.subplots()

l1, = ax.plot(x, y1, color = sns.xkcd_rgb["pale red"], linestyle = '-', label = '2*x+1')
l2, = ax.plot(x, y2, color = sns.xkcd_rgb["denim blue"], linestyle = '-', label = 'x**2')

# 第一个线条创建图例
first_legend = plt.legend(handles=[l1], loc=1)
# 手动将图例添加到当前轴域
ax = plt.gca().add_artist(first_legend)
# 第二个线条创建另一个图例
plt.legend(handles=[l2], loc=4)

plt.show()

图例边框和背景设置

1
2
3
4
5
6
7
8
# 去掉图例边框
plt.legend(loc='best',frameon=False)

# 设置图例边框颜色
plt.legend(loc='best',edgecolor='blue')

# 设置图例背景颜色,若无边框,参数无效
plt.legend(loc='best',facecolor='blue')

一个去掉图例边框的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

x = np.linspace(-2,2,20)
y1 = 2*x+1
y2 = x**2

fig, ax = plt.subplots()

l1, = ax.plot(x, y1, color = sns.xkcd_rgb["pale red"], linestyle = '-', label = '2*x+1')
l2, = ax.plot(x, y2, color = sns.xkcd_rgb["denim blue"], linestyle = '-', label = 'x**2')

ax.legend(frameon=False)
plt.show()

参考


----------- 本文结束啦感谢您阅读 -----------

赞赏一杯咖啡