Lesson
13: Matplotlib Essentials โ Publication-Grade Engineering
Plots in Minutes
The โBoring Stuffโ Problem: Manually Formatting 15 Lab Charts Every Week
Think about formatting a chart in a spreadsheet: clicking every axis title, re-typing fonts, tweaking tick ranges, exporting an imageโonly to realize someone gave you an updated CSV file two hours before the report deadline, forcing you to redo all 15 charts by hand!
With Matplotlib, you write a clean
10-line recipe once. When new lab data arrives, re-running the script
regenerates crisp, vector-sharp 300 dpi charts
automatically with identical colors, legends, units, and LaTeX math
symbols!
Use
the Explicit Object-Oriented (fig, ax) Style From Day
One
Matplotlib has two ways to plot: an old quick-hack
plt.plot(...) global state, and the clean
Object-Oriented API:
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(x, y, "o-", color="#0284c7", linewidth=2, label="Series")
ax.set_xlabel("X Quantity [unit]")
ax.set_ylabel("Y Quantity [unit]")
ax.set_title("Clear Engineering Chart Title")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()Think of fig as the physical sheet of graph paper and
ax as the coordinate box drawn inside it. Every label
(ax.set_xlabel), curve (ax.plot), reference
line (ax.axhline), and legend (ax.legend)
talks directly to ax, which scales effortlessly to
multi-panel figures next lesson.
Watch Out! Three Classic Matplotlib Traps
- Always Call
fig.tight_layout(): Without it, axis labels or titles get clipped along the edge of saved PNG files. - Every Engineering Axis Needs
[Units]: Never turn in a plot labeled"Stress"or"Temp"without units like"Stress $\\sigma$ [MPa]"or"Temperature $T$ [K]". - Avoid Cluttered Legends: Place at most 3โ5 distinct
curves per axes, using color plus line style (
--,:, markers) so grayscale printers and colorblind readers can distinguish every curve!
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
# Example 1 (Solid Mechanics & Instrumentation): Tensile Stress-Strain Curve (Real CSV!)
rtd_path = next(
p for p in [
Path("datasets/Solids_Tensile_Stress_Strain_RTD_Data.csv"),
Path("../datasets/Solids_Tensile_Stress_Strain_RTD_Data.csv"),
] if p.exists()
)
arr = np.loadtxt(rtd_path, delimiter=",", skiprows=1)
strain, sig_steel, sig_al, _, _ = arr.T
fig, ax = plt.subplots(figsize=(7.2, 4.4))
ax.plot(strain * 1000, sig_steel, "o-", color="#0284c7", lw=2, markersize=5, label="AISI 1018 Steel (E=205 GPa, Sy=250 MPa)")
ax.plot(strain * 1000, sig_al, "s--", color="#059669", lw=2, markersize=5, label="Al 6061-T6 (E=69 GPa, Sy=275 MPa)")
ax.axhline(250.0, color="#0284c7", ls=":", alpha=0.7, label="Steel Yield Plateau (250 MPa)")
ax.annotate("Steel yields first (~1.22e-3)", xy=(1.22, 250), xytext=(1.35, 195),
arrowprops=dict(arrowstyle="->", color="#0f172a"), fontsize=9)
ax.set_title("Uniaxial Tensile Stress-Strain Response (Solids Lab Benchmark)")
ax.set_xlabel("Engineering Strain [$10^{-3}$ mm/mm]")
ax.set_ylabel("Axial Stress $\\sigma$ [MPa]")
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8.5, loc="lower right")
fig.tight_layout()
# Example 2 (ME 200 Thermodynamics + HMT): Vapor Dome & Quenching Transient Plot
sat_path = next(p for p in [Path("datasets/ME200_Saturated_Water_Temp_Table.csv"), Path("../datasets/ME200_Saturated_Water_Temp_Table.csv")] if p.exists())
sat = np.loadtxt(sat_path, delimiter=",", skiprows=1)
T_sat, P_bar, sf, sg = sat[:, 0], sat[:, 1], sat[:, 5], sat[:, 9]
fig, ax = plt.subplots(figsize=(7.2, 4.4))
ax.plot(sf, T_sat, "-", color="#0284c7", lw=2.3, label="Saturated Liquid Line $s_f(T)$")
ax.plot(sg, T_sat, "-", color="#dc2626", lw=2.3, label="Saturated Vapor Line $s_g(T)$")
# Shade the two-phase liquid-vapor dome cleanly
s_dome = np.concatenate([sf, sg[::-1]])
T_dome = np.concatenate([T_sat, T_sat[::-1]])
ax.fill(s_dome, T_dome, color="#e0f2fe", alpha=0.45, label="Two-Phase Mixture Region")
ax.plot(sg[-1], T_sat[-1], "ko", markersize=6)
ax.annotate(f"Critical Point ({T_sat[-1]:.1f} C, {P_bar[-1]:.1f} bar)", xy=(sg[-1], T_sat[-1]),
xytext=(sg[-1] + 0.5, T_sat[-1] - 25), arrowprops=dict(arrowstyle="->"), fontsize=9)
ax.set_title("Water T-s Saturation Vapor Dome (Directly from ME 200 Steam Table)")
ax.set_xlabel("Specific Entropy $s$ [kJ/(kg$\\cdot$K)]")
ax.set_ylabel("Temperature $T$ [$^\\circ$C]")
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8.5, loc="lower center")
fig.tight_layout()
Practice Questions (Concept Check)
- Why do experienced engineers use
fig, ax = plt.subplots()instead of standaloneplt.title()andplt.plot()calls? - What does
"s--"mean insideax.plot(x, y, "s--")? - Why did we shade the steam dome using
np.concatenate([sf, sg[::-1]])? - Which Matplotlib call prevents clipped axis labels before exporting
a PNG with
fig.savefig("chart.png", dpi=300)?
Guided
Practice Problem 1 (Worked Self-Check): Transient Steel Quenching
Cooling Curve (Heat Transfer)
Load datasets/HMT_Steel_Quenching_Transient_Data.csv,
extract Time_s (col 0), T_Centerline_x0_degC
(col 2), T_Surface_xL_degC (col 4), and
T_Lumped_Invalid_degC (col 6). Plot all three curves
vs.ย time in seconds, showing why ignoring internal conduction
(Bi = 0.85) severely overestimates cooling speed at the
core!
Hint: Use distinct markers/linestyles and put a grid + legend on ax
Notice col 6 (T_Lumped_Invalid_degC) sits
consistently colder than col 2
(T_Centerline_x0_degC)!
# Worked Practice Problem 1 Solution: Steel Quenching Thermal Lag Plot
q_path = next(p for p in [Path("datasets/HMT_Steel_Quenching_Transient_Data.csv"), Path("../datasets/HMT_Steel_Quenching_Transient_Data.csv")] if p.exists())
qd = np.loadtxt(q_path, delimiter=",", skiprows=1)
t_s, T_core, T_surf, T_lump = qd[:, 0], qd[:, 2], qd[:, 4], qd[:, 6]
fig, ax = plt.subplots(figsize=(7.2, 4.3))
ax.plot(t_s, T_core, "o-", color="#dc2626", lw=2, label="True Core ($x=0$, Spatial)")
ax.plot(t_s, T_surf, "s-", color="#0284c7", lw=2, label="True Surface ($x=L$)")
ax.plot(t_s, T_lump, "^--", color="#64748b", lw=1.8, label="Invalid Lumped Approx (Ignores Core Lag)")
ax.set_title("Oil Quenching Core-to-Surface Lag ($Bi > 0.1$, HMT Dataset)")
ax.set_xlabel("Quench Elapsed Time $t$ [s]")
ax.set_ylabel("Temperature $T$ [$^\\circ$C]")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
End-of-Chapter Practice Problems (Try Yourself!)
- Semi-Log Colebrook Friction Chart
(
Fluids): Loaddatasets/Fluids_Moody_Friction_Dataset.csvand plot Darcy \(f\) on a log-log axes (ax.loglog()) vs.ย \(Re_D\) for smooth pipe, \(\varepsilon/D = 0.0005\), and \(\varepsilon/D = 0.005\). - PT100 Sensor Calibration Scatter vs.ย Linear Fit
(
Calculus I): Scatter-plotRTD_Temp_Cvs.ยPT100_Resistance_OhmfromSolids_Tensile_Stress_Strain_RTD_Data.csvand overlay \(R_{\text{lin}} = 100(1 + 0.00385 T)\). - Ideal Gas Isobars (\(P = 1, 5, 10\text{ bar}\)): Plot density \(\rho(T)\) for dry air from \(250\text{ K}\) to \(900\text{ K}\) across three pressures on one clean figure.