19. Histograms with Matplotlib
By Bernd Klein. Last modified: 26 Apr 2023.
It's hard to imagine that you open a newspaper or magazin without seeing some bar charts or histograms telling you about the number of smokers in certain age groups, the number of births per year and so on. It's a great way to depict facts without having to use too many words, but on the downside they can be used to manipulate or lie with statistics as well. They provide us with quantitative information on a wide range of topics. Bar charts and column charts clearly show us the ranking of our top politicians. They also inform about consequences of certain behavior: smoking or not smoking. Advantages and disadvantages of various activities. Income distributions and so on. On the one hand, they serve as a source of information for us to see our own thinking and acting in statistical comparison with others, on the other hand they also - by perceiving them - change our thinking and acting in many cases.
However, we are primarily interested in how to create charts and histograms in this chapter. A splendid way to create such charts consists in using Python in combination with Matplotlib.
What is a histogram? A formal definition can be: It's a graphical representation of a frequency distribution of some numerical data. Rectangles with equal width have heights with the associated frequencies.
If we construct a histogram, we start with distributing the range of possible x values into usually equal sized and adjacent intervals or bins.
We start now with a practical Python program. We create a histogram with random numbers:
import matplotlib.pyplot as plt
import numpy as np
gaussian_numbers = np.random.normal(size=10000)
gaussian_numbers
OUTPUT:
array([ 0.13541263, -0.23671488, -0.0991283 , ..., -1.26408285,
0.0923674 , 1.49284271])
plt.hist(gaussian_numbers)
plt.title(