The confusion comes from the fact that the returned counts
array is not what you think it is.
plt.hist2d
internally uses numpy.histogram2d
to compute the two-dimensional histogram. The documentation states as return values:
H
: ndarray, shape(nx, ny)
The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.
xedges
: ndarray, shape(nx,)
The bin edges along the first dimension.
yedges
: ndarray, shape(ny,)
The bin edges along the second dimension.
Apart from the fact that there seems to be a mistake concerning the exact shape of the arrays, we see that the first dimension of the returned histogram array is x
and the second y
.
However, matplotlib always expects y
to be the first dimenstion. Therefore, while plt.hist2d
produces the correct plot, plt.pcolormesh
needs a transposed version of the array.
plt.pcolormesh(X,Y, counts.T)
A full example, comparing plt.hist2d
and plt.pcolormesh
:
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(1,10,10)
y=np.linspace(6,9,10)
zbinsx= np.linspace(0,10,11)
zbinsy= np.linspace(5,10,6)
fig, (ax, ax2) = plt.subplots(ncols=2)
counts,xedges,yedges,d = ax.hist2d(x,y, bins=[zbinsx,zbinsy])
# counts has shape (10, 5)
X,Y = np.meshgrid(xedges,yedges)
mesh1 =ax2.pcolormesh(X,Y, counts.T)
plt.show()