Animated Histogram Using Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to create an animated histogram using Matplotlib in Python. The animated histogram will simulate new data coming in and update the heights of rectangles with the new data.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/histograms("`Histograms`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/animation_creation("`Animation Creation`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/with_statement -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} matplotlib/figures_axes -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} matplotlib/histograms -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} matplotlib/animation_creation -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/variables_data_types -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/booleans -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/for_loops -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/tuples -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/function_definition -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/importing_modules -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/standard_libraries -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/math_random -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/data_collections -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/numerical_computing -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/data_visualization -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} python/build_in_functions -.-> lab-48540{{"`Animated Histogram Using Matplotlib`"}} end

Import Libraries

First, we need to import the necessary libraries.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

Set Random Seed and Bins

Set random seed for reproducibility and fix the bin edges.

## Fixing random state for reproducibility
np.random.seed(19680801)

## Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)

Create Data and Histogram

Create data and histogram using NumPy.

## histogram our data with numpy
data = np.random.randn(1000)
n, _, _ = plt.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)

Create Animation Function

We need to create an animate function that generates new random data and updates the heights of rectangles.

def animate(frame_number):
    ## simulate new data coming in
    data = np.random.randn(1000)
    n, _ = np.histogram(data, HIST_BINS)
    for count, rect in zip(n, bar_container.patches):
        rect.set_height(count)
    return bar_container.patches

Create Bar Container and Animation

Using plt.hist allows us to get an instance of BarContainer, which is a collection of Rectangle instances. We use FuncAnimation to setup the animation.

## Using plt.hist allows us to get an instance of BarContainer, which is a
## collection of Rectangle instances. Calling prepare_animation will define
## animate function working with supplied BarContainer, all this is used to setup FuncAnimation.
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)
ax.set_ylim(top=55)  ## set safe limit to ensure that all data is visible.

ani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True)
plt.show()

Summary

In this lab, you learned how to create an animated histogram using Matplotlib in Python. You started by importing the necessary libraries, setting random seed and bins, creating data and histogram, creating an animation function, and finally creating bar container and animation. By following these steps, you can create animated histograms to visualize data in a dynamic way.

Other Python Tutorials you may like