In this Tutorial we will learn how to create Histogram in python using matplotlib with an example. This python Histogram tutorial also includes the steps to create Histogram with step type (no fills) and bar type (with fills).
Create Histogram in Python with no Fills:
import matplotlib.pyplot as plt values = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52] plt.hist(values,5, histtype='step', align='mid', color='g', label='Test Score Data') plt.legend(loc=2) plt.title('Histogram of score') plt.show()
Line 1: Imports the pyplot function of matplotlib library in the name of plt.
Line 3: Inputs the arrays to the variables named values which is score in our case.
Line 4: In hist function, first argument accepts the values to be plotted, second argument is the number of bins, histype=’step’ which plots the histogram in step format, aligned to mid, color chosen is green.
Line 5: Legend function argument loc=2 plots the legend on the top left corner.
Line 6 and Line 7: Assign Title to Histogram and Histogram is plotted.
Histogram in python with Step format is shown below
Create Histogram in Python with bar Filled:
import matplotlib.pyplot as plt values = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52] plt.hist(values,5, histtype='bar', align='mid', color='c', label='Test score Data',edgecolor='black') plt.legend() plt.title('Histogram of score') plt.show()
Line 4: In hist function, first argument accepts the values to be plotted, second argument is the number of bins, histype=’bar’ which plots the histogram in bar filled format, aligned to mid, color chosen is cyan. edgecolor=’black’ indicates the black borders for histogram.
Histogram in python with bar filled format and with black border is shown below,