Sub topic 10
One panel per column with subplots=True
A single axes works when all columns share a unit and a similar range. When one column holds thousands of units and another holds a percentage, the small series flattens into a line along the bottom. This chapter shows how subplots=True gives each column its own panel, how to arrange the panels, and how to customize them afterward.
This chapter assumes you can build a DataFrame, set an index, and call df.plot() with a kind. It also assumes you know that plot returns a matplotlib Axes. If the Axes part is hazy, review the chapter on the returned Axes first.
The basic call
Pass subplots=True and pandas creates one Axes per plotted column, stacked vertically. The data below has two columns in the hundreds and one in the thirties.
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],
"margin_pct": [33.3, 33.3, 36.7, 35.3],
}).set_index("month")
axes = df.plot(subplots=True, figsize=(6, 6), marker="o")
print(type(axes), axes.shape)
plt.show()The print line shows <class 'numpy.ndarray'> (3,). With subplots=True, plot does not return a single Axes. It returns a NumPy array of Axes, one per column, in column order. Each panel picks its own y range, so the margin_pct line is no longer squashed.
Which columns get a panel
The rules that decide what is plotted are the same as for a single chart. Only numeric columns are plotted, and the index becomes the x axis. If you did not call set_index("month"), the text column would be skipped, and the x axis would show row numbers instead of month names.
You can choose columns before plotting or with y:
df[["sales", "costs"]].plot(subplots=True)
df.plot(y=["sales", "margin_pct"], subplots=True)
plt.show()Both calls draw two panels. Prefer selecting columns when the panel count matters, because each extra numeric column adds a panel.
Arranging panels with layout
By default the panels form one column. The layout argument takes (rows, columns). Use -1 for one dimension and pandas works it out from the number of columns.
axes = df.plot(subplots=True, layout=(2, -1), figsize=(8, 5))
print(axes.shape)
plt.tight_layout()
plt.show()With three columns and two rows, pandas needs two grid columns, so axes.shape is (2, 2). The unused fourth cell is left blank. The returned array is now two-dimensional.
The grid must be large enough. layout=(1, 2) for three columns raises a ValueError saying the layout is smaller than the required size. A layout like (1, -1) is a safe way to ask for one row.
Sharing axes
Two arguments control whether panels share an axis:
| Argument | Default with subplots=True | Effect |
|---|---|---|
| `sharex` | `True` when pandas creates the figure | All panels use the same x range. Tick labels are hidden on inner panels. |
| `sharey` | `False` | When `True`, all panels use one y range. |
| `layout` | one column | Grid shape as `(rows, columns)`. |
| `figsize` | matplotlib default | Size of the whole figure, not of each panel. |
| `legend` | `True` | Draws a legend in each panel when enabled. |
Choose sharey by what you want to compare. If the columns have the same unit and you want to compare heights, use sharey=True. If they have different units, leave it off. With a grid layout, sharex=False keeps tick labels on every panel, which helps when the x values differ or when you want to read each panel on its own.
df[["sales", "costs"]].plot(subplots=True, layout=(1, 2), sharey=True, sharex=False, figsize=(8, 3), kind="bar", rot=0)
plt.tight_layout()
plt.show()Here both panels are in units sold or spent, so a shared y axis keeps the bar heights comparable.
Titles, colors and legends per panel
Several styling arguments accept a list when subplots=True:
titletakes a list of strings, one per panel. A single string would be used as a title for the whole figure instead.colortakes a list of colors, matched to columns in order.legend=Falseremoves the redundant legend in each panel, since a panel title says what is drawn.
The list length must match the number of panels. A title list that is too short or too long raises a ValueError.
axes = df.plot(
subplots=True,
layout=(3, 1),
figsize=(6, 7),
color=["tab:blue", "tab:red", "tab:green"],
title=["Sales", "Costs", "Margin"],
legend=False,
)Customizing each panel through the returned array
The array of Axes lets you adjust panels one by one. Because a two-dimensional layout returns a two-dimensional array, use axes.flat to iterate in a way that works for every layout.
units = ["Units", "Units", "Percent"]
for ax, unit in zip(axes.flat, units):
ax.set_ylabel(unit)
ax.grid(alpha=0.3)
axes[0].figure.suptitle("Q1 overview", y=1.0)
axes[0].figure.tight_layout()
axes[0].figure.savefig("overview.png", dpi=150, bbox_inches="tight")Every Axes in the array belongs to the same figure, so axes[0].figure gives you the figure object for saving or for a figure-wide title. When panels are blank in a grid, the extra cells are still in the array, so a loop with zip and a shorter list stops at the shorter one and does not fail.
Plotting into your own figure
You can also create the grid yourself and hand pandas the Axes through ax. This is useful when the panels belong to a bigger figure that has other content.
fig, axs = plt.subplots(1, 3, figsize=(9, 3))
df.plot(subplots=True, ax=axs, legend=False)
fig.suptitle("Q1 overview")
fig.tight_layout()
plt.show()The number of Axes you pass must equal the number of plotted columns. Passing four Axes for three columns raises a ValueError. Do not also pass layout or figsize, because the grid already exists and pandas will not use them to build it. In this mode sharex defaults to False, so inner panels keep their tick labels unless you ask for sharing.
When to use subplots=True and when not to
- Use it when columns differ in scale or unit, or when overlapping lines make a single chart hard to read.
- Avoid it for more than about a dozen columns. The panels become too small to read. Select the columns that matter, or aggregate first.
- Avoid it when you want to compare shapes directly on one scale. A single Axes with a shared y range is easier to read than many panels.
- For grouped categories, plot a summary first and consider a grouped bar chart instead of one panel per category.
Common errors
- A layout that is too small.
layout=(1, 2)with three columns raises aValueError. Use-1for one dimension to avoid counting. - Wrong number of Axes in
ax. The array you pass must match the number of plotted columns. - A title list of the wrong length. The list must have one string per panel.
- A bad index in a loop.
axes[0, 1]fails on a one-dimensional result. Useaxes.flatwhen the layout may change. - Text columns. Non-numeric columns are skipped. If every column is text, pandas raises
TypeError: no numeric data to plot.
Exercise
A DataFrame has 5 numeric columns. You call df.plot(subplots=True, layout=(2, -1)). What is the shape of the returned array of Axes, and how many cells are blank?
Show answer
Five panels in two rows need three grid columns (ceil of 5 / 2), so the shape is (2, 3). That grid has 6 cells, so one cell is blank.
Exercise
You want one row of three panels that all use the same y range, with a title for each panel and no legends. Write the plot call for the DataFrame df with columns "a", "b" and "c".
Show answer
df.plot(subplots=True, layout=(1, -1), sharey=True, title=["A", "B", "C"], legend=False, figsize=(9, 3)). The title list has three entries, one per panel, and sharey=True gives all panels the same y range.