Sub topic 10
One panel per column with subplots=True
This chapter assumes you can call df.plot(), know how set_index moves a column onto the x axis, and have matplotlib installed. By the end you will be able to give each column its own panel, arrange the panels in a grid, and control which axes are shared.
Why separate panels
By default, plot draws every numeric column on one set of axes. That works when the columns have similar scales. If one column ranges from 0 to 1 and another from 0 to 100000, the small one flattens into a line along the bottom. Passing subplots=True gives each column its own Axes, so each gets a readable scale.
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],
})
axes = df.set_index("month").plot(subplots=True, marker="o", figsize=(6, 4))
plt.show()The panels are stacked vertically and share the x axis. Because the call returns a NumPy array of Axes, axes[0] is the top panel and axes[1] is the bottom one.
Arranging panels with layout
The layout argument takes a (rows, columns) tuple. This example puts the two panels side by side.
axes = df.set_index("month").plot(
subplots=True,
layout=(1, 2),
figsize=(8, 3),
sharex=False,
legend=False,
title=["Sales", "Costs"],
)
plt.tight_layout()
plt.show()Several arguments work together here:
layout=(1, 2)makes one row of two panels. Use-1for one dimension, as inlayout=(-1, 2), and pandas works out the number of rows.sharex=Falsegives each panel its own x tick labels. When you do not passax,sharexdefaults toTrue.sharey=Trueforces all panels onto one y scale. Use it when you want to compare magnitudes. Leave it off when you want each column's shape to be readable.legend=Falseremoves the legend, which is redundant when each panel has a title.titletakes a single string for the whole figure, or a list with one string per panel.
tight_layout() is a matplotlib call that adjusts spacing so titles and tick labels do not overlap.
Working with the returned Axes
With no layout, axes is a one-dimensional array. With layout, it is two-dimensional, so axes[0] is a whole row. Call flatten() to get a simple loop.
axes = df.set_index("month").plot(subplots=True, layout=(1, 2), figsize=(8, 3), legend=False)
for ax, label in zip(axes.flatten(), ["Units", "Dollars"]):
ax.set_ylabel(label)
plt.tight_layout()
plt.show()Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError` about layout | `rows * columns` is smaller than the number of columns being plotted | Use a bigger grid, or `layout=(-1, 2)` |
| `TypeError: no numeric data to plot` | The columns left after `set_index` or selection are not numeric | Select numeric columns with `df[["sales", "costs"]]` |
| Overlapping x labels | Panels share x and the labels are crowded | Increase `figsize`, use `rot=0` or another angle, and call `plt.tight_layout()` |
| `axes[0, 1]` raises `IndexError` | No `layout` was given, so `axes` is one-dimensional | Use `axes[1]`, or pass `layout` |
Exercise
You have a DataFrame with five numeric columns and want them in a grid of two columns. You call df.plot(subplots=True, layout=(2, 2)). What happens, and how do you fix it?
Show answer
pandas raises a ValueError because a 2 by 2 grid has four cells and there are five columns. Use layout=(3, 2), or layout=(-1, 2) to let pandas compute the number of rows.
Exercise
Two columns have very different scales, and you want to compare their shapes. Should you use sharey=True? Explain.
Show answer
No. With sharey=True the small column is squeezed into a flat line on the large column's scale. Leave sharey at its default, which is False when subplots=True, so each panel scales itself to its own data.