I am able to set the number of major ticks of the colorbar using the following code borrowed from here:
cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)
Is there a similar way of setting the minor ticks of the colorbar?
You can use the AutoMinorLocator
to set the number of minor ticks (note that when setting n=4
, one of the major ticks is counted as 1
). Here is an example:
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()