# How to Plot GroupBy and Pivot Table Results in Pandas

> Plot pandas groupby and pivot_table results: unstack() for grouped and stacked bars, category order, monthly totals, one line per group, subplots, error bars.

Source: https://www.pythoncharts.com/pandas/pandas-plot-groupby/ | Published: 2026-11-27 | Author: Alex Scott | Category: Pandas | Tags: pandas, groupby, pivot_table, bar chart, unstack, df.plot

To plot a pandas groupby result, aggregate first and then call `.plot()` on the result: `df.groupby("store")["revenue"].sum().plot.bar()`. When you group by two columns, add `.unstack()` so the second one becomes separate colors.

## Quick Example

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(137)

# Six months of daily café sales: one row per day, store, and product category.
rows = pd.MultiIndex.from_product(
    [pd.date_range("2026-01-01", "2026-06-30"),
     ["Harbor", "Station", "Campus"], ["Coffee", "Tea", "Pastry"]],
    names=["date", "store", "category"])
df = rows.to_frame(index=False)

base = (df["store"].map({"Harbor": 210, "Station": 300, "Campus": 170})
        * df["category"].map({"Coffee": 1.0, "Tea": 0.35, "Pastry": 0.6}))
weekend = df["date"].dt.dayofweek >= 5
base *= np.where(weekend & (df["store"] == "Harbor"), 1.7, 1.0)
base *= np.where(weekend & (df["store"] != "Harbor"), 0.65, 1.0)
base *= np.where((df["store"] == "Campus") & (df["date"].dt.month >= 5), 0.5, 1.0)
df["revenue"] = (base * rng.gamma(30, 1 / 30, len(df))).round(2)

totals = df.groupby(["store", "category"])["revenue"].sum().unstack()

ax = totals.plot.bar(figsize=(8, 4.2), rot=0,
                     color=["#6f4e37", "#e0a458", "#7a9e7e"])
ax.yaxis.set_major_formatter("${x:,.0f}")
ax.set_xlabel("")
ax.set_title("Revenue by Store and Category, January to June")
ax.legend(title="")
plt.tight_layout()
plt.show()
```

![Grouped bar chart of café revenue where Station leads in coffee, tea, and pastry, followed by Harbor and Campus](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-quick-example.png)

The code targets pandas 3. The key step is the table it builds: the index becomes the x axis, and each column becomes one series.

```python
print(totals.round(0))
```

## Plot a Single groupby Result

Grouping by one column and aggregating gives a Series. Sort it, and use `barh` so the labels read horizontally.

```python
by_store = df.groupby("store")["revenue"].sum().sort_values()

ax = by_store.plot.barh(figsize=(7, 3.2), color="#33658a", width=0.7)
ax.bar_label(ax.containers[0], fmt="${:,.0f}", padding=4)
ax.set_xlim(0, by_store.max() * 1.18)  # room for the labels
ax.xaxis.set_visible(False)
ax.spines[["top", "right", "bottom"]].set_visible(False)
ax.set_ylabel("")
ax.set_title("Total Revenue by Store")
plt.tight_layout()
plt.show()
```

![Horizontal bar chart of total revenue with Station highest, then Harbor, then Campus](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-single.png)

## Stacked and 100% Stacked Bars from a pivot_table

`pivot_table()` builds the same wide table in one call. Set `aggfunc="sum"`, because the default is the mean. To compare mix rather than size, divide each row by its total.

```python
table = df.pivot_table(index="store", columns="category", values="revenue",
                       aggfunc="sum")
share = table.div(table.sum(axis=1), axis=0) * 100

fig, (left, right) = plt.subplots(1, 2, figsize=(9, 4))
colors = ["#6f4e37", "#e0a458", "#7a9e7e"]

table.plot.bar(stacked=True, ax=left, rot=0, color=colors, legend=False)
left.yaxis.set_major_formatter("${x:,.0f}")
left.set_title("Revenue")

share.plot.bar(stacked=True, ax=right, rot=0, color=colors, width=0.7)
right.yaxis.set_major_formatter("{x:.0f}%")
right.set_title("Share of Revenue")
right.legend(title="", loc="center left", bbox_to_anchor=(1, 0.5))

for ax in (left, right):
    ax.set_xlabel("")
plt.tight_layout()
plt.show()
```

![Stacked revenue bars beside 100 percent stacked bars showing a nearly identical category mix in all three stores](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-stacked.png)

The stores differ in size, but coffee, tea, and pastry make up about the same share of each. See [stacked vs unstacked bar charts](https://www.pythoncharts.com/pandas/pandas-stacked-vs-unstacked-bar-charts/) for more on the two layouts.

## Choose the Order of the Groups

Groups come out in alphabetical order, which scrambles weekdays and months. Use `reindex()` to put the result in the order you want.

```python
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday"]

daily = df.groupby(["date", "store"])["revenue"].sum().reset_index()
weekday = daily.pivot_table(index=daily["date"].dt.day_name(), columns="store",
                            values="revenue", aggfunc="mean").reindex(days)
weekday.index = weekday.index.str[:3]

ax = weekday.plot(figsize=(8, 4), marker="o", linewidth=2,
                  color=["#d1495b", "#00798c", "#edae49"])
ax.yaxis.set_major_formatter("${x:,.0f}")
ax.set_ylim(0)
ax.set_xlabel("")
ax.set_title("Average Daily Revenue by Weekday")
ax.legend(title="", ncols=3, loc="lower left")
plt.show()
```

![Lines of average revenue from Monday to Sunday where Harbor jumps on the weekend while Station and Campus drop](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-weekday.png)

Daily totals come first here: averaging the raw rows would give the average per category per day. For an order you'll reuse, convert the column with `pd.Categorical(column, categories, ordered=True)`.

## Plot Monthly Totals

Group dates into months with `pd.Grouper(key="date", freq="MS")`. For a bar chart, turn the dates into text labels first. In pandas 3.0.5, calling `.plot.bar()` on a month-start index raises `ValueError: <MonthBegin> is not supported as period frequency`.

```python
monthly = (df.groupby([pd.Grouper(key="date", freq="MS"), "store"])["revenue"]
           .sum()
           .unstack())
monthly.index = monthly.index.strftime("%b")  # Jan, Feb, ...

ax = monthly.plot.bar(figsize=(8, 4), rot=0, width=0.8,
                      color=["#d1495b", "#00798c", "#edae49"])
ax.yaxis.set_major_formatter("${x:,.0f}")
ax.set_xlabel("")
ax.set_title("Monthly Revenue by Store")
ax.legend(title="", ncols=3, loc="upper center", bbox_to_anchor=(0.5, -0.08))
plt.tight_layout()
plt.show()
```

![Monthly grouped bars where Campus revenue falls by about half in May and June](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-monthly.png)

Line charts accept the dates as they are, so skip the `strftime()` step for `monthly.plot()`. [Plotting time series with a custom frequency](https://www.pythoncharts.com/pandas/pandas-time-series-custom-frequency/) covers other intervals.

## One Chart per Group

`subplots=True` draws each column of the wide table in its own panel. `sharey=True` keeps the scales comparable.

```python
weekly = (df.groupby([pd.Grouper(key="date", freq="W"), "store"])["revenue"]
          .sum()
          .unstack()
          .iloc[1:-1])  # drop the partial first and last weeks

axes = weekly.plot(subplots=True, layout=(1, 3), sharey=True, figsize=(9, 3.2),
                   legend=False, color=["#d1495b", "#00798c", "#edae49"],
                   title=list(weekly.columns))
for ax in axes.flat:
    ax.set_xlabel("")
axes[0, 0].yaxis.set_major_formatter("${x:,.0f}")
axes[0, 0].set_ylim(0)
plt.suptitle("Weekly Revenue")
plt.tight_layout()
plt.show()
```

![Three weekly revenue panels for Campus, Harbor, and Station, with Campus dropping in May](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-subplots.png)

## Loop Over Groups for Full Control

Iterating over `groupby()` yields each key with its rows, so you can style groups differently. This is useful when you want to highlight one.

```python
fig, ax = plt.subplots(figsize=(8, 4))

for store, group in df.groupby("store"):
    series = group.groupby(pd.Grouper(key="date", freq="W"))["revenue"].sum().iloc[1:-1]
    highlight = store == "Campus"
    label = store if highlight else ("Other stores" if store == "Harbor" else None)
    ax.plot(series.index, series, label=label,
            color="#c1121f" if highlight else "#adb5bd",
            linewidth=2.6 if highlight else 1.6)

ax.yaxis.set_major_formatter("${x:,.0f}")
ax.set_ylim(0)
ax.set_title("Campus Sales Fall When the Term Ends")
ax.legend(ncols=2, loc="lower left")
plt.show()
```

![Weekly revenue lines with Campus highlighted in red and falling in May while the other stores stay in gray](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-loop.png)

Calling `df.groupby("store")["revenue"].plot()` directly also draws one line per group on the same Axes, but only against the row index. Set a date index first, and make sure each group has one row per date.

## Add Error Bars

Aggregate the mean and standard deviation together, then pass the second column as `yerr`.

```python
stats = daily.groupby("store")["revenue"].agg(["mean", "std"])

ax = stats["mean"].plot.bar(yerr=stats["std"], capsize=5, rot=0, figsize=(7, 4),
                            color="#8d99ae")
ax.yaxis.set_major_formatter("${x:,.0f}")
ax.set_xlabel("")
ax.set_title("Daily Revenue: Mean ± 1 Standard Deviation")
plt.show()
```

![Bar chart of mean daily revenue per store with standard deviation error bars](https://www.pythoncharts.com/pandas/pandas-plot-groupby/images/pandas-plot-groupby-errorbars.png)

The [pandas error bar guide](https://www.pythoncharts.com/pandas/pandas-error-bars/) covers asymmetric errors and line charts.

## Which Shape Do I Need?

| You want | Shape of the data | Code |
|---|---|---|
| One bar per group | Series | `groupby("a")["v"].sum().plot.bar()` |
| Grouped or stacked bars | Index = x axis, columns = colors | `groupby(["a", "b"])["v"].sum().unstack()` |
| Same, in one step | Same | `pivot_table(index="a", columns="b", values="v", aggfunc="sum")` |
| One line per group | Dates in the index, groups in columns | `...unstack().plot()` |

## Practical Tips

- If your bars are the wrong way around, transpose the table with `.T`, or call `.unstack(0)` to move the first level to the columns.
- `groupby()` drops rows whose key is missing. Pass `dropna=False` to keep them as their own bar.
- `.size()` counts rows per group, and `.count()` counts non-missing values in each column.
- With a categorical key, pandas 3 only returns categories that appear in the data. Pass `observed=False` to include the empty ones.

## Similar Topics

- [Grouped Bar Charts in Matplotlib](https://www.pythoncharts.com/matplotlib/grouped-bar-charts-matplotlib/)
- [Plot Multiple Columns on the Same Line Chart in Pandas](https://www.pythoncharts.com/pandas/multiple-columns-line-chart-pandas/)
- [How to Style a Pandas DataFrame with df.style](https://www.pythoncharts.com/pandas/pandas-style-dataframe/)
