Matplotlib Stepwise Histogram Tutorial

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a data visualization library in Python. It is widely used for creating a wide range of visualizations like line plots, scatter plots, bar plots, histograms, and more. This tutorial will focus on creating stepwise histograms using Matplotlib.

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/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) 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/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") 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/with_statement -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} matplotlib/importing_matplotlib -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} matplotlib/figures_axes -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} matplotlib/line_plots -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} matplotlib/titles_labels -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} matplotlib/legend_config -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/booleans -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/for_loops -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/lists -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/tuples -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/importing_modules -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/using_packages -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/standard_libraries -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/math_random -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/numerical_computing -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/data_visualization -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} python/build_in_functions -.-> lab-48957{{"`Matplotlib Stepwise Histogram Tutorial`"}} end

Import the necessary libraries and modules

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import StepPatch

Prepare the data

np.random.seed(0)
h, edges = np.histogram(np.random.normal(5, 3, 5000),
                        bins=np.linspace(0, 10, 20))

Create a simple step histogram

plt.stairs(h, edges, label='Simple histogram')
plt.legend()
plt.show()

Modify the baseline of the step histogram

plt.stairs(h, edges + 5, baseline=50, label='Modified baseline')
plt.legend()
plt.show()

Create a step histogram without edges

plt.stairs(h, edges + 10, baseline=None, label='No edges')
plt.legend()
plt.show()

Create a filled histogram

plt.stairs(np.arange(1, 6, 1), fill=True,
              label='Filled histogram\nw/ automatic edges')
plt.legend()
plt.show()

Create a hatched histogram

plt.stairs(np.arange(1, 6, 1)*0.3, np.arange(2, 8, 1),
              orientation='horizontal', hatch='//',
              label='Hatched histogram\nw/ horizontal orientation')
plt.legend()
plt.show()

Create a StepPatch artist

patch = StepPatch(values=[1, 2, 3, 2, 1],
                  edges=range(1, 7),
                  label=('Patch derived underlying object\n'
                         'with default edge/facecolor behaviour'))
plt.gca().add_patch(patch)
plt.xlim(0, 7)
plt.ylim(-1, 5)
plt.legend()
plt.show()

Create stacked histograms

A = [[0, 0, 0],
     [1, 2, 3],
     [2, 4, 6],
     [3, 6, 9]]

for i in range(len(A) - 1):
    plt.stairs(A[i+1], baseline=A[i], fill=True)
plt.show()

Compare .pyplot.step and .pyplot.stairs

bins = np.arange(14)
centers = bins[:-1] + np.diff(bins) / 2
y = np.sin(centers / 2)

plt.step(bins[:-1], y, where='post', label='step(where="post")')
plt.plot(bins[:-1], y, 'o--', color='grey', alpha=0.3)

plt.stairs(y - 1, bins, baseline=None, label='stairs()')
plt.plot(centers, y - 1, 'o--', color='grey', alpha=0.3)
plt.plot(np.repeat(bins, 2), np.hstack([y[0], np.repeat(y, 2), y[-1]]) - 1,
         'o', color='red', alpha=0.2)

plt.legend()
plt.title('step() vs. stairs()')
plt.show()

Summary

This tutorial covered the basics of creating stepwise histograms using Matplotlib. We learned how to create simple step histograms, modify the baseline of histograms, create filled and hatched histograms, and create stacked histograms. We also compared the differences between .pyplot.step and .pyplot.stairs.

Other Python Tutorials you may like