Sub topic 5
Bar charts: grouped, stacked and horizontal
This chapter assumes you can build a DataFrame, select columns, and call groupby. It also assumes matplotlib is installed and that you know how set_index moves a column onto the index (covered earlier in this tutorial). Here you will draw three kinds of bar chart and learn how pandas decides what each bar means.
How pandas draws bars
A bar chart compares values across categories. In DataFrame.plot, the index supplies the categories on the category axis. Each numeric column becomes one series of bars, with its own color and a legend entry.
Two things follow from this rule:
- One column gives one bar per index label.
- Several columns give a group of bars per index label. This is the grouped chart, and it is the default.
The kind="bar" argument and the df.plot.bar accessor are equivalent. The accessor is shorter and shows up in autocomplete, so many people prefer it.
Grouped bars
Start with the monthly data used earlier in the tutorial.
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 argument names the column for the category axis. The y argument names the columns to draw, and a list gives one bar per column in each group. The rot=0 argument keeps the tick labels horizontal. Without it, pandas rotates bar labels by 90 degrees.
If you leave out x, pandas uses the index, which here would be the integers 0 to 3. Moving the labels onto the index first gives the same chart:
df.set_index("month")[["sales", "costs"]].plot.bar(rot=0)
plt.show()Selecting [["sales", "costs"]] after set_index matters when the frame has other numeric columns. Without the selection, every numeric column would become a bar.
Stacked bars
Pass stacked=True to put the series of each category on top of one another.
df.set_index("month")[["sales", "costs"]].plot.bar(stacked=True, rot=0)
plt.show()The bar height is now the sum of the columns. Use a stacked chart when the parts add up to a meaningful total, such as revenue split by product line. Here the stack of sales and costs has no real meaning, because costs are not part of sales. It is shown only to illustrate the argument.
Stacking has two limits:
- Only the bottom series has a common baseline. The reader cannot compare the other segments by length alone.
- Negative values stack downward from zero, separately from the positive ones. A column with mixed signs gives a confusing picture.
When the comparison between series is the main point, use grouped bars. When the total is the main point, use stacked bars.
Horizontal bars
Use barh when labels are long or there are many categories. Long labels read more easily on the vertical axis than rotated under the bars.
df.set_index("month")[["sales", "costs"]].plot.barh()
plt.show()With barh, the index runs along the vertical axis, and the first index label sits at the bottom. If you want the first row at the top, as in a table, invert the axis on the returned Axes:
ax = df.set_index("month")[["sales", "costs"]].plot.barh()
ax.invert_yaxis()
plt.show()The stacked=True argument works with barh as well.
Summarize first, then bar
Bar charts rarely start from data that is ready to plot. Raw tables usually have many rows per category, and plot.bar draws one bar per row. Aggregate first, so each category appears once.
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")
orders["region"].value_counts().plot.bar(rot=0)
plt.show()Both calls return a Series whose index holds the categories. A Series plots as a single set of bars, so no legend appears.
groupby(...).sum()gives a total per category.sort_values()orders the bars from smallest to largest. In a horizontal chart, the largest bar then ends up at the top, which reads as a ranking.value_counts()counts rows per category and sorts them by count, largest first.
For two categorical dimensions, use pivot_table to make a wide table. Its rows become the category axis and its columns become the series.
sales = pd.DataFrame({
"region": ["north", "north", "south", "south", "east", "east"],
"product": ["A", "B", "A", "B", "A", "B"],
"amount": [10, 15, 20, 30, 5, 12],
})
table = sales.pivot_table(index="region", columns="product", values="amount", aggfunc="sum")
table.plot.bar(rot=0)
table.plot.bar(stacked=True, rot=0)
plt.show()The first call draws one group per region with a bar for each product. The second stacks the products within each region. This pattern, groupby or pivot_table followed by plot.bar, covers most bar charts you will need.
Styling a bar chart
Bar charts accept the common styling arguments. A few are specific to bars:
| Argument | Effect |
|---|---|
| `rot` | Rotation of the category tick labels, in degrees |
| `width` | Width of each bar or group, from 0 to 1 (default 0.5 for `bar`) |
| `color` | One color for a Series, or a list with one color per series |
| `edgecolor` | Outline color of the bars |
| `legend` | Set to `False` to hide the legend |
| `title` | Title above the chart |
The returned Axes can add value labels with bar_label, available in matplotlib 3.4 and later:
ax = df.set_index("month")["sales"].plot.bar(
title="Monthly sales",
color="steelblue",
figsize=(6, 4),
rot=0,
)
ax.set_xlabel("Month")
ax.set_ylabel("Units sold")
ax.bar_label(ax.containers[0])
ax.figure.savefig("sales.png", dpi=150, bbox_inches="tight")Each series creates one container in ax.containers. For a chart with several series, loop over the containers and label each one.
Common problems
- A bar for every row. If the chart has dozens of thin bars for the same label, you skipped the aggregation step.
- Numbers on the category axis. If the labels read 0, 1, 2, you did not set
xor callset_index. - An unwanted extra series. A numeric column you did not intend to plot appears in the legend. Select the columns you want with
y=or a column list. TypeError: no numeric data to plot. Every selected column is text. Convert withpd.to_numericor choose another column.- Overlapping labels. Switch to
barh, shorten the labels, or enlargefigsize. - Bars start above zero. If you set a y-axis limit with
ylim, bar lengths no longer match values. Keep the baseline at zero, because bar length is the encoding. - Missing values. A
NaNproduces no bar for that category and series. Usefillna(0)only if zero is the true value.
Exercises
Exercise
A DataFrame t has the columns team (text), wins and losses. Write one expression that draws a horizontal stacked bar chart of wins and losses for each team, with team names as the labels.
Show answer
t.set_index("team")[["wins", "losses"]].plot.barh(stacked=True). The set_index call puts the team names on the category axis, the column selection limits the series to two, barh makes the bars horizontal, and stacked=True stacks wins and losses for each team.
Exercise
A DataFrame log has one row per support ticket, with the columns category and minutes_to_close. You want a bar chart of the average closing time per category, with the longest bar at the top. What do you write, and why does the sort order produce that result?
Show answer
log.groupby("category")["minutes_to_close"].mean().sort_values().plot.barh(). The groupby call gives one value per category. sort_values() puts the smallest first, and barh draws the first index label at the bottom, so the largest value ends up at the top.