DEV Community

Cover image for Mastering Matplotlib Stepwise Histograms
Labby for LabEx

Posted on • Originally published at labex.io

Mastering Matplotlib Stepwise Histograms

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.

Import the necessary libraries and modules

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import StepPatch
Enter fullscreen mode Exit fullscreen mode

Prepare the data

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

Create a simple step histogram

plt.stairs(h, edges, label='Simple histogram')
plt.legend()
plt.show()
Enter fullscreen mode Exit fullscreen mode

Modify the baseline of the step histogram

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

Create a step histogram without edges

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

Create a filled histogram

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

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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.


Want to learn more?

Join our Discord or tweet us @WeAreLabEx ! ๐Ÿ˜„

Top comments (0)