1. Why Subplots
Subplots put several related charts on one figure so stakeholders see distribution, trend, and comparisons together instead of separate windows.
2. Grid Basics
plt.subplots(nrows, ncols, figsize=...) returns a figure and a 2D axes array. For a 2×2 grid:
ax[0, 0] — top-left
ax[0, 1] — top-right
ax[1, 0] — bottom-left
ax[1, 1] — bottom-right
3. Synthetic 2×2 Demo
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(2, 2, figsize=(8, 6))
ax[0, 0].plot(x, y, color="b")
ax[0, 0].set_title("Line Plot")
ax[0, 1].scatter(x, y, color="r")
ax[0, 1].set_title("Scatter Plot")
random_data = np.random.randn(200)
ax[1, 0].hist(random_data, bins=20, color="g")
ax[1, 0].set_title("Histogram")
categories = ["A", "B", "C"]
values = [5, 7, 3]
ax[1, 1].bar(categories, values, color="m")
ax[1, 1].set_title("Bar Chart")
plt.tight_layout()
plt.show()
plt.tight_layout() reduces label collisions between adjacent cells.
4. E-Commerce 2×2 Dashboard
import pandas as pd
df = pd.read_csv("ecommerce_orders.csv", parse_dates=["Order Date"])
fig, ax = plt.subplots(2, 2, figsize=(10, 8))
ax[0, 0].hist(df["Revenue"], bins=30, color="g")
ax[0, 0].set_title("Revenue Distribution")
monthly = df.set_index("Order Date")["Revenue"].resample("ME").sum()
ax[0, 1].plot(monthly.index, monthly.values, color="r")
ax[0, 1].set_title("Monthly Revenue Trend")
ax[1, 0].hist(df["Delivery Days"], bins=10, color="m")
ax[1, 0].set_title("Delivery Days Distribution")
ax[1, 1].hist(df["Customer Rating"], bins=10, color="b")
ax[1, 1].set_title("Customer Rating Distribution")
plt.tight_layout()
plt.show()
5. sharey
sharey=True aligns y-scales across columns and shows tick labels only on the leftmost subplot; sharey=False (default) gives each panel its own scale.
fig, ax = plt.subplots(1, 2, sharey=True, figsize=(8, 4))
ax[0].plot([1, 2, 3], [0.2, 0.5, 0.8])
ax[0].set_title("First Subplot (Y-Labels Shown)")
ax[1].plot([1, 2, 3], [0.3, 0.4, 0.9])
ax[1].set_title("Second Subplot (Y-Labels Shared)")
plt.show()