How to plot a histogram using matplotlib in python?

How to plot a histogram using matplotlib in python?

According to matplotlib official, Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Matplotlib has pyplot as a module that provides a MATLAB-like interface. It is designed to be as applicable as MATLAB, with the ability to use python, and being opensource. There are various plotting techniques in matplotlib pyplot like line plot, histogram, scatter plot, 3D plot, Image plot, Contour plot, Scatter plot, Polar plot, Line plot, 3-D plot and Image plot. Get some insights into histogram with this image from matplotlib official website.

histogram, matplotlib

A histogram is an appropriate visual representation of the distribution of numerical or categorical data. It is a graphical display of data using bars of different heights. Each bar in histogram falls into some range. If the bar is taller than more data falls under that range (bin) than others. Here are the basics of how to plot with histogram, other details are to be explored by yourself. If you have not installed matplotlib library than the easiest way to install using pip.

pip install matplotlib

Here is the basic snippet to visualize using histogram from matplotlib.


import matplotlib.pyplot as plt
x = [val1, val2, val3,....]
plt.hist(x, bins = number of bins)
plt.show()

Here, pyplot module is alias to plt and data is stored in x. plt.hist() is a method to create using histogram with number of bins (default is 10). Histogram only get displayed after you use plt.show() method.

Label Axis 

Example given below has x axis labelled as “count” and y-axis as “petal length(cm)”. It is appropriate to give units in the labels.

plt.ylabel('count')
plt.xlable('petal length (cm)')

Style your histogram

Example below is one of the style of histogram for more explore .

plt.style.use('ggplot')

For more details explore the official site.

Leave a Reply

Your email address will not be published. Required fields are marked *