python数据科学(八) matplotlib图例风格与配色方案

本文最后更新于:2023年4月15日 晚上

1 | 配置图例

plt.legend()用于创建最简单的图例, 下面展示图例的默认配置

1
2
3
4
5
6
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label = 'Sine')
ax.plot(x, np.cos(x), '--r', label = 'Cosine')
ax.axis('equal')
leg = ax.legend()

我们经常需要对图例进行各种个性化的配置, 下面给出几个例子:

1 | 左上角, 取消外边框

1
2
ax.legend(loc = 'upper left', frameon = False)
fig

2 | 下端居中, 分两列显示(ncol)

1
2
ax.legend(frameon = False, loc = 'lower center', ncol = 2)
fig

3 | 定义圆角边框fancybox并指定大小borderpad, 增加阴影shadow, 改变外边框透明度framealpha

1
2
ax.legend(fancybox = True, framealpha = 1, shadow = True, borderpad = 1)
fig

1-1 | 选择图例显示的元素

图例会默认显示所有元素的标签, 如果想只显示部分, 可以采用如下方法:

方法1: 将需要显示的线条传入plt.legend

1
2
3
y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
plt.legend(lines[:2], ['first', 'second']) # 一共四条线, 给前两条设置图例

方法2: 只为需要在图例中显示的元素设置label

因为legend只显示有label的线

1
2
3
4
plt.plot(x, y[:, 0], label = "first")
plt.plot(x, y[:, 1])
plt.plot(x, y[:, 2], label = "third")
plt.legend()

1-2 | 在图例中显示不同尺寸的点

比如我们有一个人口统计图, 想用不同尺寸的点表示不同人口数量级

首先创建一个不带标签的散点图

1
2
3
4
5
6
7
8
9
10
11
cities = pd.read_csv('./california_cities.csv')
lat, lon = cities['latd'], cities['longd'] # 经纬度
population, area = cities['population_total'], cities['area_total_km2'] # 人口地区
fig, ax = plt.subplots()
# 用不同尺寸散点图表示数据, 但是不带标签
ax0 = ax.scatter(lon, lat, label = None, c = np.log10(population), cmap = 'viridis', s = area, linewidth = 0, alpha = 0.5)
ax.axis(aspect = 'equal') # 宽高相等
ax.set_xlabel('longitude')
ax.set_ylabel('latitude')
fig.colorbar(ax0, label = 'log$_{10}$(population)')
ax0.set_clim(3, 7)

然后创建图例, 将两张图叠在一起(利用ax)

1
2
3
4
5
# 下面创建图例
for area in [100, 300, 500]:
ax.scatter([], [], c = 'k', alpha = 0.3, s = area, label = str(area) + ' km$^2$')
ax.legend(scatterpoints = 1, frameon = False, labelspacing = 1, title = 'city area')
fig

2 | 配置颜色条

plt.colorbar()可以创建最简单的颜色条

可以用cmap设置不同配色方案, 如cmap = ‘gray'设置灰度配色方案:

配色

2-1 | 颜色条扩展

可以通过clim指定颜色条的范围(上下限), 并用extend参数表示超过上下限的数

e.g.

通过增加一些噪点(远大于平均数据/远小于平均数据)来展示extend的作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
speckles = (np.random.random(I.shape) < 0.01)
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles))
plt.figure(figsize = (15, 4))
plt.subplot(1, 3, 1)
plt.imshow(I, cmap = 'RdBu')
plt.colorbar()
plt.subplot(1, 3, 2)
plt.imshow(I, cmap = 'RdBu')
plt.colorbar(extend = 'both') # both / max / min / neither
plt.clim(-1, 1)
plt.subplot(1, 3, 3)
plt.imshow(I, cmap = 'RdBu')
plt.colorbar(extend = 'max')
plt.clim(-2, 1)

可以看到最左边一张图显示噪点的范围完全覆盖了我们感兴趣的数据, 我们可以通过plt.colorbar(extend = 'both')来进行扩展, 并用clim设置颜色条的上下限, 当超过上限或者低于下限时, 如果设置扩展, 将以一种颜色表示(比如上图超过1都用深蓝色表示, 低于-1都用深红色表示)

2-2 | 离散型颜色条

利用plt.cm.get_cmap()函数将配色方案和需要的离散区间数量传入即可

e.g.

1
2
3
plt.imshow(I, cmap = plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1)


python数据科学(八) matplotlib图例风格与配色方案
https://blog.roccoshi.top/posts/29473/
作者
RoccoShi
发布于
2021年1月26日
许可协议