Search code examples
pythonmatplotliblabelcolorbar

Minor ticks do not display properly


With the following code, I get a colorbar with min value of 1 (0 value is transparent due to mincnt=1 in the hexbin() method). Minor ticks are correctly displayed.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# Create figure
fig = plt.figure(figsize=(3, 2))

# Data
vals_x = np.random.standard_normal(10000)
vals_y = np.random.standard_normal(10000)

# Plot data
ax = plt.subplot(111)
h = ax.hexbin(vals_x, vals_y, gridsize=40, extent=(-2, 2,-2, 2), 
              mincnt=1, cmap=cm.viridis_r, edgecolors='k', lw=0.025)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)

# Show colorbar
axin = ax.inset_axes([0.02, 0.57, 0.03, 0.4])
cbar = plt.colorbar(h, cax=axin)
cbar.ax.tick_params(which='major', size=6, width=0.5)
cbar.ax.tick_params(which='minor', size=3, width=0.3)
ticks = cbar.get_ticks()
if False:
    ticks = np.insert(ticks, 0, 1) # add 1
cbar.set_ticks(ticks)
cbar.minorticks_on()

enter image description here

However, if I add "1" as a first major tick (by switching False to True in the code above), the minor ticks do not display properly anymore. enter image description here

Any idea how to fix this? Thanks!


Solution

  • Importing MultipleLocator with from matplotlib.ticker import MultipleLocator and adding cbar.ax.yaxis.set_minor_locator(MultipleLocator(ticks[1]/5)) solves the problem. However, it does not explain it.