Align separate Matplotlib plotting areas

How do I align the plotting areas of separate Matplotlib figures?

In Matplotlib, use the same figsize and subplots_adjust(left=0.25, right=0.96, bottom=0.20, top=0.88) for both figures.

On this page

Published and tested 22 November 2026.

How can separate figures keep the same plotting area despite different tick widths?

In Matplotlib, use the same figsize and subplots_adjust(left=0.25, right=0.96, bottom=0.20, top=0.88) for both figures.

The four values locate the edges of the plotting area as fractions of the whole figure. Disable automatic layout, and export the complete canvas with bbox_inches=None. This example uses two separate 5 × 3.2 inch figures at 200 DPI, producing 1000 × 640 pixel PNGs. The shared left margin is wide enough for both sets of labels here; longer labels need another check.

Why can independently fitted layouts move the left edge?

tight_layout() calculates space from each figure's labels, so a longer decimal tick label can require more left margin. The two before images use the same input and canvas size as the corrected versions, but call tight_layout(pad=1.2) separately. Their plotting areas begin at 115.72 and 203.35 pixels from the left edge.

This article uses simulated example data. The five times are 0, 1, 2, 3 and 4 hours. Series A is 2, 5, 4, 7, 6; series B is 0.0002, 0.0005, 0.0004, 0.0007, 0.0006. The y scales differ by a factor of 10,000; read the response values against their respective y scales. “a.u.” means arbitrary units.

I align the edges of the plotting areas first. Two exported images can have the same width while their left axes still sit at different positions.

Before: Series A; 0–8 a.u. / 0–4 h
Before: Series A; 0–8 a.u. / 0–4 h
Before: Series B; 0–0.0008 a.u. / 0–4 h
Before: Series B; 0–0.0008 a.u. / 0–4 h

Before: independently fitted layouts leave different left margins. Both complete figures retain their own y-axis values.

What changes after fixing the margins?

Both corrected plotting areas start at x = 250 pixels and have width 710 pixels and height 435.2 pixels on the 1000 × 640 canvas. Their bottom edge is 128 pixels above the canvas bottom. The input values, axis ranges, tick formatting and font size are unchanged.

After: Series A; 0–8 a.u. / 0–4 h
After: Series A; 0–8 a.u. / 0–4 h
After: Series B; 0–0.0008 a.u. / 0–4 h
After: Series B; 0–0.0008 a.u. / 0–4 h

After: the two separate exports share all four plotting-area edges. Insert both images at the same displayed width to preserve the alignment.

How do I reproduce and check the exports?

Run the complete script below with Python and Matplotlib 3.8.4: python example.py. It writes four PNGs, two corrected PDFs, the input CSV and the measured positions CSV beside the script. The test environment uses the Agg backend and DejaVu Sans. The corrected PDFs have 360 × 230.4 point pages, equivalent to 5 × 3.2 inches.

"""Original Bopbun example; code and synthetic observations: CC0-1.0."""
from pathlib import Path
import csv
import json
import platform
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

OUT = Path(__file__).resolve().parent
plt.rcdefaults()
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 11,
                     'figure.autolayout': False, 'figure.constrained_layout.use': False,
                     'savefig.bbox': None})
x = [0, 1, 2, 3, 4]
series = {'A': [2, 5, 4, 7, 6], 'B': [0.0002, 0.0005, 0.0004, 0.0007, 0.0006]}
rows = []
with (OUT / 'synthetic.csv').open('w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['time_h', 'series_A', 'series_B'])
    w.writerows(zip(x, series['A'], series['B']))
for stage in ['before', 'after']:
    for name, y in series.items():
        fig, ax = plt.subplots(figsize=(5, 3.2), dpi=200, layout=None)
        ax.plot(x, y, 'o-', color='#007C83', linewidth=1.8)
        ax.set(xlabel='Time (h)', ylabel='Response (a.u.)', title=f'Series {name}', xlim=(-0.2, 4.2))
        factor = 1 if name == 'A' else 0.0001
        ax.set_ylim(0, 8 * factor)
        ax.set_yticks([v * factor for v in [0, 2, 4, 6, 8]])
        ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f' if name == 'A' else '%.4f'))
        ax.set_xticks(x)
        ax.grid(axis='y', color='#dddddd')
        if stage == 'before':
            fig.tight_layout(pad=1.2)
        else:
            fig.subplots_adjust(left=0.25, right=0.96, bottom=0.20, top=0.88)
        fig.canvas.draw()
        box = ax.get_window_extent()
        rows.append({'stage': stage, 'series': name, 'left_px': box.x0,
                     'bottom_px': box.y0, 'width_px': box.width, 'height_px': box.height})
        fig.savefig(OUT / f'{stage}-{name}.png', dpi=200, bbox_inches=None)
        if stage == 'after':
            fig.savefig(OUT / f'{stage}-{name}.pdf', bbox_inches=None, metadata={'CreationDate': None, 'ModDate': None})
        plt.close(fig)
with (OUT / 'positions.csv').open('w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0]))
    w.writeheader()
    w.writerows(rows)
(OUT / 'runtime.json').write_text(json.dumps({'python': platform.python_version(),
    'matplotlib': matplotlib.__version__, 'backend': matplotlib.get_backend(),
    'font': 'DejaVu Sans', 'canvas_px': [1000, 640], 'positions': rows}, indent=2), encoding='utf-8')
print(json.dumps(rows))

What should I check if my own figures still shift?

Keep automatic layout off, use the same canvas size and margins, and avoid per-file tight cropping when positioning full images. bbox_inches="tight" can change each exported canvas according to its labels. These settings assume ordinary Cartesian axes with automatic aspect; equal-aspect axes, colorbars and added axes need separate geometry checks. If labels overlap or clip, increase the shared margin for both figures and inspect both exports again.

example.py

synthetic.csv

positions.csv

after-A.png

after-B.png

after-A.pdf

after-B.pdf

LICENSE.txt

Matplotlib 3.8.4: subplots_adjust · savefig

For equal numerical limits inside one figure, see the shared-axis answer. For unequal panel proportions, see GridSpec ratios.

Which sources and licenses apply?

Original code and data: CC0-1.0. DejaVu Sans font rights remain separate. Install Matplotlib and NumPy locally to run the code.

Related public question — Nov 11; exact year/timezone metadata unverified.

SHA256 · DejaVu · Matplotlib · NumPy