bhylu.com

Advertisements

Matplotlib Subplot

Subplots put related views in one figure. Use common scales when direct comparison matters, and label each panel's distinct purpose.

Understand the idea

subplots can return several Axes objects, which you then configure individually. Shared axes are useful for comparable quantities but inappropriate when units differ. layout='constrained' helps allocate space for labels. The example deliberately compares counts rather than mixing an amount and a count on an unlabeled shared scale.

Where to try it

Run this complete script in a local virtual environment with Matplotlib installed (py -m pip install matplotlib). It uses a non-interactive backend and saves workshop.png in the current folder. The site shows a rendered example below; its text-only online runner does not display plot windows.

A worked example

Python

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
plt.close(fig)
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True, layout="constrained")
axes[0].bar(["Morning", "Evening"], [8, 12])
axes[1].bar(["Morning", "Evening"], [10, 14])
axes[0].set(title="Week 1", ylabel="Attendees")
axes[1].set_title("Week 2")
fig.savefig("workshop.png", dpi=140)
plt.close(fig)
print("Saved workshop.png")

Read the result

Two panels share the attendee scale, so the taller bars reflect a real cross-panel difference.

Two panels share the attendee scale, so the taller bars reflect a real cross-panel difference.
Rendered from this original example. Change and rerun the script locally to make your own chart.

Try one change

Remove sharey and inspect the new limits, then decide which version matches the report's purpose.

For package options, see the Matplotlib documentation.