自定义颜色条教程#

本教程展示了如何构建和自定义独立的色条,即不附带图表的色条。

一个 colorbar 需要一个“可映射” (matplotlib.cm.ScalarMappable) 对象(通常是一张图像),该对象指示要使用的色图和范数。为了在没有附加图像的情况下创建色条,可以使用一个没有关联数据的 ScalarMappable

import matplotlib.pyplot as plt
import matplotlib as mpl

基本连续色条#

在这里,我们创建一个带有刻度和标签的基本连续色条。

colorbar 调用的参数是 `.ScalarMappable`(使用 normcmap 参数构建)、应绘制颜色条的轴,以及颜色条的方向。

更多信息请参见 colorbar API。

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

cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=5, vmax=10)

fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
             cax=ax, orientation='horizontal', label='Some Units')
colorbar only

颜色条附加在现有坐标轴旁边#

本教程中的所有示例(除了这个)都展示了独立的颜色条在其自己的图形上,但可以通过在调用 colorbar() 时传递 ``ax=ax``(意思是“在 ax 旁边绘制颜色条”)而不是 ``cax=ax``(意思是“在 ax 上绘制颜色条”)来在预先存在的 Axes ax 旁边显示颜色条。

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

fig.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(0, 1), cmap='magma'),
             ax=ax, orientation='vertical', label='a colorbar label')
colorbar only

离散和扩展的颜色条,带有连续的颜色标度#

以下示例展示了如何基于连续的 cmap 创建一个离散的颜色条。我们使用 matplotlib.colors.BoundaryNorm 来描述区间边界(这些边界必须按递增顺序排列),并进一步传递 extend 参数以显示“超出”和“低于”颜色(这些颜色用于表示超出 norm 范围的数据)。

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

cmap = mpl.cm.viridis
bounds = [-1, 2, 5, 7, 12, 15]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N, extend='both')

fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
             cax=ax, orientation='horizontal',
             label="Discrete intervals with extend='both' keyword")
colorbar only

带有任意颜色的色条#

以下示例仍然使用 BoundaryNorm 来描述离散区间边界,但现在使用 matplotlib.colors.ListedColormap 将每个区间与任意颜色关联(区间数量必须与颜色数量相同)。使用 Colormap.with_extremes 在颜色映射上设置“溢出”和“下溢”颜色。

我们还向 colorbar 传递了额外的参数:

  • 要在颜色条上显示超出范围的值,我们在调用 colorbar() 时使用 extend 参数。(这等同于在前一个示例中通过 extend 参数传递给 BoundaryNorm 构造函数。)

  • 为了使每个颜色条段的宽度与其对应的区间成比例,我们在 colorbar() 调用中使用 spacing 参数。

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

cmap = (mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan'])
        .with_extremes(under='yellow', over='magenta'))
bounds = [1, 2, 4, 7, 8]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

fig.colorbar(
    mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    cax=ax, orientation='horizontal',
    extend='both',
    spacing='proportional',
    label='Discrete intervals, some other units',
)
colorbar only

带有自定义扩展长度的颜色条#

我们可以自定义带有离散间隔的颜色条的扩展长度。要使每个扩展的长度与内部颜色的长度相同,请使用 extendfrac='auto'

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

cmap = (mpl.colors.ListedColormap(['royalblue', 'cyan', 'yellow', 'orange'])
        .with_extremes(over='red', under='blue'))
bounds = [-1.0, -0.5, 0.0, 0.5, 1.0]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

fig.colorbar(
    mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    cax=ax, orientation='horizontal',
    extend='both', extendfrac='auto',
    spacing='uniform',
    label='Custom extension lengths, some other units',
)

plt.show()
colorbar only

由 Sphinx-Gallery 生成的图库