0%

『Python基础』matplotlib中的colormap

简介

matplotlib 是 Python 中常用的绘图库。本文主要介绍 matplotlib 中的 colormap,即颜色映射。在绘图函数中通常将 colormap 的名称字符串传入 cmap 参数,即可使用该 colormap。下面展示一下 matplotlib 中的 colormap 及其对应的名称。

colormap

  • 均匀连续的颜色序列

Perceptually Uniform Sequential colormaps

  • 单色颜色序列

Sequential colormaps

  • 双色渐变颜色序列

Sequential (2) colormaps

  • 离散颜色序列

Diverging colormaps

  • 循环颜色序列

Cyclic colormaps

  • 渐变色块序列

Qualitative colormaps

  • 混合

Miscellaneous colormaps

  • 可以在 colormap 的名称后面加 _r 来获得逆序的 colormap, 例如:
1
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])

Original and reversed colormaps

演示代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import matplotlib.pyplot as plt

cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)

axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)

for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)

# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()


for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)

参考资料

更多资料可以参考 matplotlib 的文档:https://matplotlib.org/stable/api/pyplot_summary.html

--- ♥ end ♥ ---

欢迎关注我呀~