Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
restrepo
GitHub Repository: restrepo/ComputationalMethods
Path: blob/master/activities/histogram2d-example.ipynb
934 views
Kernel: Unknown Kernel

Example of 2D-Histograms

For this example, we are going to make a 2D histogram of a randomly generated data of some human population, comprising age and height. For this we are going to use the random module of the library NumPy.

import numpy as np %pylab inline import matplotlib.pyplot as plt
Populating the interactive namespace from numpy and matplotlib

Let's assume a set of 50 entries with 3 values each one. The first one is an age, the second one is a height and the thrid one is the number of people who meet the first two conditions.

#Number of entries Ndata = 50 #Generating ages [from 20 to 80 years old] ages = np.random.randint( 20, 50, Ndata ) #Generating heights [from 150cm to 190cm] heights = np.random.randint( 150, 190, Ndata ) #Number of people in each category [from 10 people to 100 people] people = np.random.randint( 10, 100, Ndata )

The objetive now is to make a 2D histogram of age vs height. The function histogram2d allows to use different bins in each axis.

#Returns: # 2D histogram with counts (H) # x coordinate with ranges (x) # y coordinate with ranges (y) H, x, y = np.histogram2d( ages, heights, bins=(4,4), weights = people ) #It is necessary to transpose the 2D Histogram in order to a proper plotting H = np.transpose( H[:,::-1] )
#Plotting the histogram using the imshow function plt.figure( figsize=(8,8) ) #Arguments: # 2D histogram with counts (H) # extent: ranges in the histogram (xmin,xmax,ymin,ymax) # interpolation: type of interpolation between cells. "none" is better for this case. # cmap: color palette used for representing data plt.imshow( H, extent = (20,60,150,190), interpolation="none", cmap="binary" ) #Generating a colorbar for interpreting the data plt.colorbar() #Format of the figure plt.title( "Number of people for different\n ranges of age and heights", fontsize=16 ) plt.xlabel( "Age [years]", fontsize=16 ) plt.ylabel( "Heights [cm]", fontsize=16 )
<matplotlib.text.Text at 0x7fac9b9b7590>