Sub topic 5
Bar charts: grouped, stacked and horizontal
This chapter assumes you can build a DataFrame, select columns, and call plot with the kind argument. It also assumes matplotlib is installed. Bar charts compare values across categories, so the category labels must sit on the index or in a column you name with x.
How bars map to the data
Each index value (or each value in the x column) becomes one group of bars along the category axis. Each plotted column becomes one series, drawn in its own color. With two or more columns, plot.bar draws a grouped chart by default.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
"costs": [80, 90, 95, 110],
})
df.plot(x="month", y=["sales", "costs"], kind="bar", rot=0)
plt.show()The x and y arguments choose the columns explicitly. The rot=0 argument keeps the month labels horizontal. Without it, pandas rotates vertical-bar labels 90 degrees.
Choosing the accessor
The call df.plot.bar(...) is equivalent to df.plot(kind="bar"). The accessor form is shorter and shows only the arguments that apply to that chart type. Use set_index and a column list when you want to be sure which columns are drawn.
Stacked bars
Pass stacked=True to pile the series of each category on top of each other. Use this when the total matters as much as the parts.
df.set_index("month")[["sales", "costs"]].plot.bar(stacked=True, rot=0)
plt.show()Stacking adds values, so it only makes sense when the columns are parts of a whole. Sales and costs are not parts of one total, so this example only shows the syntax. Stacked bars are also harder to read for the upper series, because their baseline moves from bar to bar.
Horizontal bars
Use plot.barh when category names are long or there are many categories. Horizontal bars give labels room to read without rotation.
orders = pd.DataFrame({
"region": ["north", "south", "north", "east", "south", "north"],
"amount": [10, 20, 15, 5, 30, 25],
})
orders.groupby("region")["amount"].sum().sort_values().plot.barh(
title="Revenue by region"
)
plt.show()The groupby call returns a Series whose index is the region, so no x is needed. Sorting before plotting orders the bars by size. With barh, the first row is drawn at the bottom, so ascending order puts the largest bar at the top.
Counting categories
value_counts produces a Series that is ready to plot as a bar chart.
orders["region"].value_counts().plot.bar(rot=0)
plt.show()Useful bar options
| Argument | Effect |
|---|---|
| `stacked=True` | Stacks series instead of grouping them |
| `width=0.8` | Sets bar width as a fraction of the slot. Values near 1 close the gaps. |
| `rot=0` | Rotates the category labels by the given angle |
| `color="steelblue"` | Sets one color, or pass a list for several series |
| `legend=False` | Hides the legend, useful for a single series |
Common errors
- Numeric categories on the index. If the category column is numeric and you leave it as a column, pandas plots it as a series. Move it to the index with
set_indexor name it withx. - Mixed scales. Grouped bars share one axis. A column in the millions next to one in the tens makes the small one invisible. Plot them separately.
- Unsorted bars. The bars follow the row order. Call
sort_values()first if you want a ranking.
Exercise
You have a Series s with the index ["alpha", "beta", "gamma"] and values [3, 9, 5]. Write one line that draws a horizontal bar chart with the largest bar at the top.
Show answer
s.sort_values().plot.barh(). Sorting ascending puts the smallest value first, and barh draws the first row at the bottom, so the largest bar is at the top.
Exercise
A DataFrame has columns "region", "q1" and "q2". How do you draw a stacked bar chart with one bar per region and horizontal labels?
Show answer
df.setindex("region")[["q1", "q2"]].plot.bar(stacked=True, rot=0). The setindex call puts the regions on the category axis, and stacked=True piles q1 and q2 in each bar.