Lesson
14: Multi-Panel Subplots, Dual Axes (twinx), Error Bars
& Contour Maps
The “Boring Stuff” Problem: Side-by-Side Tradeoffs & Field Visuals
Real engineering reports rarely use a single standalone XY curve. You need to show:
- Side-by-side Pump Head & NPSH margin
(
Fluids): Head in meters[m]on the left axis and Efficiency[%]on the right axis (ax.twinx()) sharing the exact same Flow Rate \(Q\)! - Multi-panel Comparative Grids
(
fig, axes = plt.subplots(1, 2)): Comparing Parallel-Flow vs. Counterflow vs. Crossflow heat exchangers side-by-side (HMT). - 2D Spatial Fields (
contourf,quiver,streamplot): Seeing stagnation zones around cylinders (Fluid Mechanics Module 6) or stress intensity fields cleanly.
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
# Example 1 (Fluid Mechanics Module 5): Dual-Panel Pump Operating Point & Twin-Axis NPSH Safety
pump_path = next(p for p in [Path("datasets/Fluids_Pump_and_Pipe_Network_Data.csv"), Path("../datasets/Fluids_Pump_and_Pipe_Network_Data.csv")] if p.exists())
pd_arr = np.loadtxt(pump_path, delimiter=",", skiprows=1, usecols=range(9))
Q, _, _, H_sys, H_pump, eta, pow_kw, npsha, npshr = pd_arr.T
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.3))
# Left Panel: System vs Pump Curve + Efficiency on right twin Y-axis
ax1.plot(Q, H_pump, "o-", color="#0284c7", lw=2, label="Pump Head $H_{pump}$")
ax1.plot(Q, H_sys, "s--", color="#dc2626", lw=2, label="System Head $H_{sys}$")
ax1.set_xlabel("Volumetric Flow Rate $Q$ [L/s]")
ax1.set_ylabel("Total Dynamic Head [m]", color="#0284c7")
ax1.set_title("Pump-System Matching & Efficiency")
ax1.grid(True, alpha=0.3)
ax1_r = ax1.twinx()
ax1_r.plot(Q, eta * 100, "^:", color="#059669", lw=2, label="Efficiency $\\eta$ [%]")
ax1_r.set_ylabel("Pump Efficiency $\\eta$ [%]", color="#059669")
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax1_r.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="center left", fontsize=8)
# Right Panel: Cavitation Safety Margin
ax2.plot(Q, npsha, "o-", color="#0284c7", lw=2, label="$NPSH_A$ (Available)")
ax2.plot(Q, npshr, "s--", color="#dc2626", lw=2, label="$NPSH_R$ (Required)")
ax2.fill_between(Q, npshr, npsha, where=(npsha < npshr), color="#fca5a5", alpha=0.5, label="Cavitation Zone")
ax2.set_title("Suction Cavitation Envelope")
ax2.set_xlabel("Volumetric Flow Rate $Q$ [L/s]")
ax2.set_ylabel("Suction Head [m]")
ax2.grid(True, alpha=0.3)
ax2.legend(fontsize=8)
fig.tight_layout()
# Example 2 (Fluid Mechanics Module 6): Potential Flow Streamlines & Pressure Field Contour Around Spinning Cylinder
R = 1.0
U_inf = 10.0
Gamma = -2.0 * np.pi * U_inf * R * 1.0 # Clockwise lift circulation gamma* = 0.5 -> Gamma = -4*pi*U*R*gamma*
x = np.linspace(-3.2, 3.2, 160)
y = np.linspace(-2.5, 2.5, 130)
X, Y = np.meshgrid(x, y)
r2 = X**2 + Y**2
r = np.sqrt(r2)
theta = np.arctan2(Y, X)
with np.errstate(divide="ignore", invalid="ignore"):
vr = U_inf * (1.0 - (R**2) / r2) * np.cos(theta)
vt = -U_inf * (1.0 + (R**2) / r2) * np.sin(theta) + Gamma / (2.0 * np.pi * r)
u = vr * np.cos(theta) - vt * np.sin(theta)
v = vr * np.sin(theta) + vt * np.cos(theta)
Cp = 1.0 - (u**2 + v**2) / (U_inf**2)
mask_inside = r < R
u[mask_inside], v[mask_inside] = np.nan, np.nan
Cp[mask_inside] = np.nan
fig, ax = plt.subplots(figsize=(7.2, 4.8))
cf = ax.contourf(X, Y, Cp, levels=np.linspace(-3.5, 1.0, 22), cmap="coolwarm", extend="both")
fig.colorbar(cf, ax=ax, label="Pressure Coefficient $C_p = (P-P_\\infty)/q_\\infty$")
ax.streamplot(X, Y, np.nan_to_num(u), np.nan_to_num(v), color="#0f172a", density=1.35, linewidth=0.9)
ax.add_patch(plt.Circle((0, 0), R, color="#475569", zorder=5))
ax.set_aspect("equal")
ax.set_title("Magnus Lifting Cylinder: Potential Streamlines & Surface $C_p$ Contour")
ax.set_xlabel("$x / R$")
ax.set_ylabel("$y / R$")
fig.tight_layout()
Practice Questions (Concept Check)
- Notice in Example 1 we combined legends from
ax1andax1_rusingax1.get_legend_handles_labels() + ax1_r.get_legend_handles_labels(). Why is that better than callingax1.legend()andax1_r.legend()separately? - What does
ax.set_aspect("equal")guarantee for geometric plots like flow around a circle or structural cross-sections? - What does
fig, axes = plt.subplots(2, 2)return asaxes’s shape? - Why did we mask
r < Rwithnp.nanbefore plotting contours around the cylinder?
Guided
Practice Problem 1 (Worked Self-Check): 2-Panel Pin-Fin Performance
& Bar Chart (Heat Transfer)
Load datasets/HMT_Pin_Fin_Heat_Sink_Data.csv. Create a
1x2 subplot figure: Left panel showing
Air_Velocity_m_s vs. Total_Heat_Dissipation_W
(with Convection_Coeff_h_W_m2K on a twin right axis), and
Right panel showing Single_Fin_Efficiency_eta_f
(%) across velocities as a crisp bar chart!
Hint: Column indices in HMT_Pin_Fin_Heat_Sink_Data.csv
Col 0 = Air_Velocity_m_s, Col 3 =
Convection_Coeff_h_W_m2K, Col 5 =
Single_Fin_Efficiency_eta_f, Col 7 =
Total_Heat_Dissipation_W.
# Worked Practice Problem 1 Solution: 2-Panel Pin-Fin Performance Dashboard
fin_path = next(p for p in [Path("datasets/HMT_Pin_Fin_Heat_Sink_Data.csv"), Path("../datasets/HMT_Pin_Fin_Heat_Sink_Data.csv")] if p.exists())
fd = np.loadtxt(fin_path, delimiter=",", skiprows=1)
vel, h_c, eta_f, Q_w = fd[:, 0], fd[:, 3], fd[:, 5] * 100.0, fd[:, 7]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.0))
ax1.plot(vel, Q_w, "o-", color="#dc2626", lw=2, label="Total Q [W]")
ax1.set_xlabel("Air Velocity [m/s]"); ax1.set_ylabel("Heat Dissipated Q [W]", color="#dc2626")
ax1.set_title("Heat Sink Q & h vs. Air Velocity"); ax1.grid(True, alpha=0.3)
ax1r = ax1.twinx()
ax1r.plot(vel, h_c, "s--", color="#0284c7", label="h [W/m^2K]")
ax1r.set_ylabel("h [W/(m^2*K)]", color="#0284c7")
ax2.bar([f"{v:.1f}" for v in vel], eta_f, color="#059669", alpha=0.85)
ax2.set_title("Single Pin Fin Efficiency $\\eta_f$ [%]")
ax2.set_xlabel("Air Velocity [m/s]"); ax2.set_ylabel("Fin Efficiency [%]")
ax2.set_ylim(0, 100); ax2.grid(True, axis="y", alpha=0.3)
fig.tight_layout()
End-of-Chapter Practice Problems (Try Yourself!)
- Heat Exchanger \(\\varepsilon\)-NTU Side-by-Side Plot
(
Heat Transfer): Loaddatasets/HMT_Heat_Exchanger_NTU_Data.csvand plot Counterflow (\(C_r = 0.5, 1.0\)) vs. Parallel Flow (\(C_r = 0.5, 1.0\)) vs. Shell-and-Tube (\(C_r = 1.0\)) cleanly in two panels (Cr = 0.5on left,Cr = 1.0on right). - Error Bar Calibration Chart: Plot mean PT100
resistance with synthetic \(\\pm
0.5\\,\\Omega\) measurement uncertainty bars
(
ax.errorbar). - Solar Radiation & Efficiency Twin Plot
(
Solar Thermal): PlothourvsG_T_W_m2(left axis bar/area) andefficiency_percent(right axis line) fromdatasets/Solar_Collector_FlatPlate_Hourly_Data.csv.
🎬 Concept & Engineering Animation
🎬 Pump System Match Twin Axis