How to Plot GroupBy and Pivot Table Results in Pandas

Turn groupby() and pivot_table() results into bar, line, and small multiple charts, using unstack(), ordered categories, error bars, and monthly dates.

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

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

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.

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.

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

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.

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

The stores differ in size, but coffee, tea, and pastry make up about the same share of each. See 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.

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

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.

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

Line charts accept the dates as they are, so skip the strftime() step for monthly.plot(). Plotting time series with a 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.

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

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.

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

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.

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

The pandas error bar guide 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