在 matplotlib colorbar 中设置次要刻度数

Set the number of minor ticks in matplotlib colorbar

我可以使用从 here:

借用的以下代码来设置颜色条的主要刻度数
cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)

是否有类似的方法来设置颜色条的小刻度?

您可以使用AutoMinorLocator设置次要刻度数(注意设置n=4时,其中一个主要刻度被算作1)。这是一个例子:

import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, ScalarFormatter
import numpy as np

data = np.random.rand(10, 10)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))

img1 = ax1.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar1 = plt.colorbar(img1, ax=ax1)
ax1.set_title('default colorbar ticks')

img2 = ax2.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar2 = plt.colorbar(img2, ax=ax2)
# 3 major ticks
cbar2.ax.locator_params(nbins=3)
# 4 minor ticks, including one major, so 3 minor ticks visible
cbar2.ax.yaxis.set_minor_locator(AutoMinorLocator(n=4))
# show minor tick labels
cbar2.ax.yaxis.set_minor_formatter(ScalarFormatter())
# change the color to better distinguish them
cbar2.ax.tick_params(which='minor', color='blue', labelcolor='crimson')
ax2.set_title('3 major, 4 minor colorbar ticks')

plt.tight_layout()
plt.show()