How to make a plot that looks like stairs with Matplotlib in Python

1 min

Step plots are those plots that we only use a few times in our life, but can always become handy when we want to show state changes.

Here is a simple example of a step plot, using the matplotlib library.

import matplotlib.pyplot as plt
import pandas as pd

# We generate a dataframe with some random data
df = pd.DataFrame(index = ['2018', '2019', '2020', '2021'], 
                  data={"sales": [28429, 41771, 55238, 120681]})

# We set our canvas
fig, axes = plt.subplots(1,1, figsize=(8,6))

# We do a step plot on the axes
axes.step(x=df.index,
         y=df["sales"])

# We set a title
axes.set_title("Sales per year")

# Change the labels
axes.set_xlabel("Year")
axes.set_ylabel("In USD")

# Fixing the layout to fit the size
fig.tight_layout()

# Showing the plot
plt.show()

As we can see we are using the axes.stackplot() method that will do a step plot given a list of x values and multiple y as pandas.Series. (e.g. axes.step(x, y))

Here is the result.

How to make a step plot in Python

Here you are! You now know how to make step plots.

More on plots

If you want to know more about how to add labels, plot different types of plots, etc... check out the other articles I wrote on the topic, just here :

Matplotlib - The Python You Need
We gathered the only Python essentials that you will probably ever need.