Home » Python » python – Understanding numpy 2D histogram – Stack Overflow

# python – Understanding numpy 2D histogram – Stack Overflow

Questions:

I have the following 2D distribution of points. My goal is to perform a 2D histogram on it. That is, I want to set up a 2D grid of squares on the distribution and count the number of points that fall within square `i,j`. I came across `numpy.histogram2d(x,y)`, but because I wasn’t too sure about how it operates, I also implemented my own 2D histogram code. I get this rather suprising result, which I cannot make sense of: my histogram is a clockwise-90 degree rotation off from the output of `numpy.histogram2d`. Does anyone know why I’m seeing this behavior? I want to say I’m fairly confident in my own histogram code, so I think there’s something with `numpy` I’m not understanding. Code to produce above:

``````import numpy as np
import matplotlib.pyplot as plt

# ----- Get Data ----- #
n = 5000
uni_X, uni_Y = 2 * np.random.rand(n) - 1, 2 * np.random.rand(n) - 1
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Uniform 2D Distribution')
plt.scatter(uni_X,uni_Y,s=5,c='black')
plt.show()

# ---- numpy histogram ----- #
H, x_edges, y_edges = np.histogram2d(uni_X,uni_Y,bins=20)

# ---- my histogram ----- #
xmin, xmax = -1,1
ymin, ymax = -1,1
dx = 0.1
n_bins = int((xmax-xmin)/dx)
uni_zip = zip(uni_X,uni_Y)
my_H = np.zeros(shape=(n_bins,n_bins))
for tup in uni_zip:
x, y = tup, tup
x_ind, y_ind = int((x-xmin)/dx), int((ymax-y)/dx)
my_H[y_ind,x_ind] += 1

# ----- visualizing data ----- #
plt.subplot(211)
plt.imshow(my_H,extent=(-1,1,-1,1))
plt.title('My hist')
cbar = plt.colorbar()
cbar.set_label('Count')
plt.subplot(212)
plt.imshow(H,extent=(-1,1,-1,1))
plt.title('np.histogram2d')
cbar = plt.colorbar()
cbar.set_label('Count')
plt.show()
``````