Histograms In Python

Hi there. I have been playing around with plotting histograms in Python with the Numpy and matplotlib packages. Here is some stuff I have done in Python.

 


Sections

A Histogram Of Simulated Uniform Random Variables

A Histogram Of Simulated Standard Normal Random Variables

References

 


A Histogram Of Simulated Uniform Random Variables

Before plotting anything in Python, it is important to import the necessary packages. In Python, you need this code:

 

From the numpy package, I use the random function to generate (simulate) random variables. In this example, I generate 10 000 standard uniform random variables with np.random.uniform() with low = 0 and high = 1 in its arguments.

To set up the histogram, I need plt.gca() to get the current axes.

The remaining code below shows how to format the histogram in terms of bins, bar colours, labels and the title. To show the histogram, the function plt.show() does the trick.

The histogram plot turns out nicely for the most part. The shape of all the bars does not exactly turn out to be a rectangle but I would assume that with a larger sample size, this shape would look much closer to a rectangle that the plot above.

 


A Histogram Of Simulated Standard Normal Random Variables

In this example, I work with simulating standard normal random variables. The code is not much different than the one before. Slight modifications include the random function, the bar colour, the number of bins and labels.

Note that when you use the random.standard_normal() function, it is implied that the mean = 0  and the standard deviation = 1. The only argument in random.standard_normal() is the size.

 


References

  • http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html
  • Python Data Visualization Cookbook by Igor Milovanovic
  • https://docs.scipy.org/doc/numpy-1.12.0/reference/routines.random.html