Plotting Histogram


There are two way of making histogram in python:

  1. pyplot.hist()
  2. numpy.histogram()

pyplot.hist


Let's plot the histgram of a zero mean Gaussian random number

In [2]:
import numpy as np
import matplotlib.pyplot as plt
In [39]:
Ns=10000 # number of random samples 
r=np.random.randn(Ns)  # Random Number itself
fig1=plt.figure(figsize=[9,7])
plt.hist(r, bins=30, color='C9',histtype='step', lw=3 ,label='Normal Random No ')
# bins give number of x points, histtype=step gives only outline, lw is for linewidth
plt.hist(r, bins=30, color='C1',histtype='bar',align='mid' ,alpha=0.3 , rwidth=0.8)
# rwidth, gives the width of bar w.r.t size of bin!
plt.grid(color='r', alpha=0.3)
plt.legend()
plt.show()
# Not that two hist are plotted one over other step and bar to give nice look
In [40]:
x=np.linspace(-4,4,100) # value at which count need to be done, it can be passed to hist
values=plt.hist(r, bins=x, histtype='step', lw=3 )  
## Same can be done with np.histogram, wihtout plot shown 
counts=values[0]  # first array is count 
bins=x[0:-1]+(x[1]-x[0])/2  # need to shifted middle of bin!
In [41]:
fig1=plt.figure(figsize=[9,7])
plt.plot(bins, counts, color='C1',lw=2)
plt.grid(color='C3', alpha=0.1)

plt.hist2d


There is a 2-D function which is more interesting

In [62]:
Ns2=1000
rx=np.random.randn(Ns2)
ry=np.random.randn(Ns2) 
bins=30
h1=np.histogram(rx,bins=bins)
h2=np.histogram(ry,bins=bins)
x1=h1[1][0:-1]+
h1h2=np.outer(h1[0], h2[0])
plt.hist2d(rx,ry, bins=bins, alpha=0.5)
plt.pcolor(h1[1][0:-1],h1[1][0:-1], h1h2, alpha=0.5)
plt.show()