Lesson 19: Matplotlib Object-Oriented Plotting (fig, ax) — River DO Sag & Pump Curves

The “Boring Stuff” Problem: Redoing 12 Excel Charts Every Time New Lab Data Arrives

Manually clicking fonts, axis ranges, legends, and error bars in a spreadsheet takes 20 minutes per figure—and if your lab advisor asks to highlight the \(5.0\text{ mg/L}\) dissolved oxygen aquatic standard, you have to rebuild screenshots by hand.

In Matplotlib, we always use the clean Object-Oriented API:

fig, ax = plt.subplots(figsize=(7.5, 4.4))

Think of fig as the blank page and ax as the calibrated graph window inside it. Every unit label (ax.set_xlabel), curve (ax.plot), compliance threshold (ax.axhline), critical-point annotation (ax.annotate), and grid (ax.grid) stays inside a reusable 12-line recipe that renders 300 dpi publication graphics automatically whenever the CSV updates!

from pathlib import Path
def data_file(name):
    """Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
    for p in [
        Path("datasets") / name,
        Path("../datasets") / name,
        Path("../../datasets") / name,
    ]:
        if p.exists():
            return p
    raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import numpy as np
import matplotlib.pyplot as plt

# Example 1 (Water Quality Modeling): Annotated Streeter-Phelps Dissolved Oxygen Sag Curve
x_km = np.linspace(0.0, 140.0, 281)
u_km_d, kd, kr = 24.0, 0.25, 0.55
L0, D0, DO_sat = 26.0, 1.2, 9.2
t = x_km / u_km_d
D = (kd * L0 / (kr - kd)) * (np.exp(-kd * t) - np.exp(-kr * t)) + D0 * np.exp(-kr * t)
DO = DO_sat - D

# Exact critical point
tc = np.log((kr / kd) * (1.0 - D0 * (kr - kd) / (kd * L0))) / (kr - kd)
xc = tc * u_km_d
Dc = (kd / kr) * L0 * np.exp(-kd * tc)
DO_min = DO_sat - Dc

fig, ax = plt.subplots(figsize=(7.8, 4.3))
ax.plot(x_km, DO, color="#0284c7", lw=2.5, label="River Dissolved Oxygen DO(x)")
ax.plot(x_km, L0 * np.exp(-kd * t), color="#d97706", ls="--", lw=1.8, label="Remaining BODu(x)")
ax.axhline(5.0, color="#dc2626", ls=":", lw=1.8, label="Warmwater Fish Standard (5.0 mg/L)")
ax.fill_between(x_km, DO, 5.0, where=(DO < 5.0), color="#fecaca", alpha=0.55, label="Hypoxic Violation Zone")
ax.plot(xc, DO_min, "ro", markersize=7)
ax.annotate(f"Critical Point\n({xc:.1f} km, {DO_min:.2f} mg/L)",
            xy=(xc, DO_min), xytext=(xc + 16, DO_min - 1.5),
            arrowprops=dict(arrowstyle="->", color="#0f172a"), fontsize=9, fontweight="bold")
ax.set_title("Streeter-Phelps River Oxygen Sag Curve Downstream of Outfall")
ax.set_xlabel("Downwind River Distance x [km]")
ax.set_ylabel("Concentration [mg/L]")
ax.set_ylim(0, 28)
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8.5, loc="upper right")
fig.tight_layout()
print(f"Critical Point: t_c={tc:.2f} d ({xc:.1f} km) -> Minimum DO = {DO_min:.2f} mg/L")
Matplotlib Object-Oriented Plotting (fig, ax) — River DO Sag & Pump Curves Output Plot 1
Critical Point: t_c=2.44 d (58.5 km) -> Minimum DO = 2.78 mg/L
# Example 2 (Fluid Mechanics Course Integration): Pump vs. System Curve & Cavitation Safety Margin
p_arr = np.genfromtxt(data_file("Fluids_Pump_and_Pipe_Network.csv"), delimiter=",", skip_header=1, usecols=(0, 3, 4, 5, 7, 8))
q_ls, h_sys, h_pump, eta, npsha, npshr = p_arr.T

fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.plot(q_ls, h_pump, "o-", color="#0284c7", lw=2.2, label="Centrifugal Pump Head H_pump [m]")
ax.plot(q_ls, h_sys, "s--", color="#059669", lw=2.2, label="Treatment Pipe System Head H_sys [m]")
ax.plot(q_ls, npsha - npshr, "^:", color="#dc2626", lw=1.8, label="Net Suction Margin (NPSHa - NPSHr) [m]")
ax.axhline(0.0, color="#dc2626", lw=1.0, alpha=0.5)
ax.set_title("Water Treatment Lift Pump vs. Pipe Network Curve (Fluid Mechanics Dataset)")
ax.set_xlabel("Volumetric Flow Rate Q [L/s]")
ax.set_ylabel("Head [m]")
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8.5)
fig.tight_layout()
Matplotlib Object-Oriented Plotting (fig, ax) — River DO Sag & Pump Curves Output Plot 2

Concept Check Questions

  1. Why should every axis label include bracketed engineering units ([mg/L], [km], [m])?
  2. What does ax.fill_between(x, DO, 5.0, where=(DO < 5.0)) visually highlight on the Streeter–Phelps chart?
  3. Why did Example 2 plot (NPSHa - NPSHr) alongside H_pump and H_sys?

Guided Practice Problem 1: Solar Collector Thermal Efficiency Curve (Solar_Irradiance_Collector_Hourly.csv)

Load Solar_Irradiance_Collector_Hourly.csv (columns hour, G_T_W_m2, T_amb_C, U_L_W_m2K, efficiency_percent), filter active daytime hours (G_T_W_m2 > 0), and plot both solar irradiance \(G_T\) and thermal efficiency % across daytime hours!

# Guided Practice 1 Starter
sol = np.loadtxt(data_file("Solar_Irradiance_Collector_Hourly.csv"), delimiter=",", skiprows=1)
day = sol[sol[:, 1] > 0]
fig, ax = plt.subplots(figsize=(7.0, 3.8))
ax.plot(day[:, 0], day[:, 1], "o-", color="#f59e0b", lw=2, label="Tilted Irradiance G_T [W/m^2]")
ax.set_title("Daytime Solar Collector Irradiance Profile (Solar Thermal Course)")
ax.set_xlabel("Hour of Day [LST]")
ax.set_ylabel("Solar Irradiance G_T [W/m^2]")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
Matplotlib Object-Oriented Plotting (fig, ax) — River DO Sag & Pump Curves Output Plot 3