I have this codeimport matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FixedLocator, StrMethodFormatter
np.random.seed(42)
x = np.random.rand(100) * 100
y = np.random.rand(100) * 100
z = np.random.rand(100) * 100
fig, ax = plt.subplots(figsize=(10, 8), dpi=100)
hb = ax.hexbin(x, y, C=z, gridsize=30, cmap="plasma", reduce_C_function=np.mean)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_title("Hexbin KDE Plot with Colorbar Ticks Issue")
cbar = fig.colorbar(hb, ax=ax, shrink=0.8, aspect=20)
cbar.set_label("Density")
ymin, ymax = y.min(), y.max()
zmin, zmax = z.min(), z.max()
ticklocs = FixedLocator(np.linspace(ymin, ymax, 6))
ticklocs2 = FixedLocator(np.linspace(zmin, zmax, 6))
tickfrmt = StrMethodFormatter("{x:.0f}")
tickfrmt2 = StrMethodFormatter("{x:.0f}")
ax.yaxis.set_major_locator(ticklocs)
ax.yaxis.set_major_formatter(tickfrmt)
cbar.locator = ticklocs2
cbar.formatter = tickfrmt2
cbar.update_ticks()
plt.tight_layout()
plt.show()
But the colorbar does not show the ticks. I have tried adding the text manually using fig.text()
but it does not work as well.
How could I display colorbar ticks for the hexbin plot?
Update: currently the output is
And you can see no ticks in colorbar ( I am using Google Colab).
2