Libraries & Dataset

First, we need to load a few libraries and a dataset:

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')

df = pd.DataFrame({
    'Group': bars,
    'Value': height
})

📍 Most basic

Building a horizontal barplot with matplotlib follows pretty much the same process as a vertical barplot. The only difference is that the barh() function must be used instead of the bar() function. Here is a basic example:

# Create horizontal bars
plt.barh(y=df.Group, width=df.Value)

# Show graphic
plt.show()

↕️ Control order

A bar chart is always more insightful when ordered. It allows to understand how items are ranked much quicker. Since matplotlib traces the values in the order in which they are found in the data frame, you just have to sort the dataframe upfront to sort the chart:

# Sort the table
df = df.sort_values(by=['Value'])

# Create horizontal bars
plt.barh(y=df.Group, width=df.Value)

# Display the plot
plt.show()

✨ Object-oriented API

Same graph as above using the matplotlib object oriented API instead of the pyplot API. See the matplotlib section for more about this.

# Initialize a Figure and an Axes
fig, ax = plt.subplots()

# Create horizontal bars
ax.barh(y=df.Group, width=df.Value)

# Show the plot
plt.show()

Going further

This post explains how to create a horizontal barplot using matplotlib!

For more examples of how to create or customize your barplots, see the barplot section. You may also be interested in how to custom colors in a barplot.

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!