How to plot multiple dataframes in subplots
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Plotting several pandas DataFrames in subplots is a common reporting pattern when you need side-by-side trend comparison. The main challenges are layout consistency, axis alignment, and avoiding repetitive plotting code. A small reusable structure with dynamic subplot creation keeps chart code clean and scalable.
Build a Reusable Plot Specification
Instead of writing one hardcoded block per DataFrame, define a list of plotting specs. Each spec carries the DataFrame, selected columns, title, and optional style settings.
This approach makes it easy to add or remove panels without rewriting layout logic.
Create Subplots Dynamically
Use matplotlib.pyplot.subplots with nrows=len(plot_specs) so the figure adapts automatically. Also normalize the single-axis case, because matplotlib returns a scalar axis when only one subplot exists.
sharex=True is particularly useful for time series because all panels align naturally.
Plot Multiple Columns Per Subplot
Some DataFrames contain related metrics that belong in one panel. You can pass multiple columns per spec and let pandas build the legend.
This works well when the series share units and scale.
Two-Column Grid Layout
When you have many DataFrames, a vertical stack can become too tall. A grid layout improves readability in dashboards.
Always hide unused axes in incomplete last rows so the final chart looks intentional.
Keep Axes Comparable Across Panels
For fair visual comparison, align y-axis limits when metrics share units. If units differ, separate scales are fine, but label axes clearly.
Use this only when it improves interpretation. Forced shared limits on very different ranges can flatten small but meaningful variation.
Encapsulate as a Helper Function
For repeated usage in notebooks or services, wrap plotting behavior in a function.
Now chart creation is a one-line call from data pipelines and report scripts.
Common Pitfalls
- Assuming
axesis always iterable, which breaks when only one subplot exists. - Plotting all columns by default and creating unreadable legends with noisy lines.
- Forgetting shared x-axis for time series, which makes cross-panel comparison difficult.
- Leaving unused grid cells visible in multi-column layouts.
- Mixing metrics with very different units on shared y-axis without clear labeling.
Summary
- Use a plot specification list to remove repetitive plotting logic.
- Generate subplot layouts dynamically from dataset count.
- Normalize single-subplot behavior so code remains robust.
- Choose stacked or grid layout based on number of panels and report size.
- Align axes intentionally and wrap the final pattern in a reusable helper.

