DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Python Histograms | Matplotlib Tutorial in Python | Chapter 6

  • 4 minutes read
  • 4562 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

Chapter 6 - Data Types & Variables
By Udit Vashisht

Variables and Identifiers in Python

If we go by the dictionary meaning ‘Variable’ is something which is ‘able to be changed or adapted’. Which is true to much extent in terms of Python programming language also. Variable is basically a reference to the memory location where an object is ...

Read More
Chapter 4 - Print function
By Udit Vashisht

How to use Python print() function?

In the early days of your python learning, one function that you are going to use the most is the print() function. So, I have decided to add it in the opening chapter of this tutorial. In addition to the print function, you ...

Read More
How to fill area between the Line Plots? | Matplotlib Tutorial in Python | Chapter 5
By Udit Vashisht

How to fill area between the line plots in Matplotlib?

You can easily fill the area with any color between the lines or under a curve in Matplotlib Line Plots using plt.fill_between().

Parameters of matplotlib.pyplot.fill_between() or plt.fill_between()

The syntax for plt.fill_between() is :

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, ...

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 python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python