色條刻度標籤#

垂直色條在 y 軸上顯示刻度、刻度標籤和標籤,水平色條則在 x 軸上顯示。 ticks 參數可用於設定刻度,而 format 參數可用於格式化可見色條軸的刻度標籤。若要進一步調整,可以使用色條的 ax 屬性擷取其 yaxisxaxis 軸。

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.548 秒)

由 Sphinx-Gallery 產生的範例集