色条刻度标签#

垂直色条在 y 轴上显示刻度、刻度标签和标签,水平色条在 x 轴上显示。参数 ticks 可用于设置刻度,参数 format 可用于格式化可见色条轴(Axes)的刻度标签。如需进一步调整,可通过色条的 ax 属性获取其 yaxisxaxis 轴(Axes)。

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.ticker as mticker

# Fixing random state for reproducibility
rng = np.random.default_rng(seed=19680801)

绘制带有垂直(默认)色条的图

fig, ax = plt.subplots()

data = rng.standard_normal((250, 250))

cax = ax.imshow(data, vmin=-1, vmax=1, cmap='coolwarm')
ax.set_title('Gaussian noise with vertical colorbar')

# Add colorbar, make sure to specify tick locations to match desired ticklabels
cbar = fig.colorbar(cax,
                    ticks=[-1, 0, 1],
                    format=mticker.FixedFormatter(['< -1', '0', '> 1']),
                    extend='both'
                    )
labels = cbar.ax.get_yticklabels()
labels[0].set_verticalalignment('top')
labels[-1].set_verticalalignment('bottom')
Gaussian noise with vertical colorbar

绘制带有水平色条的图

fig, ax = plt.subplots()

data = np.clip(data, -1, 1)

cax = ax.imshow(data, cmap='afmhot')
ax.set_title('Gaussian noise with horizontal colorbar')

# Add colorbar and adjust ticks afterwards
cbar = fig.colorbar(cax, orientation='horizontal')
cbar.set_ticks(ticks=[-1, 0, 1], labels=['Low', 'Medium', 'High'])

plt.show()
Gaussian noise with horizontal colorbar

参考

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

脚本总运行时间: (0 分 2.225 秒)

由 Sphinx-Gallery 生成的画廊