Home > database >  matplotlib hist2d: how to show counts on colorbar
matplotlib hist2d: how to show counts on colorbar

Time:09-16

I want to plot two heatmaps side by side, using figures and axes, but I can't seem to get the colorbar to show the counts for each color.

It works when I use the procedural style like this:

x1 = np.random.normal(size=1000)
y1 = np.random.normal(size=1000)
cmap = mpl.cm.plasma
plt.hist2d(x1, y1, cmap=cmap, bins=30)
plt.colorbar()
plt.show()

using plt.hist2d()

but not when I uses the OOP style:

x1 = np.random.normal(size=1000)
y1 = np.random.normal(size=1000)
fig, ax1 = plt.subplots(1, 1)
cmap = mpl.cm.plasma
ax1.hist2d(x1, y1, cmap=cmap,  bins=30)
fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap), ax=ax1)
plt.show()

with fig.hist2d()

CodePudding user response:

The problem has to do with normalization of data for 2d histograms. The solution is here.

CodePudding user response:

Thank you @JustLearning

I used numpy's histogram2d to get the values and then normalized it as follows:

h, xe, ye = np.histogram2d(x1, y1)
vmin = np.min(h)
vmax = np.max(h)
cmap = mpl.cm.plasma
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)

fig, ax1 = plt.subplots(1, 1)
ax1.hist2d(x1, y1, cmap=cmap,  bins=30)
fig.colorbar(mappable=sm, ax=ax1)
plt.show()
  • Related