从色图中选择单个颜色#

有时我们希望使用比默认颜色循环提供的更多颜色或不同的颜色集。从提供的颜色映射中选择个别颜色可以是一种方便的方式来实现这一点。

我们可以通过调用任何 Colormap 并传入一个浮点数或一个范围在 [0, 1] 内的浮点数列表来获取颜色;例如 cmap(0.5) 将给出中间颜色。另见 Colormap.__call__

从连续色图中提取颜色#

import matplotlib.pyplot as plt
import numpy as np

import matplotlib as mpl

n_lines = 21
cmap = mpl.colormaps['plasma']

# Take colors at regular intervals spanning the colormap.
colors = cmap(np.linspace(0, 1, n_lines))

fig, ax = plt.subplots(layout='constrained')

for i, color in enumerate(colors):
    ax.plot([0, i], color=color)

plt.show()
individual colors from cmap

从离散色图中提取颜色#

ListedColormap 中所有颜色的列表可以通过 colors 属性获取。

colors = mpl.colormaps['Dark2'].colors

fig, ax = plt.subplots(layout='constrained')

for i, color in enumerate(colors):
    ax.plot([0, i], color=color)

plt.show()
individual colors from cmap

另见#

有关操作色图的更多详细信息,请参阅 在 Matplotlib 中创建 Colormap。要更改默认颜色循环,请参阅 使用 cycler 进行样式设置

参考文献

以下函数、方法、类和模块的使用在本示例中展示:

由 Sphinx-Gallery 生成的图库