Hillslope Hydrology#

This tutorial shows how to visualize hillslope history output from CLM.#

BEFORE BEGINNING THIS EXERCISE - Check that your kernel (upper right corner, above) is NPL2026a. This should be the default kernel, but if it is not, click on that button and select NPL2026a.

Background. In the hillslope configuration, each naturally vegetated gridcell is split into four hillslope aspects, i.e., North-, East-, South-, and West-facing slopes. Each hillslope aspect has several user-defined columns, ordered by elevation along the slope (e.g., column 1 is the lowland column next to the stream). Water flows laterally from higher to lower columns, so columns behave differently. A brief overview of hillslope postprocessing can be found here: Hillslope Postprocessing


What you will do

  1. Map the columns and aspects of the hillslopes (gridded output)

  2. Plot time series and profiles at a single point (vector output)

  3. Save all figures to a PDF

What you will learn

  1. How north- vs. south-facing hillslopes differ for different variables (i.e., the role of aspect)

  2. How position along the slope (the elevation-ordered columns) matters

  3. How hillslope output compares with the gridcell mean, and why the two differ

  4. How to follow soil moisture, snow, water table, etc. over time in each column at a single point

1. Setup#

import os
import glob
import warnings

import numpy as np
import netCDF4 as netcdf4
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.ticker import MaxNLocator
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

# Empty (ocean) gridcells give harmless "mean of empty slice" warnings - so ignore these warnings
warnings.filterwarnings('ignore', category=RuntimeWarning)

Options (select from one of the experiments below)#

# Data locations (hardcoded - do not change these)
base_dir = '/glade/campaign/cgd/tss/tutorials/clm_2026/hillslope/data/'

# experiment 1: uniform soil thickness for all columns
grid_dir = base_dir + 'western_US_gridded/'   # gridded output: one file per column and year
vec_dir  = base_dir + 'western_US_vector/'    # vector output: column-level (h1) and gridcell-mean (h0) files

# experiment 2: Deeper lowland soil thickness
#grid_dir = base_dir + 'western_US_gridded_deep_soil_lowland'   # gridded output: one file per column and year
#vec_dir  = base_dir + 'western_US_vector_deep_soil_lowland'    # vector output: column-level (h1) and gridcell-mean (h0) files

# Plot style
use_contour = True       # True: filled contours, False: raster (one box per gridcell)
#cmap = 'YlGnBu'          # colormap for mean fields (try 'viridis', 'terrain', ...)
cmap = 'terrain'          # colormap for mean fields (try 'viridis', 'terrain', ...)
diff_cmap = 'RdBu'       # colormap for differences

# Figure output
save_figures = True      # save each figure as png, and all figures to one pdf at the end
plot_dir = '~/hillslope_figures/'

# Aspects: hillslope index 1-4 in the model output
aspect_names = ['North', 'East', 'South', 'West']
aspect_colors = {'North': 'tab:blue', 'East': 'tab:green', 'South': 'tab:orange', 'West': 'tab:red'}

Helper functions#

def get_history_filenames(directory, htag, years=None):
    """Sorted list of CLM history files, e.g. *clm2.h1a.1990*.nc. years = (first, last)."""
    year_tags = range(years[0], years[1] + 1) if years else ['']
    files = sorted({f for y in year_tags
                    for f in glob.glob(os.path.join(directory, f'*clm2.{htag}.{y}*.nc'))})
    if not files:
        raise FileNotFoundError(f'no {htag} files found in {directory}')
    return files


def get_hillslope_dims(filename):
    """Number of hillslopes and number of columns per hillslope."""
    with netcdf4.Dataset(filename) as ds:
        nhillslope = len(ds.dimensions['nhillslope'])
        ncols = len(ds.dimensions['max_columns_hillslope']) // nhillslope
    return nhillslope, ncols


def read_field(filename, varname):
    """Read the first time slice of a variable; missing values become NaN."""
    with netcdf4.Dataset(filename) as ds:
        field = np.ma.filled(ds.variables[varname][0].astype(float), np.nan)
    field[field >= 1e30] = np.nan
    return field


def read_hillslope(files, varname, hillslope, ncols):
    """Read all columns of one hillslope (1-based index) from the gridded files.
    Returns an array [column, time, lat, lon]."""
    data = []
    for c in range(1, ncols + 1):
        tag = f'_h{hillslope:02d}_c{c:02d}'
        data.append([read_field(f, varname) for f in files if tag in f])
    return np.array(data)


def read_weights(ds, name):
    """Read column weights [hillslope, column, lat, lon]; missing values become 0."""
    w = np.ma.filled(ds.variables[name][:], 0.0).astype(float)
    w[w >= 1e30] = 0.0
    return w
# Map plotting

PLATE = ccrs.PlateCarree()

def make_map_axes(nrow, ncol, figsize):
    """Figure with nrow x ncol map panels (needs lonw, lat and extent, defined below)."""
    fig, axes = plt.subplots(nrow, ncol, figsize=figsize, constrained_layout=True,
                             subplot_kw={'projection': PLATE})
    axes = np.atleast_1d(axes).ravel()
    xticks = np.arange(np.ceil(lonw.min() / 10) * 10, lonw.max(), 10)
    yticks = np.arange(np.ceil(lat.min() / 10) * 10, lat.max(), 10)
    for i, ax in enumerate(axes):
        ax.set_extent(extent, PLATE)
        ax.add_feature(cfeature.OCEAN, facecolor='lightgray', zorder=1.5)  # hide data over ocean
        ax.coastlines(linewidth=0.5, zorder=2)
        ax.set_xticks(xticks, crs=PLATE)
        ax.set_yticks(yticks, crs=PLATE)
        ax.xaxis.set_major_formatter(LongitudeFormatter())
        ax.yaxis.set_major_formatter(LatitudeFormatter())
        # only label the outer panels
        ax.tick_params(labelsize=8, labelbottom=(i // ncol == nrow - 1), labelleft=(i % ncol == 0))
    return fig, axes


def draw_maps(fig, axes, fields, titles, vmin, vmax, cmap, label):
    """Draw one field per axes with a shared horizontal colorbar below them."""
    levels = np.linspace(vmin, vmax, 21)
    for ax, field, title in zip(axes, fields, titles):
        if use_contour:
            img = ax.contourf(lonw, lat, field, levels=levels, cmap=cmap, extend='both', transform=PLATE)
        else:
            img = ax.pcolormesh(lonw, lat, field, vmin=vmin, vmax=vmax, cmap=cmap,
                                shading='nearest', transform=PLATE)
        ax.set_title(title, fontsize=10)
    cbar = fig.colorbar(img, ax=list(axes), orientation='horizontal', extend='both',
                        shrink=0.8, aspect=40, pad=0.04, label=label)
    cbar.ax.xaxis.set_major_locator(MaxNLocator(5))


def plot_map_grid(fields, titles, suptitle, label, vmin, vmax, cmap, ncol=2, figsize=(7, 5.5)):
    """Grid of maps sharing one colorbar."""
    nrow = int(np.ceil(len(fields) / ncol))
    fig, axes = make_map_axes(nrow, ncol, figsize)
    draw_maps(fig, axes, fields, titles, vmin, vmax, cmap, label)
    fig.suptitle(suptitle, fontsize=13)
    return fig


# ---- colour ranges ----
fixed_range = {'H2OSNO': (0, 160), 'ZWT': (0, 8)}   # (vmin, vmax); other variables use percenitles

def color_range(varname, field):
    if varname in fixed_range:
        return fixed_range[varname]
    vmin, vmax = np.nanpercentile(field, [5, 95])
    if vmax <= vmin:                       # e.g. a mostly-zero field
        vmax = max(np.nanmax(field), vmin + 1e-6)
    return vmin, vmax

def diverging_limit(diff):
    """Symmetric limit for difference maps (95th percentile, so outliers don't dominate)."""
    return max(np.nanpercentile(np.abs(diff), 95), 1e-6)

def merge_colormaps(cname1,cname2):
    from matplotlib.colors import ListedColormap
    N = 256
    bottom = plt.get_cmap(cname1, N)
    top = plt.get_cmap(cname2, N)
    newcolors = np.vstack((bottom(np.linspace(0, 0.5, int(N//2))),
        top(np.linspace(0.5, 1.0, int(N//2)))))

    newcmap = ListedColormap(newcolors)
    return newcmap

# ---- saving ----
figures = {}

# Make the figures directory if it's not already there
plot_dir = os.path.realpath(os.path.expanduser(plot_dir))
if not os.path.isdir(plot_dir):
    print ("figures directory does not exist... creating it now!")
    os.makedirs(plot_dir, exist_ok=True)
else:
    print("figures directory already exists")
    
def save_fig(fig, name):
    """Save a figure as png and remember it for the pdf at the end."""
    if save_figures:
        fig.savefig(f'{plot_dir}/hillslope_{name}.png', dpi=150, bbox_inches='tight')
        figures[name] = fig

2. Maps of hillslope columns (gridded output)#

Find files and set up the map grid#

yr1, yr2 = 1990, 1992             # Data available from 1980 - 2019; feel free to chose any period

grid_h1_files = get_history_filenames(grid_dir, 'h1a', (yr1, yr2))   # column-level, gridded
vec_h0_files  = get_history_filenames(vec_dir,  'h0a', (yr1, yr2))   # gridcell mean

nhillslope, ncols = get_hillslope_dims(grid_h1_files[0])

# Grid coordinates (convert longitude from 0-360 to -180-180 for plotting)
with netcdf4.Dataset(grid_h1_files[0]) as ds:
    lon = np.asarray(ds.variables['lon'][:])
    lat = np.asarray(ds.variables['lat'][:])
lonw = np.where(lon > 180, lon - 360, lon)

# Map extent, padded by half a gridcell
dlon, dlat = abs(lon[1] - lon[0]), abs(lat[1] - lat[0])
extent = [lonw.min() - dlon / 2, lonw.max() + dlon / 2, lat.min() - dlat / 2, lat.max() + dlat / 2]

print(f'{nhillslope} hillslopes x {ncols} columns, {len(grid_h1_files) // (nhillslope * ncols)} files per column')

Select a variable#

# Choose a variable (uncomment one)

varname, units = 'H2OSNO', 'mm'          # snow water equivalent
# varname, units = 'ZWT', 'm'            # water table depth
# varname, units = 'QSOIL', 'mm/s'       # ground evaporation
# varname, units = 'FH2OSFC', ''         # fraction of surface water
# varname, units = 'hillslope_area', 'm2'

convert_units = False   # True will convert mm/s fluxes to mm/month

# all_cols has dimensions [hillslope, column, time, lat, lon]
all_cols = np.array([read_hillslope(grid_h1_files, varname, h + 1, ncols) for h in range(nhillslope)])

if convert_units and units == 'mm/s':
    all_cols *= 30 * 24 * 3600
    units = 'mm/month'
print(all_cols.shape)       # [hillslope, column, time, lat, lon]

Time-mean map of each column in one hillslope aspect#

aspect = 'North'                         # 'North', 'East', 'South' or 'West' - feel free to change
h = aspect_names.index(aspect)

mean_cols = np.nanmean(all_cols[h], axis=1)          # average over time -> [column, lat, lon]
vmin, vmax = color_range(varname, mean_cols)

fig = plot_map_grid(mean_cols, [f'Column {c + 1}' for c in range(ncols)],
                    f'Mean {varname}: {aspect} hillslope', units, vmin, vmax, cmap)
save_fig(fig, 'columns')
What attribute (geomorphic parameter) could explain the different snowpack magnitudes?
Answer

Elevation.

The columns are ordered by elevation (column 1 is the lowest, the last column the highest). Higher columns have colder temperatures because temperature is downscaled with elevation.

Difference between different columns / elevations#

# This is plotting the difference from the lowland column (i.e., Column 1)

diffs = mean_cols[1:] - mean_cols[0]                 # columns 2..N minus column 1
lim = diverging_limit(diffs)

fig = plot_map_grid(diffs, [f'Column {c + 2} - Column 1' for c in range(ncols - 1)],
                    f'Difference in mean {varname}: {aspect} hillslope', units,
                    -lim, lim, diff_cmap, ncol=ncols - 1, figsize=(10, 3.6))
save_fig(fig, 'column_differences')
Why do columns 2-4 have smaller snowpack magnitudes than column 1 (the lowland column) in some locations?
Answer

Surface water.

Subsurface lateral flow causes higher soil moisture in the lowland column, which may result in surface water. As surface water freezes in autumn, it is converted to ice and incorporated into the snowpack.

Note: the hillslope columns may have different areas. In particular, the lowland column in mountainous areas may be quite small relative to the upland columns. Thus, the differences may be somewhat misleading because they do not account for potential area differences.

Look at the surface water directly#

# Same plot for a second variable (the hillslope aspect chosen above is reused)

varname2, units2 = 'H2OSFC', 'mm'

cols2 = read_hillslope(grid_h1_files, varname2, h + 1, ncols)
mean_cols2 = np.nanmean(cols2, axis=1)
vmin, vmax = color_range(varname2, mean_cols2)

fig = plot_map_grid(mean_cols2, [f'Column {c + 1}' for c in range(ncols)],
                    f'Mean {varname2}: {aspect} hillslope', units2, vmin, vmax, cmap='ocean_r')
save_fig(fig, 'surface_water')

Compare hillslopes (aspects)#

# Column weights: the fraction of the natural vegetation landunit / of the gridcell covered by each column

with netcdf4.Dataset(grid_dir + '/hillslope_western_US_hillslope_geometry.nc') as ds:
    wt_lunit = read_weights(ds, 'cols1d_wtlunit')[:nhillslope, :ncols]
    wt_gcell = read_weights(ds, 'cols1d_wtgcell')[:nhillslope, :ncols]

# Area-weighted mean over the columns of each hillslope -> [hillslope, time, lat, lon]
data = np.nan_to_num(all_cols)
hillslope_mean = np.sum(wt_lunit[:, :, None] * data, axis=1) / wt_lunit.sum(axis=1)[:, None]
mean_aspects = np.nanmean(hillslope_mean, axis=1)    # average over time

vmin, vmax = color_range(varname, mean_aspects)
fig = plot_map_grid(mean_aspects, aspect_names, f'Mean {varname}: hillslope averages',
                    units, vmin, vmax, cmap)
save_fig(fig, 'aspects')
What attribute (geomorphic parameter) could explain the different snowpack magnitudes?
Answer

Aspect.

Each hillslope corresponds to a different aspect. In the northern hemisphere, north-facing hillslopes receive less insolation, while south-facing hillslopes absorb the most solar radiation.

Hillslope columns vs. gridcell mean#

# Gridcell mean from the hillslope columns (weights are fractions of the gridcell)
grc_from_columns = np.sum(wt_gcell[:, :, None] * data, axis=(0, 1))          # [time, lat, lon]
grc_from_columns = np.where(wt_gcell.sum(axis=(0, 1)) > 0, grc_from_columns, np.nan)
grc_from_columns = grc_from_columns.mean(axis=0)

# Gridcell mean written directly by the model (h0a files)
grc_h0 = np.nanmean([read_field(f, varname) for f in vec_h0_files], axis=0)
diff = grc_h0 - grc_from_columns

vmin, vmax = color_range(varname, grc_h0)
lim = diverging_limit(diff)

fig, axes = make_map_axes(1, 3, (11, 3.8))
draw_maps(fig, axes[:2], [grc_from_columns, grc_h0], ['Sum of hillslope columns', 'Gridcell mean (h0a)'],
          vmin, vmax, cmap, units)
draw_maps(fig, axes[2:], [diff], ['Difference (h0a - columns)'], -lim, lim, diff_cmap, units)
fig.suptitle(f'Mean {varname}: hillslope columns vs. gridcell mean', fontsize=13)
save_fig(fig, 'gridcell_mean')
Why doesn't the weighted average of all the hillslope columns match the gridcell average?
Answer

Hillslopes are only active on the naturally vegetated landunit.

The gridcell average may include other landunits, such as crop, lake, glacier, or urban. Here, the presence of crop and lake landunits explains most of the differences.

3. Time series and profiles at a point (vector output)#

Read data at one gridcell#

yr1, yr2 = 1981, 1984               # Feel free to chose between 1980 - 2019
#yr1, yr2 = 2000, 2003

h0_files = get_history_filenames(vec_dir, 'h0a', (yr1, yr2))   # gridcell mean (gridded)
h1_files = get_history_filenames(vec_dir, 'h1a', (yr1, yr2))   # column level (vector)
nhillslope, ncols = get_hillslope_dims(h1_files[0])

# Choose a point (longitude is 0-360); the nearest gridcell is used
points = {1: (245, 46), 2: (250, 46), 3: (250, 35), 4: (265,32)}
ptnum = 1
plon, plat = points[ptnum]

# Select an aspect to show in the profile plot
aspect = 'North'
aspect_index = aspect_names.index(aspect) + 1

# Soil moisture as saturation (0-1) or as volumetric water content (m3/m3)
show_saturation = True

# ---- grid and time (from the gridcell-mean files) ----
ds = netcdf4.MFDataset(h0_files)
lon = np.asarray(ds.variables['lon'][:])
lat = np.asarray(ds.variables['lat'][:])
ref_year = int(ds.variables['time'].units.split()[2].split('-')[0])
ytime = np.asarray(ds.variables['time'][:]) / 365 + ref_year      # time in decimal years
ds.close()

pt_i, pt_j = np.argmin(np.abs(plon - lon)), np.argmin(np.abs(plat - lat))
slon, slat = lon[pt_i], lat[pt_j]
slon_w = (slon + 180) % 360 - 180
point_label = f'{abs(slat):.1f}N, {abs(slon_w):.1f}W'

# ---- soil structure at the point ----
static_file = get_history_filenames(vec_dir, 'h0a')[0]
with netcdf4.Dataset(static_file) as ds:
    nlevsoi = len(ds.dimensions['levsoi'])
    zsoi   = np.asarray(ds.variables['ZSOI'][:nlevsoi, pt_j, pt_i])     # layer depth
    dzsoi  = np.asarray(ds.variables['DZSOI'][:nlevsoi, pt_j, pt_i])    # layer thickness
    watsat = np.asarray(ds.variables['WATSAT'][:nlevsoi, pt_j, pt_i])   # saturated water content
zisoi = zsoi + 0.5 * dzsoi                                              # depth of layer bottoms


# ---- find the columns at this point ----
def columns_at_point(filename, lon0, lat0, tol=1e-5):
    with netcdf4.Dataset(filename) as ds:
        col_lon = np.ma.filled(ds.variables['cols1d_lon'][:], np.nan)
        col_lat = np.ma.filled(ds.variables['cols1d_lat'][:], np.nan)
        hill_idx = np.ma.filled(ds.variables['hillslope_index'][:], 0)
    at_point = (np.abs(col_lon - lon0) < tol) & (np.abs(col_lat - lat0) < tol) & (hill_idx > 0)
    return at_point, hill_idx


def read_columns(files, names, cols):
    """Read variables (time series) for the selected columns"""
    ds = netcdf4.MFDataset(files)
    out = {n: np.ma.filled(ds.variables[n][..., cols].astype(float), np.nan) for n in names}
    ds.close()
    return out


at_point, hill_idx = columns_at_point(h1_files[0], slon, slat)
cols = at_point & (hill_idx == aspect_index)       # columns of the chosen aspect

with netcdf4.Dataset(h1_files[0]) as ds:
    hillslope_elev = np.ma.filled(ds.variables['hillslope_elev'][:], np.nan)
    hillslope_dist = np.ma.filled(ds.variables['hillslope_distance'][:], np.nan)
    nbedrock = np.ma.filled(ds.variables['cols1d_nbedrock'][:], 0).astype(int)
zbedrock = zisoi[nbedrock[cols]-1]    # depth of bedrock in each colunm

# ---- time series for these columns ----
# (add other column-level variables here, e.g. 'QLATFLOWOUT' or 'QDRAI')
names = ['ZWT', 'FROST_TABLE', 'FH2OSFC', 'H2OSFC', 'FSNO', 'H2OSNO', 'SOILLIQ', 'SOILICE']
ts = read_columns(h1_files, names, cols)

# Soil moisture [time, level, column]: liquid + ice, as a fraction of the layer volume (or of saturation)
sm = (ts['SOILLIQ'] + ts['SOILICE'])[:, :nlevsoi, :]
denominator = 1e3 * dzsoi[None, :, None]
if show_saturation:
    denominator = denominator * watsat[None, :, None]
sm = sm / denominator
sm_label = 'Saturation' if show_saturation else 'Volumetric water content (m$^3$/m$^3$)'

Soil moisture profiles in each column#

fig, axes = plt.subplots(ncols, 2, figsize=(12, 2 * ncols + 1.5), sharex=True, sharey='col',
                         constrained_layout=True, gridspec_kw={'width_ratios': [2, 1.4]})

levels = np.linspace(0.4, 1.0, 21) if show_saturation else np.linspace(0, 0.5, 21)
surface_max = np.nanmax([ts['H2OSNO'], ts['H2OSFC']])

cmap_profile = merge_colormaps('BrBG','RdBu')

for c in range(ncols):
    ax, ax2 = axes[c]

    # Left: soil moisture vs depth. Above zero depth: surface water and snow cover fractions.
    img = ax.contourf(ytime, zsoi, sm[:, :, c].T, levels=levels, cmap=cmap_profile, extend='both')
    ax.plot(ytime, ts['ZWT'][:, c], c='k', lw=1, label='Water table')
    ax.plot(ytime, ts['FROST_TABLE'][:, c], c='r', lw=1, ls='--', label='Frost table')
    ax.plot(ytime, -ts['FH2OSFC'][:, c], c='slategray', lw=1, label='Surface water fraction')
    ax.plot(ytime, -ts['FSNO'][:, c], c='turquoise', lw=1, label='Snow cover fraction')
    ax.set_title(f'Column {c + 1}  (elevation {hillslope_elev[cols][c]:.1f} m, '
                 f'{hillslope_dist[cols][c]:.0f} m from channel)', loc='left', fontsize=9)
    ax.set_ylabel('Depth (m)')

    # Right: surface water and snow
    ax2.plot(ytime, ts['H2OSFC'][:, c], c='tab:red', lw=1, label='H2OSFC (surface water)')
    ax2.plot(ytime, ts['H2OSNO'][:, c], c='tab:blue', lw=1, label='H2OSNO (snow)')
    ax2.set_ylabel('mm')

axes[0, 0].set_ylim(zbedrock.max(), -1)     # depth increases downward
axes[0, 1].set_ylim(0, surface_max)
axes[0, 0].legend(loc='lower left', fontsize=7, ncol=2)
axes[0, 1].legend(fontsize=7)
axes[-1, 0].set_xlabel('Year')
axes[-1, 1].set_xlabel('Year')

fig.colorbar(img, ax=axes[:, 0], orientation='horizontal', shrink=0.6, aspect=40, pad=0.03, label=sm_label)
fig.suptitle(f'{aspect} hillslope at {point_label}', fontsize=13)
save_fig(fig, 'soil_moisture_profiles')

Compare aspects at the same point#

snow = read_columns(h1_files, ['H2OSNO'], at_point)['H2OSNO']     # [time, all columns at the point]
hill_idx_pt = hill_idx[at_point]

fig, axes = plt.subplots(ncols, 1, figsize=(8, 1.8 * ncols + 1), sharex=True, sharey=True,
                         constrained_layout=True)
for h, name in enumerate(aspect_names):
    members = np.where(hill_idx_pt == h + 1)[0]          # columns of this hillslope, in order
    for c in range(ncols):
        axes[c].plot(ytime, snow[:, members[c]], c=aspect_colors[name], lw=1, label=name)

for c, ax in enumerate(axes):
    ax.set_title(f'Column {c + 1}', loc='left', fontsize=9)
    ax.set_ylabel('H2OSNO (mm)')
    ax.set_ylim(bottom=0)
axes[0].legend(ncol=4, fontsize=8)
axes[-1].set_xlabel('Year')
fig.suptitle(f'Snow water equivalent by aspect at {point_label}', fontsize=13)
save_fig(fig, 'aspect_comparison')
To what do the different colors correspond? Do the magnitudes match your physical intuition?
Answer

The colors indicate the aspect (azimuthal orientation) of each column.

In the northern hemisphere, north-facing columns receive the least sunlight and should hold the most snow, while south-facing columns should hold the least.

Hillslope profiles#

fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
for h, name in enumerate(aspect_names):
    members = at_point & (hill_idx == h + 1)
    ax.plot(hillslope_dist[members], hillslope_elev[members], marker='o', ms=4, lw=1,
            c=aspect_colors[name], label=name)

ax.set_xlabel('Distance from channel (m)')
ax.set_ylabel('Height above channel (m)')
ax.set_xlim(left=0)
ax.set_ylim(bottom=0)
ax.legend()
ax.set_title(f'Hillslope profiles at {point_label}')
save_fig(fig, 'hillslope_profiles')

4. Save figures to a single PDF#

if save_figures:
    pdf_filename = f'{plot_dir}/hillslope_figures.pdf'
    with PdfPages(pdf_filename) as pdf:
        for fig in figures.values():
            pdf.savefig(fig, bbox_inches='tight')
    print(f'{len(figures)} figures saved to {pdf_filename}')