Udit Vashisht
Author: Udit Vashisht


Python Histograms | Matplotlib Tutorial in Python | Chapter 6

  • 4 minutes read
  • 102 Views
Python Histograms | Matplotlib Tutorial in Python | Chapter 6

    Table of Contents

Matplotlib Tutorial in Python

Python Histograms | Chapter 6

A Python Histogram/Matplotlib Histogram is an accurate representation of the distribution of numerical data. Bar graphsrelates to two variables, however a Python Histogram relates to only one variable and shows it distribution in different range of the values called “bin” or “bucket”.

Python Histogram in Matplotlib

To create as simple Python Histogram in Matplotlib we will be using plt.hist(). Let us quickly right the following code to plot a simple Python/Matplolib Histogram of ages in Matplotlib.

# python_histogram.py

import matplotlib.pyplot as plt

plt.style.use('ggplot')
ages = [12, 13, 15, 19, 20, 20, 24, 26, 32, 39, 49]
plt.hist(ages)
plt.xlabel("Age")
plt.ylabel("Age Disribution")
plt.title("Age Distribution Histogram")
plt.show()

matplotlib_tutorial_histogram_.png

Python Histogram with bins in Matplotlib

The above Python Histogram is an-auto Python Histogram created by the Matplolib. Now we will define the bins and pass it to plt.hist() to create the Matplotlib Histogram. We can simply choose the number of bins and Matplotlib will distribute the data on the basis of the number of bins provided in the Python Histogram. We will also add border to each bin so that we can distinguish between them easily.

# python_histogram.py

bins = 5
plt.hist(ages, bins = bins, edgecolor = 'black')

matplotlib_tutorial_histogram_bins.png

So, in the above Matplotlib/Python Histogram, the age-range is evenly distributed between 5 bins and each bin has certain number of persons corresponding to that age range.

Instead of Matplotlib doing the distribution in the Histogram, we can also provide the age-range in form of a list.

# python_histogram.py

ages = [12, 13, 15, 19, 20, 20, 24, 26, 32, 39, 49]
bins = [10, 15, 20, 25, 30, 35, 40, 45, 50]
plt.hist(ages, bins=bins, edgecolor='black')

matplotlib_tutorial_histogram_bins_list.png.

So, here instead of providing number of bins, we have provided the list, where two adjacent items represent one bin of that age-group. So, we have 8 age-groups and the Python Histrogram shows the distribution of person in those 8 age groups. We can also, ignore certain ages by just removing them from the bin-range.

# python_histogram.py
ages = [12, 13, 15, 19, 20, 20, 24, 26, 32, 39, 49]
bins = [20, 25, 30, 35, 40, 45, 50]
plt.hist(ages, bins=bins, edgecolor='black')

matplotlib_tutorial_histogram__.png

So, here we have removed two age-bins (age-ranges) i.e. 10-15 and 15-20. Though 12,13,15 are present in the ages but still they are not plotted on the histogram.

Customizing the Python Histogram in Matplotlib

We can further customize our Histograms, like we can draw a verticle line for median age using plt.axvline().

# python_histogram.py

import matplotlib.pyplot as plt

plt.style.use('ggplot')
ages = [12, 13, 15, 19, 20, 20, 24, 26, 32, 39, 49]
bins = [10, 15, 20, 25, 30, 35, 40, 45, 50]
median_age = 20
plt.hist(ages, bins=bins, edgecolor='black')
plt.axvline(median_age, color='blue', label="Median Age")
plt.xlabel("Age")
plt.ylabel("Age Disribution")
plt.title("Age Distribution Histogram")
plt.legend()
plt.show()

matplotlib_tutorial_histogram_!.png

Matplotlib Video Tutorial Series

We are glad to inform you that we are coming up with the Video Tutorial Series of Matplotlib on Youtube. Check it out below.

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

So, here we have a median line of blue color at age 30.

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

In the next chapter we will be learning to create scatterplots in Matplotlib in Python.

If you want to support our work. You can do it using Patreon.



Related Posts

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7
By Udit Vashisht

Scatter Plot in Python using Pandas and Matplotlib

In this tutorial we will learn to create a Scatter Plot in Python using Matplotlib and Pandas. We will use matplotlib.pyplot()’s plt.scatter() to create the scatter plot

What is a Scatter Plot?

Scatter Plot also known as scatter plots ...

Read More
Python unittest module - How to test your python code?
By Udit Vashisht

Python unittest module

Why to unit test your python source code?

All programmers want their code to be impeccable, but as the saying goes, to err is human, we make mistakes and leave bugs in our source code. Here is where the unit testing comes to our rescue. If you ...

Read More
Matplotlib Tutorial in Python | Chapter 1 | Introduction
By Udit Vashisht

Matplotlib Tutorial in Python

In this series of Matplotlib Tutorials in Python, we will cover all the concepts from beginners to expert level. Starting with how to install Matplotlib library to how to create the plots, this series is an exhaustive tutorial and by the end of this series you ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas