How to plot histograms in python3 using matplotlib
I was asked by a friend the other day, how to plot a histogram with python3.
Prerequisites:
Have matplotlib installed, as well as numpy for array operations
pip3 install matplotlib numpy
Code example:
import numpy as np
from matplotlib import pyplot as plt
network = np.array([17.2,22.1,18.5,17.2,18.6,14.8,21.7,15.8,16.3,22.8,24.1,13.3,16.2,17.5,19.0,23.9,14.8,22.2,21.7,20.7,13.5,15.8,13.1,16.1,21.9,23.9,19.3,12.0,19.9,19.4,15.4,16.7,19.5,16.2,16.9,17.1,20.2,13.4,19.8,17.7,19.7,18.7,17.6,15.9,15.2,17.1,15.0,18.8,21.6,11.9])
plt.hist(network, bins=6)
plt.show()
which creates a graph like this:
Explanation:
First, we import numpy as np for short. Using the keyword 'as' essentially renames numpy to np so it's easier to type. Next, we need to import the pyplot class which is within matplotlib, then we rename pyplot to plt
import numpy as np
from matplotlib import pyplot as plt
Next, we declare our data. In this case, we will name our array 'network'.
network = np.array([17.2,22.1,18.5,17.2,18.6,14.8,21.7,15.8,16.3,22.8,24.1,13.3,16.2,17.5,19.0,23.9,14.8,22.2,21.7,20.7,13.5,15.8,13.1,16.1,21.9,23.9,19.3,12.0,19.9,19.4,15.4,16.7,19.5,16.2,16.9,17.1,20.2,13.4,19.8,17.7,19.7,18.7,17.6,15.9,15.2,17.1,15.0,18.8,21.6,11.9])
Finally, we create a histogram using matplotlib's pyplot 'hist' function. Right now, we are only going to be using the 'bins' extra parameter. A full documentation of how to use hist can be found here
plt.hist(network, bins=6)
plt.show()
Above, we specify the number of 'bins', or 'buckets' to group the values by. We can get fancy and specify spacing and more but for now we will just bin the data into 6 buckets.
After specifying your plots, it is important to always call plt.show()
in order for the plots to be drawn!