How to make a plot that looks like stairs with Matplotlib in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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.
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 :
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚