How to Create Multiple Pie Charts in Matplotlib

A regional sales manager asked me for one image that compares 2026 revenue share across four US regions, quarter by quarter. Matplotlib multiple pie charts handle that: create a grid with plt.subplots(2, 2), then call ax.pie() once per quarter in a loop.

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
for ax, quarter, values in zip(axes.flat, quarters, sales):
    ax.pie(values, labels=regions, autopct="%1.1f%%")
    ax.set_title(quarter)

The charts and numbers on this page came out of real runs on Matplotlib 3.11.2, pandas 3.0.6 and Python 3.12.5, each captured straight from the plot window.

In this tutorial, I’ll build matplotlib multiple pie charts step by step: grid, fixed colors, shared legend, totals and a saved PNG. Then we’ll loop over a pandas DataFrame, add nested and donut pies, and fix the errors I hit.

Here’s what we’re building:

Matplotlib multiple pie charts in a 2x2 grid showing 2026 quarterly sales share by region with one shared legend and dollar totals
The finished figure: four quarterly pies, one legend for all four regions and each quarter’s total in its title.

Before You Start: The 2026 Regional Sales Data for the Pie Charts

You need Python 3.10 or newer plus Matplotlib, and pandas only for the DataFrame section. Install both with pip install matplotlib pandas if they’re missing.

Our running sample is a made-up retailer, Cedar Ridge Outdoor Supply, with sales in four regions for each 2026 quarter. Every script imports it from sales.py, so save this file first:

# Cedar Ridge Outdoor Supply - 2026 sales by region (USD)
regions = ["Northeast", "Southeast", "Midwest", "West"]
quarters = ["Q1 2026", "Q2 2026", "Q3 2026", "Q4 2026"]
sales = [
    [184250.75, 142380.40, 121905.15, 210640.90],   # Q1
    [196410.20, 158925.60, 118340.85, 231775.35],   # Q2
    [162880.45, 171210.30, 129455.70, 244190.10],   # Q3
    [228945.95, 181660.25, 140220.55, 259830.65],   # Q4
]
region_colors = {"Northeast": "#7FA7D9", "Southeast": "#F2A65A",
                 "Midwest": "#8CCB8F", "West": "#C9A3E0"}

if __name__ == "__main__":
    for quarter, row in zip(quarters, sales):
        top = regions[row.index(max(row))]
        print(f"{quarter}: ${sum(row):,.2f}  top region: {top}")
    print(f"Year total: ${sum(map(sum, sales)):,.2f}")

Output:

Q1 2026: $659,177.20  top region: West
Q2 2026: $705,452.00  top region: West
Q3 2026: $707,736.55  top region: West
Q4 2026: $810,657.40  top region: West
Year total: $2,883,023.15
QuarterNortheastSoutheastMidwestWest
Q1 2026$184,250.75$142,380.40$121,905.15$210,640.90
Q2 2026$196,410.20$158,925.60$118,340.85$231,775.35
Q3 2026$162,880.45$171,210.30$129,455.70$244,190.10
Q4 2026$228,945.95$181,660.25$140,220.55$259,830.65
Command Prompt output of the sales.py sample data showing each 2026 quarter's total and top region
Running python sales.py prints every quarter’s total. West leads all four quarters.

The region_colors dictionary is there for Step 2. If a single pie is new to you, my Matplotlib pie chart guide covers labels, autopct and startangle first.

Step 1: Draw a 2×2 Grid of Pie Charts with plt.subplots()

Goal: four pies in one window. plt.subplots(2, 2) returns a figure and a 2×2 array of Axes, and axes.flat walks them left to right, top to bottom.

  1. Create the grid with plt.subplots(2, 2, figsize=(7, 6)).
  2. Zip axes.flat with the quarter names and the sales rows.
  3. Call ax.pie() and ax.set_title() on each Axes.
  4. Run the script with python grid.py.
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
from sales import regions, quarters, sales

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
for ax, quarter, values in zip(axes.flat, quarters, sales):
    pc = ax.pie(values, labels=regions, autopct="%1.1f%%")
    ax.set_title(quarter)
    first = to_hex(pc.wedges[0].get_facecolor())
    print(f"{quarter}: first wedge {first}, aspect {ax.get_aspect()}")
plt.show()

Output:

Q1 2026: first wedge #1f77b4, aspect 1.0
Q2 2026: first wedge #1f77b4, aspect 1.0
Q3 2026: first wedge #1f77b4, aspect 1.0
Q4 2026: first wedge #1f77b4, aspect 1.0
Matplotlib plot window with four pie charts in a 2x2 subplots grid, one per 2026 quarter, with region labels on every pie
One ax.pie() call per Axes gives four labeled pies, but the region names repeat four times.

Checkpoint: you should see four round pies titled Q1 to Q4 2026, with West the largest slice in each. The printout shows every pie starting at the same blue (#1f77b4), and the aspect is 1.0, so pie() keeps them circular without plt.axis("equal").

Colors match here only because each Axes restarts the default color cycle. For more grid shapes, see the Matplotlib subplot tutorial.

Step 2: Lock Each Region to One Pie Chart Color

Goal: Northeast is always blue, whatever the order. That matters as soon as you sort slices, because default colors follow position, not the label.

  1. Import region_colors from sales.py.
  2. Sort each quarter’s regions from largest to smallest.
  3. Build the colors list from the sorted names, not from positions.
  4. Add startangle=90, counterclock=False so slices run clockwise from 12 o’clock.
import matplotlib.pyplot as plt
from sales import regions, quarters, sales, region_colors

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
for ax, quarter, values in zip(axes.flat, quarters, sales):
    # biggest region first, starting at 12 o'clock
    pairs = sorted(zip(regions, values), key=lambda p: p[1],
                   reverse=True)
    names = [name for name, _ in pairs]
    ax.pie([v for _, v in pairs], labels=names,
           colors=[region_colors[n] for n in names],
           autopct="%1.1f%%", startangle=90, counterclock=False,
           wedgeprops={"edgecolor": "white", "linewidth": 1.5})
    ax.set_title(quarter)
    print(f"{quarter}: {', '.join(names)}")
plt.show()

Output:

Q1 2026: West, Northeast, Southeast, Midwest
Q2 2026: West, Northeast, Southeast, Midwest
Q3 2026: West, Southeast, Northeast, Midwest
Q4 2026: West, Northeast, Southeast, Midwest
Matplotlib multiple pie charts sorted by sales with each region keeping the same color in every quarter
Q3 2026 puts Southeast ahead of Northeast, yet both keep their own colors.

Checkpoint: the printout shows Q3 2026 in a different order (West, Southeast, Northeast, Midwest), while the other quarters lead with West, Northeast. In the window, Southeast stays orange in every pie.

The white edgecolor in wedgeprops separates neighboring slices. The same lookup idea works for any category column, as shown in plotting categorical data in a pie chart.

Step 3: Add One Shared Legend Below All the Pie Charts

Goal: replace 16 repeated labels with one legend. I’m back to the fixed region order here, because readers compare the same slice position across quarters.

  1. Pass labeldistance=None so labels are stored but not drawn.
  2. Add layout="constrained" to plt.subplots().
  3. Call fig.legend() once with the last pie’s wedges and loc="outside lower center".
import matplotlib.pyplot as plt
from sales import regions, quarters, sales, region_colors

colors = [region_colors[r] for r in regions]
fig, axes = plt.subplots(2, 2, figsize=(7, 6), layout="constrained")
for ax, quarter, values in zip(axes.flat, quarters, sales):
    pc = ax.pie(values, labels=regions, labeldistance=None,
                colors=colors, autopct="%1.1f%%", startangle=90,
                counterclock=False,
                wedgeprops={"edgecolor": "white", "linewidth": 1.5})
    ax.set_title(quarter)

fig.legend(pc.wedges, regions, loc="outside lower center", ncols=4,
           frameon=False)
print(type(pc).__name__, "with", len(pc.wedges), "wedges per pie")
plt.show()

Output:

PieContainer with 4 wedges per pie
Matplotlib plot window with four pie charts and one shared figure legend for Northeast, Southeast, Midwest and West below the grid
One figure-level legend sits under the grid, and the pies get more room without the outside labels.

Note: since Matplotlib 3.11, ax.pie() returns a PieContainer instead of a tuple. Old code that unpacks wedges, texts, autotexts still ran for me, but pc.wedges reads better.

Checkpoint: the console prints PieContainer with 4 wedges per pie, and the legend shows four colored patches in one row. More legend placements are in legends in Matplotlib subplots.

Step 4: Add Totals and a Title, Then Save the Pie Charts as PNG

Goal: a finished chart you can drop into a slide. Each title gets the quarter’s total in USD, the figure gets a suptitle(), and savefig() writes the file before plt.show().

  1. Put f"{quarter}\n${sum(values):,.2f}" in each title.
  2. Add fig.suptitle() for the whole figure.
  3. Call fig.savefig(out, dpi=150, bbox_inches="tight") before plt.show().
import os
import matplotlib.pyplot as plt
from sales import regions, quarters, sales, region_colors

colors = [region_colors[r] for r in regions]
fig, axes = plt.subplots(2, 2, figsize=(7, 6.2), layout="constrained")
for ax, quarter, values in zip(axes.flat, quarters, sales):
    pc = ax.pie(values, colors=colors, autopct="%1.1f%%",
                startangle=90, counterclock=False,
                wedgeprops={"edgecolor": "white", "linewidth": 1.5})
    ax.set_title(f"{quarter}\n${sum(values):,.2f}", fontsize=11)

fig.legend(pc.wedges, regions, loc="outside lower center", ncols=4,
           frameon=False)
fig.suptitle("Cedar Ridge Outdoor Supply: 2026 Sales by Region",
             fontsize=14, fontweight="bold")

out = "regional_sales_2026.png"
fig.savefig(out, dpi=150, bbox_inches="tight")
h, w = plt.imread(out).shape[:2]
print(f"Saved {out}: {w} x {h} px, {os.path.getsize(out) / 1024:,.1f} KB")
plt.show()

Output:

Saved regional_sales_2026.png: 901 x 943 px, 93.4 KB

Checkpoint: the window matches the finished figure at the top of this post, and the console says Saved regional_sales_2026.png: 901 x 943 px, 93.4 KB. Save before show(), because closing the window leaves nothing to save.

bbox_inches="tight" keeps the legend inside the file; there’s more on output options in saving a Matplotlib figure as PNG. To size the titles, see pie chart title font size.

Test the Pie Chart Grid with Three Quarters of Data

Real data rarely fills a neat 2×2. In October 2026 you’d only have Q1 to Q3, which leaves an empty fourth Axes with a blank frame. So I wrapped the build in a function that removes unused Axes and tested it on three quarters:

import math
import matplotlib.pyplot as plt
from sales import regions, quarters, sales, region_colors

def pie_grid(datasets, titles, labels, ncols=2):
    nrows = math.ceil(len(datasets) / ncols)
    fig, axes = plt.subplots(nrows, ncols, figsize=(3.5 * ncols, 3 * nrows),
                             layout="constrained", squeeze=False)
    colors = [region_colors[name] for name in labels]
    for ax, values, title in zip(axes.flat, datasets, titles):
        pc = ax.pie(values, colors=colors, autopct="%1.1f%%",
                    startangle=90, counterclock=False,
                    wedgeprops={"edgecolor": "white"})
        ax.set_title(f"{title}\n${sum(values):,.2f}")
    extra = axes.flat[len(datasets):]
    for ax in extra:
        ax.remove()                      # no blank frame in the gap
    fig.legend(pc.wedges, labels, loc="outside lower center",
               ncols=len(labels), frameon=False)
    return fig, len(extra)

fig, removed = pie_grid(sales[:3], quarters[:3], regions)
fig.suptitle("2026 Year to Date (Q1-Q3)", fontweight="bold")
print(f"Drew 3 pies and removed {removed} empty Axes")
plt.show()

Output:

Drew 3 pies and removed 1 empty Axes
Matplotlib multiple pie charts function test with three 2026 quarters, the empty fourth subplot removed and a shared legend
Three pies, no empty frame in the bottom-right corner and the same shared legend.

The run printed Drew 3 pies and removed 1 empty Axes. squeeze=False keeps axes two-dimensional even for one row, so the function works for 1 to 12 pies. To show dollar amounts inside slices, see autopct formatting.

Loop Over a pandas DataFrame to Draw One Pie per Quarter

Same sales, now in a DataFrame. I transpose it so regions are rows and quarters are columns; then df.items() hands you one column (one quarter) at a time:

import matplotlib.pyplot as plt
import pandas as pd
from sales import regions, quarters, sales, region_colors

df = pd.DataFrame(sales, index=quarters, columns=regions).T
print(df.to_string())

fig, axes = plt.subplots(1, len(df.columns), figsize=(8.6, 3.4),
                         layout="constrained")
for ax, (quarter, column) in zip(axes, df.items()):
    pc = ax.pie(column, colors=[region_colors[r] for r in column.index],
                autopct="%1.0f%%", startangle=90, counterclock=False,
                textprops={"fontsize": 8},
                wedgeprops={"edgecolor": "white"})
    ax.set_title(f"{quarter}\n${column.sum():,.2f}", fontsize=9)
fig.legend(pc.wedges, df.index, loc="outside lower center", ncols=4,
           frameon=False, fontsize=8)
plt.show()

Output:

             Q1 2026    Q2 2026    Q3 2026    Q4 2026
Northeast  184250.75  196410.20  162880.45  228945.95
Southeast  142380.40  158925.60  171210.30  181660.25
Midwest    121905.15  118340.85  129455.70  140220.55
West       210640.90  231775.35  244190.10  259830.65
Matplotlib plot window with four pie charts in one row drawn by looping over a pandas DataFrame of 2026 quarterly sales
Looping over df.items() gives one pie per quarter column in a single row.

Each column is a Series, so column.index supplies the region names and column.sum() the total. For wider rows, adjust figsize as shown in Matplotlib subplot figure size.

pandas can also do it in one call with df.plot.pie(subplots=True), which draws one pie per column:

import matplotlib
matplotlib.use("Agg")                    # save only, no window
import pandas as pd
from sales import regions, quarters, sales

df = pd.DataFrame(sales, index=quarters, columns=regions).T
axes = df.plot.pie(subplots=True, layout=(2, 2), figsize=(8, 7),
                   legend=False, autopct="%1.0f%%")
print(type(axes).__name__, axes.shape)
axes[0, 0].figure.savefig("pandas_pies.png")

Output:

ndarray (2, 2)

It returns a NumPy array of Axes; with layout=(2, 2) the run printed ndarray (2, 2). I still prefer the loop, because it gives me fixed colors and one shared legend.

How Do You Put Nested and Donut Pie Charts Side by Side?

Add wedgeprops={"width": 0.3} to turn a pie into a ring. Two rings with different radius values on the same Axes make a nested pie, and a ring with text in the middle makes a donut:

import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
from sales import regions, quarters, sales, region_colors

by_region = list(zip(*sales))              # 4 regions x 4 quarters
inner = [sum(q) for q in by_region]        # 2026 total per region
outer = [v for region in by_region for v in region]
outer_colors = [to_rgba(region_colors[r], a) for r in regions
                for a in (1.0, 0.8, 0.6, 0.4)]
ring = {"width": 0.3, "edgecolor": "white"}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8.6, 4.8),
                               layout="constrained")
ax1.pie(inner, radius=0.7, colors=[region_colors[r] for r in regions],
        startangle=90, counterclock=False, wedgeprops=ring)
ax1.pie(outer, radius=1.0, colors=outer_colors, startangle=90,
        counterclock=False, wedgeprops=ring)
ax1.set_title("Nested: 2026 total (inner),\nQ1-Q4 (outer)")

q4 = sales[3]
pc = ax2.pie(q4, colors=[region_colors[r] for r in regions],
             autopct="%1.1f%%", pctdistance=0.8, startangle=90,
             counterclock=False,
             wedgeprops={"width": 0.4, "edgecolor": "white"})
ax2.text(0, 0, f"Q4 2026\n${sum(q4):,.2f}", ha="center", va="center",
         fontsize=10, fontweight="bold")
ax2.set_title("Donut: Q4 2026 share")
fig.legend(pc.wedges, regions, loc="outside lower center", ncols=4,
           frameon=False)
print(f"Inner ring: {len(inner)} slices, ${sum(inner):,.2f}")
print(f"Outer ring: {len(outer)} slices")
plt.show()

Output:

Inner ring: 4 slices, $2,883,023.15
Outer ring: 16 slices
Matplotlib nested pie chart of 2026 region totals and quarters next to a donut chart of Q4 2026 sales with the total in the center
Left: region totals on the inner ring with each region’s four quarters around it. Right: a Q4 donut with the total in the center.

The inner ring adds up to the year total, $2,883,023.15, and the outer ring has 16 slices. Labeling every outer slice gets crowded fast; nested pie chart labels covers that.

For the donut, pctdistance=0.8 keeps percentages on the ring. The Matplotlib donut chart tutorial goes further with center text and gaps.

Troubleshooting Multiple Pie Charts in Matplotlib

ValueError on a negative value. A net refund line in Q4 West stopped my script cold. Pie wedges can’t be negative:

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

# Q4 2026 West after a refund batch was booked as one net line
values = [228945.95, 181660.25, 140220.55, -2169.35]
fig, ax = plt.subplots()
ax.pie(values)

Output:

Traceback (most recent call last):
  File "C:\pyguides\negative_pie.py", line 8, in <module>
    ax.pie(values)
  File "C:\pyguides\venv\Lib\site-packages\matplotlib\_api\deprecation.py", line 477, in wrapper
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\pyguides\venv\Lib\site-packages\matplotlib\__init__.py", line 1531, in inner
    return func(
           ^^^^^
  File "C:\pyguides\venv\Lib\site-packages\matplotlib\axes\_axes.py", line 3659, in pie
    raise ValueError("Wedge sizes 'x' must be non negative values")
ValueError: Wedge sizes 'x' must be non negative values
Command Prompt traceback of Matplotlib ax.pie raising ValueError because a wedge size is negative
ax.pie() rejects the negative West value with a ValueError before drawing anything.

The fix is to decide what a negative region means and report it, not hide it. Here I plot the positive regions and list the rest:

regions = ["Northeast", "Southeast", "Midwest", "West"]
values = [228945.95, 181660.25, 140220.55, -2169.35]

keep = [(r, v) for r, v in zip(regions, values) if v > 0]
skipped = [f"{r} (-${abs(v):,.2f})" for r, v in zip(regions, values)
           if v <= 0]
print("Plotting:", ", ".join(r for r, _ in keep))
print("Left out:", ", ".join(skipped))

Output:

Plotting: Northeast, Southeast, Midwest
Left out: West (-$2,169.35)

Legend cut off in the PNG. Use layout="constrained" with loc="outside lower center", and save with bbox_inches="tight".

Labels overlap on small pies. Drop wedge labels (labeldistance=None), keep percentages, and lean on the shared legend. Spacing between subplots is covered in Matplotlib tight_layout.

Important: pies of equal size hide that Q4 sold more than Q1. Put the total in each title, as in Step 4, or scale radius by the square root of each total.

Where to Take It Next with Matplotlib Pie Charts

Pull the top region forward in each quarter with explode; the explode and shadow effects guide shows the values that look right.

Call out one slice with an arrow and a note through pie chart annotation. To match a slide theme, set the figure color with pie chart background color.

These chart guides pair well with this one:

Frequently asked questions

How do I plot multiple pie charts in Matplotlib?

Create a grid with fig, axes = plt.subplots(2, 2), then loop over axes.flat and call ax.pie(values) once per dataset.

How do I add one legend for multiple pie charts?

Pass labeldistance=None to each ax.pie(), then call fig.legend(pc.wedges, labels, loc="outside lower center") with layout="constrained".

How do I keep the same colors in every pie chart?

Map each category to a color in a dictionary and pass colors=[color_map[name] for name in labels] to every ax.pie() call.

Can I make multiple pie charts from a pandas DataFrame?

Yes. Loop over df.items() and call ax.pie(column), or use df.plot.pie(subplots=True) for one pie per column.

How do I hide the empty subplot when I have an odd number of pies?

Call ax.remove() on each unused Axes, for example for ax in axes.flat[len(data):]: ax.remove().

What does ax.pie() return in Matplotlib 3.11?

A PieContainer with wedges and texts; older versions returned a tuple. See Axes.pie in the Matplotlib docs.