Mastering Matplotlib Stepwise Histograms
Tags: matplotlib, coding, programming, tutorial
Published: 2024-06-29 03:23:54


## 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

```python
import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import StepPatch
```


## Prepare the data

```python
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

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


## Modify the baseline of the step histogram

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


## Create a step histogram without edges

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


## Create a filled histogram

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


## Create a hatched histogram

```python
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

```python
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

```python
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`

```python
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`.

---

## Want to learn more?

- 🚀 Practice [Matplotlib Stepwise Histogram Tutorial](https://labex.io/tutorials/python-matplotlib-stepwise-histogram-tutorial-48957)
- 🌳 Learn the latest [Matplotlib Skill Trees](https://labex.io/skilltrees/matplotlib)
- 📖 Read More [Matplotlib Tutorials](https://labex.io/tutorials/category/matplotlib)

Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx) ! 😄