Sub topic 11
Summarize first, then plot: groupby, pivot_table and value_counts
DataFrame.plot draws what it is given. If you pass it 10,000 order rows, it draws 10,000 points or bars. Most charts you want show a summary instead: revenue per region, orders per category, average score per month. This chapter covers how to build that summary and hand it to plot.
This chapter assumes you can do the following:
- Create a DataFrame and select columns.
- Use
groupbywith an aggregation such assumormean. - Run matplotlib in your environment, so
plt.show()orsavefigworks.
The pattern: aggregate, then plot
Every example in this chapter has the same shape:
- Start with raw rows.
- Reduce them to a Series or DataFrame whose index holds the categories.
- Call
.ploton the result.
Step 3 works without extra arguments because of the rule from the earlier chapter on axes: the index becomes the x axis (or the y axis for horizontal bars), and each numeric column becomes one series. groupby, pivot_table and value_counts all put the categories in the index, so they produce chart-ready data directly.
Summing groups with groupby
The sample data below has one row per order.
import pandas as pd
import matplotlib.pyplot as plt
orders = pd.DataFrame({
"region": ["north", "south", "north", "east", "south", "north"],
"amount": [10, 20, 15, 5, 30, 25],
})
totals = orders.groupby("region")["amount"].sum()
print(totals)The output is a Series named amount, indexed by region:
region
east 5
north 50
south 50
Name: amount, dtype: int64Plot it as horizontal bars, sorted so the largest bar ends up on top:
orders.groupby("region")["amount"].sum().sort_values().plot.barh(
title="Revenue by region"
)
plt.show()Two details matter here:
sort_values()sorts ascending. In a horizontal bar chart the first row is drawn at the bottom, so ascending order puts the largest bar at the top.groupbysorts the group keys alphabetically by default. If the order of the categories carries meaning (for example weekdays), sort or reindex explicitly instead of accepting the default.
Counting with value_counts
When you only need how often each value occurs, value_counts is shorter than groupby(...).size().
orders["region"].value_counts().plot.bar(rot=0, title="Orders per region")
plt.show()value_counts sorts by count, largest first, so a bar chart reads from tallest to shortest without extra work. Pass sort=False to keep the order in which values first appear, or call .sort_index() to order by category name.
For shares of a whole, normalize=True returns fractions that sum to 1:
shares = orders["region"].value_counts(normalize=True)
shares.plot.pie(autopct="%.0f%%", ylabel="")
plt.show()A pie chart needs a Series, with the index as slice labels. That is exactly what value_counts returns. Use pies sparingly: with more than about five slices, a bar chart is easier to read.
Several statistics at once with agg
To compare more than one statistic per group, use agg. The result is a DataFrame with one column per statistic, and plot.bar draws them side by side.
summary = orders.groupby("region")["amount"].agg(["mean", "max"])
summary.plot.bar(rot=0, title="Order size by region")
plt.show()Keep the statistics on a comparable scale. A sum and a count in one chart share one y axis, and the smaller one becomes hard to see.
Two grouping keys with pivot_table
Grouping by two columns gives a series with a two-level index, which plot does not turn into a grouped chart in a useful way. pivot_table moves one key into the columns instead, so you get one bar group per row and one bar per column.
sales = pd.DataFrame({
"quarter": ["Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q3", "Q3"],
"region": ["north", "south", "east", "north", "south", "east", "north", "south"],
"amount": [100, 80, 40, 120, 90, 55, 130, 95],
})
table = sales.pivot_table(
index="quarter",
columns="region",
values="amount",
aggfunc="sum",
fill_value=0,
)
print(table)
table.plot.bar(rot=0, title="Revenue by quarter and region")
plt.show()
table.plot.bar(stacked=True, rot=0, title="Stacked revenue")
plt.show()The printed table looks like this:
region east north south
quarter
Q1 40 100 80
Q2 55 120 90
Q3 0 130 95Each quarter is a group on the x axis and each region is a colored bar within it. The legend is built from the column names.
Note fill_value=0. The data has no east row for Q3, so without it that cell would be NaN. A missing value draws as a gap in a bar chart, which is easy to mistake for zero. Decide whether the value really is zero. If it is unknown, leaving NaN is more honest.
If you already have a grouped Series with a two-level index, unstack() gives the same result as pivot_table:
sales.groupby(["quarter", "region"])["amount"].sum().unstack().plot.bar(rot=0)
plt.show()Which key goes on the axis?
The row index becomes the x axis and the columns become the legend. Swap them with .T (transpose) to compare the other way:
table.T.plot.bar(rot=0, title="Revenue by region and quarter")
plt.show()Put the key you want to compare across on the x axis, and the key you want to compare within each group in the legend.
Plotting a limited number of categories
A bar chart with 80 categories is unreadable. Cut the summary down before plotting:
top = (
orders.groupby("region")["amount"]
.sum()
.nlargest(2)
)
top.plot.bar(rot=0)
plt.show()nlargest(n) returns the top n rows in descending order, and nsmallest(n) does the opposite. Mention the cutoff in the title, such as "Top 10 products", so readers know the chart is partial.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: no numeric data to plot` | The summary has only text columns, for example after `groupby(...).first()` on string data | Select a numeric column, or aggregate with `sum`, `mean` or `count` |
| Bars labeled `0, 1, 2, ...` | You called `reset_index()` before plotting, so the categories moved out of the index | Use `plot.bar(x="region", y="amount")`, or skip `reset_index()` |
| An extra bar or line for a column you did not want | `groupby(...).sum()` on a whole DataFrame keeps every numeric column | Select the column first: `groupby("region")["amount"]` |
| Bars in alphabetical order, not the order you wanted | `groupby` sorts keys | Call `.reindex([...])` with the order you want, or `sort_values()` |
| Chart is empty or flat | `NaN` values from a pivot, or an aggregation over the wrong column | Print the summary before plotting and check it |
The most useful habit is to print the summary first. If the printed table is wrong, the chart will be too, and the table is much easier to read than a misdrawn figure.
Summary of when to use each tool
| Goal | Tool | Typical chart |
|---|---|---|
| One statistic per category | `groupby(key)[col].agg_func()` | `bar`, `barh` |
| How often each value occurs | `value_counts()` | `bar`, `pie` |
| Several statistics per category | `groupby(key)[col].agg([...])` | grouped `bar` |
| A statistic across two categories | `pivot_table(...)` or `unstack()` | grouped or stacked `bar` |
Exercise
You have a DataFrame df with columns product, store and units. You want a grouped bar chart with one group per store and one bar per product, showing total units. Write the code, and say which key you would swap if you wanted one group per product instead.
Show answer
Code: df.pivot_table(index="store", columns="product", values="units", aggfunc="sum").plot.bar(rot=0). The row index (store) forms the groups on the x axis and each column (product) becomes a bar with a legend entry. To get one group per product, swap the keys in the call (index="product", columns="store") or append .T to the pivot table before plotting.
Exercise
A colleague runs df.groupby("city").mean().plot.bar() and gets a chart with many unrelated bars, including an ID column. What is wrong, and how do you fix it?
Show answer
groupby("city").mean() returns every numeric column, so each one, including the ID, is drawn as a series. Select the column of interest before aggregating: df.groupby("city")["price"].mean().plot.bar(). Averaging an ID column is also meaningless, so it should not be in the summary at all.