I generate an N-dimensional histogram via numpy
's histogramdd, with dimensions varying between 2-5. I need to plot a 2-dimensional histogram of its first two dimensions, ie:
When there's only two dimensions, I can do that easily as shown below. How can I generalize this code to N dimensions so that it will always plot the first two?
import numpy as np
import matplotlib.pyplot as plt
dims = np.random.randint(2, 5)
print('Dimensions: {}'.format(dims))
N_pts = np.random.randint(100, 500)
print('Points: {}'.format(N_pts))
A_pts, bin_edges = [], []
for _ in range(dims):
d_min, d_max = np.random.uniform(-1., 1.), np.random.uniform(-1., 1.)
sample = np.random.uniform(d_min, d_max, N_pts)
A_pts.append(sample)
# Define bin edges separately, since they come from somewhere else.
bin_edges.append(np.histogram(sample, bins='auto')[1])
# Obtain N-dimensional histogram
A_h = np.histogramdd(A_pts, bins=bin_edges)[0]
print(np.shape(A_h))
# Subplots.
fig = plt.figure()
ax0 = fig.add_subplot(1, 2, 1)
ax1 = fig.add_subplot(1, 2, 2)
# 2D histogram x,y ranges
x_extend = [min(A_pts[0]), max(A_pts[0])]
y_extend = [min(A_pts[1]), max(A_pts[1])]
# Scatter plot for A.
ax0.invert_yaxis()
ax0.set_xlim(x_extend)
ax0.set_ylim(y_extend)
ax0.scatter(A_pts[0], A_pts[1], c='b', label='A')
for x_ed in bin_edges[0]:
# vertical lines
ax0.axvline(x_ed, linestyle=':', color='k', zorder=1)
for y_ed in bin_edges[1]:
# horizontal lines
ax0.axhline(y_ed, linestyle=':', color='k', zorder=1)
# 2D histogram.
# Grid for pcolormesh, using first two dimensions
X, Y = np.meshgrid(bin_edges[0], bin_edges[1])
HA = np.rot90(A_h)
HA = np.flipud(HA)
ax1.pcolormesh(X, Y, HA, cmap=plt.cm.Blues)
# Manipulate axis and ranges.
ax1.invert_yaxis()
ax1.set_xlim(x_extend)
ax1.set_ylim(y_extend)
fig.subplots_adjust(hspace=1)
plt.show()