How to plot a histogram in Python using matplotlib

In this tutorial, we will learn how to plot a histogram in Python using Matplotlib.

Histogram in Python using Matplotlib

Firstly, we will look at what is a histogram?
A histogram is used to show data provided in a form of some groups. It is a valid way of displaying numerical data distribution graphically.


To use matplotlib we need to install it using the command

pip install matplotlib

To check the version use the code

 import matplotlib.pyplot as plt


Plotting a histogram requires data to be a variable that takes continuous numeric values. This indicates that regardless of their apparent value, the variances between values are consistent.

A histogram uses bins, bins display numerical data by grouping data into ‘bins’ of the same width. Each bin is plotted as a bar whose height shows the data points in the bin. They are also referred to as “intervals”, “buckets” and “classes”.

For creating a histogram we should have a dataset. We need to know how many bins are required in our graphical representation.

We can select the number of bins as per our business requirement.
The syntax for choosing a bin is as follows,

plt.hist(x,bins=number of bins)


To display the figure we use


Syntax for plotting a histogram using matplotlib Python library is given below:

import matplotlib.pyplot as plt
x= [1,2,15,29,31,41,45,49]

The attribute used as edge color is used to provide color to the border of each bin and gives us a clear understanding of the bins. The attribute width allows us to define the breadth of the bar.


Leave a Reply

Your email address will not be published.