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

If __name__ == '__main__' in Python
By Udit Vashisht

What does if __name__ == ‘__main__‘in python means?

In python, you must have come accross the following code :-

if __name__ == '__main__': main() 

In this tutorial, we will learn in detail what does the above statement means. As per official documentation:

‘__main__‘ is the name of the ...

Read More
What is a Dictionary in Python?
By Udit Vashisht

What is a Dictionary in Python?

Python Dictionary or Dictionary in Python is a data-structure in Python that is also known as associative array. A python dictionary is used to store data values in key:value pair. Each item has a key and a corresponding value that is expressed as a ...

Read More
Chapter 5- Indentation
By Udit Vashisht

What is indentation in Python?

Like many other languages, python is also a block-structured language.

Blocks of code in Python

Block is basically a group of statements in a code script. A block in itself can have another block or blocks, hence making it a nested block. Now, ...

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