← Data analysis with Python

Bar charts for comparing groups

One bar per category, ideally sorted so the ranking is obvious.

Start this lesson

Bar charts compare amounts across separate categories: units per store, votes per candidate, visitors per branch. ax.bar(names, values) draws one vertical bar per name; ax.barh draws horizontal bars, which fit long names better. Bars are compared by their length, so the value axis should start at zero. Sorting the bars from largest to smallest makes the ranking easy to read, and a groupby result is a natural thing to chart.

import io
import pandas as pd

csv_text = """day,store,item,units,price
Mon,North,Coffee,30,3.5
Mon,North,Muffin,12,2.75
Mon,South,Coffee,22,3.5
Mon,South,Tea,9,3.0
Tue,North,Coffee,35,3.5
Tue,North,Tea,7,3.0
Tue,South,Coffee,18,3.5
Tue,South,Muffin,15,2.75
Wed,North,Muffin,10,2.75
Wed,South,Coffee,27,3.5
"""
sales = pd.read_csv(io.StringIO(csv_text))
import matplotlib.pyplot as plt

by_item = sales.groupby("item")["units"].sum().sort_values(ascending=False)
fig, ax = plt.subplots()
ax.bar(by_item.index, by_item.values, color="#4C78A8")
ax.set_title("Units sold by item")
ax.set_xlabel("Item")
ax.set_ylabel("Units")

The groupby result already has names (index) and totals (values), so it goes straight into ax.bar. Sorting first puts Coffee on the left, then Muffin, then Tea.

One color for all bars is usually clearest. Use a different color only to highlight something on purpose.