Plotting basics#

Background#

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.

This activity provides examples for making basic plots of CLM simulations run on regular grids (f09 and f19 resolution) and was developed primarily by Will Wieder.


Global Visualizations#

These are examples of typical variables and plots that we look at in land model diagnostics. You can see examples of land model output from CESM3 development runs here. These plots were generated by the python-based land diagnostic framework (LDF), which was shamelessly built on work from the atmosphere diagnostics framework (ADF). You can also see the sample plots from the older, ncl-based land model diagnostics package here. More information on CUPiD: CESM Unified Postprocessing and Diagnostics is here: CUPID.

Notebook Objectives#

  1. Become familiar with Jupyter Notebooks

  2. Begin getting acquainted with python packages and their utilities

  3. Plot a map and timeseries of global results


History files from CLM are saved in netcdf format (denoted with the .nc file extension), a file format commonly used for storing large, multi-dimensional scientific variables. Netcdf files are platform independent and self-describing; each file includes metadata that describes the data, including: variables, dimensions, and attributes.


We’ll start by loading some packages

The first step is to import the libraries needed to plot the data. Here we will use xarray as a tool to read the netCDF file and plot results with matplotlib and cartopy.

# python packages
import os,sys
from glob import glob
from os.path import join
import numpy as np
import pandas as pd
import xarray as xr
from netCDF4 import num2date

# some resources for plotting
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature

# And to avoid annoying warnings
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline

NOTE: This example largely uses features of xarray and matplotlib packages. We won’t go into the basics of python or features included in these packages, but there are lots of resources to help get you started. Some of these are listed below.


1. Reading and formatting data#

Note: We’ll be using archived data from a longer simulation from your first i1850_sp.basics simulation for plotting for this section

1.1 Point to the data#

The first step is to grab land (CTSM) history files from a provided CESM model run

For this example we will use:

  • reflected solar radiation (FSR),

  • incident solar radiation (FSDS), and

  • exposed leaf area index (ELAI)

# TODO, point to the archived data from day 1 examples
# Here we point to the archive directory from a longer I1850 simulation
run_name = "i1850_sp.basics" # Name of CESM run
monthly_output_path = "/glade/campaign/cgd/tss/tutorials/clm_2026/basic_plotting/"+run_name+"/lnd/hist/"

# Create path to all files, including unix wild card for all dates
files = [] 
files.extend(sorted(glob(join(monthly_output_path+run_name+ ".clm2.h0a.*"))))

# List of variables to read into our dataset
load_vars = ['FSDS', 'FSR', 'ELAI', 'landfrac', 'area']

# Define preprocess function to only keep specific variables
def preprocess_vars(ds):
    return ds[load_vars]

# Finally use the xarray open_mfdataset function to open our data
# File IO can be a little slow, but we're only reading in 5 years of data
ds = xr.open_mfdataset(files, preprocess=preprocess_vars)

NOTE: These are the raw history files that CTSM writes out.

By default, they include grid cell averaged monthly means for different state and flux variables (h0a).

TIP: If you want to look at other variables, the fields variable in the cell below is where you can modify what we're reading off of the CLM history files.

Printing information about the dataset is helpful for understanding your data.#

  • What dimensions do your data have?

  • What are the coordinate variables?

  • What variables are we looking at?

  • Is there other helpful information, or are there attributes in the dataset we should be aware of?

# Print information about the dataset
ds

You can also print information about the variables in your dataset. The example below prints information about one of the data variables we read in. You can modify this cell to look at some of the other variables in the dataset.

What are the units, long name, and dimensions of your data?

ds.FSDS

1.2 Simple Calculations#

To begin with we’ll look at albedo that’s simulated by the model.

Albedo can be calculated in several different ways, but the calculations use solar radiation terms that are handled within CTSM.

Here we’ll look at ‘all sky albedo’, which is the ratio of reflected to incoming solar radiation (FSR/FSDS). Other interesting variables might include latent heat flux or gross primary productivity.

We will add this as a new variable in the dataset and add appropriate metadata.

When doing calculations, it is important to avoid dividing by zero. Use the .where function for this purpose

ds['ASA'] = ds.FSR/ds.FSDS.where(ds.FSDS>0)
ds['ASA'].attrs['units'] = 'unitless'
ds['ASA'].attrs['long_name'] = 'All sky albedo'
ds['ASA']

2. Plotting#

2.1 Easy plots using Xarray#

To get a first look at the data, we can plot a month of data from the simulation, selecting the month using the .isel function.

  • We will plot exposed leaf area index (variable = ELAI). Note that we select the variable by specifying our dataset, ds, and the variable.

  • We also have to deal with time somehow, here we’ll just plot the max value

More plotting examples are on the Xarray web site

# For LAI plots we'll make 'dead' grids really stand out
cmap = plt.cm.viridis_r
cmap.set_under(color='deeppink')
cmap = cmap.resampled(7)
levels = [0.1, 1, 2, 3, 4, 5, 6, 7]

p = ds.ELAI.max('time').plot(
    cmap = cmap,
    vmin=levels[0],vmax=levels[-1],
    subplot_kws=dict(projection=ccrs.Robinson()),
    transform=ccrs.PlateCarree(),
    figsize=(7,3)
)
p.axes.set_global()
p.axes.coastlines() 
p.axes.set_title(run_name + ' max LAI');
Click here for figure

plot example

Figure: maximum monthly exposed leaf area index (ELAI)


2.2 Calculating differences#

We can calculate the differences between the maximum and minimum of the simulation to see how much all sky albedo (ASA) changes throughout the year.

Below we’ll plot the max, min, and difference plots

cmap = plt.cm.viridis
cmap = cmap.resampled(10)
levels = [0, 0.1, 0.2, 0.3, 0.4, 0.5,
          0.6, 0.7, 0.8, 0.9, 1]
titles = ['Max Albedo', 'Min Albedo', 'Max-min difference']

# Calculate the three fields we want to plot
plot_data = [ds.ASA.max('time'),
             ds.ASA.min('time'),
             ds.ASA.max('time') - ds.ASA.min('time')]

fig, axs = plt.subplots(nrows=1, ncols=3,
                        subplot_kw=dict(projection=ccrs.Robinson()),
                        figsize=(15,4), constrained_layout=True)

for i in range(3):
    # add_colorbar=False so we can make one shared colorbar below
    im = plot_data[i].plot(ax=axs[i], transform=ccrs.PlateCarree(),
                           cmap=cmap, vmin=levels[0], vmax=levels[-1],
                           add_colorbar=False)
    axs[i].set_extent([-180, 180, -65, 88], ccrs.PlateCarree())
    axs[i].gridlines()
    axs[i].coastlines()
    axs[i].set_title(titles[i])

# One colorbar shared by all three maps
cbar = fig.colorbar(im, ax=axs, orientation='horizontal',
                    shrink=0.5, pad=0.04, ticks=levels)
cbar.set_label('All sky albedo (unitless)');

Questions:

  • How do you think albedo changes at different times of year?

  • What regions have the largest difference in their max and min albedos?

  • What’s causing these albedo changes in different regions?

Click here for figure

plot example

Figure: maximum, minimum and difference in monthly all sky albedo (ASA)


2.3 Calculating Time Series#

As above, the plotting function we use here requires data to be 1D or 2D. Therefore, to plot a time series we either need to average over an area or select a single point.

2.3.1 Global time series#

  1. Calculate weights:

  • land area la that is the product of land fraction (fraction of land area in each grid cell) and the total area of the grid cell (which changes by latitude). Units are the same as area.

  • land weights weights, the fractional weight that each grid makes to the global total, is calculated as the land area of each grid cell divided by the global sum of the land area.

  1. Use weights to calculate global sums

# Calculate land area and weights
ds['la'] = (ds.area * ds.landfrac).isel(time=0)
ds['la'] = ds['la'] * 1e6  #converts from land area from km2 to m2 
ds['la'].attrs['units'] = 'm^2'
ds['weights'] = ds['la']/(ds['la'].sum())

# Check that weights sum to 1
print("sum land weights")
print(ds['weights'].sum().values)

# quick plot of the land weights
p = ds['weights'].plot(
    cmap='viridis',
    subplot_kws=dict(projection=ccrs.Robinson()),
    transform=ccrs.PlateCarree(),
    figsize=(7,3)
)
p.axes.set_global()
p.axes.coastlines()
p.axes.set_title('Land Weights');

Look:

  • How does the grid cell area (and therefore the weight) change with latitude on this regular (FV) grid?

  • Why might grid cells near the coasts have smaller weights than inland grid cells?

Click here to see weights on the FV grid

Figure: Land weights on the FV grid

plot example

Next, calculate and plot a global weighted sum#

NOTE: You will likely want to calculate a global weighted sum for a variety of different variables. For variables that have area-based units (e.g. GPP, gC/m^2/s), you need to use the land area variable when calculating a global sum. Remember to pay attention to the units and apply any necessary conversions! Keep in mind that grid cell area is reported in km^2.

# Calculate global mean using weights
## make sure you pay attention to units!
plotVars = ['ELAI','ASA', 'FSDS','FSR']
global_mean = (ds[plotVars] * ds['weights']).sum(['lat','lon'])

plt.figure(figsize=(12,5))

for i in range(len(plotVars)):
    plt.subplot(2,2,(i+1))
    global_mean[plotVars[i]].plot() 
    if i == 0:
        plt.title('Global mean '+run_name) ;
Click here for the solution

plot example

Figure: Plotting solution for global mean timeseries.

2.3.2 Subset data for a point#

In this section we’ll:

  1. Define the point [longitude, latitude] in degrees

  2. Select the nearest grid cell to that point using .sel(..., method='nearest')

  3. Plot using xarray

NOTE: CTSM longitudes run from 0 to 360, so we convert western-hemisphere (negative) longitudes before selecting.

# 1. Define the point [longitude, latitude] in degrees
point_coord = [-105.27, 40.01]  # Boulder, CO example
point_lon = point_coord[0] % 360  # convert to 0-360 longitudes used by CTSM

plt.figure(figsize=(12,5))
plotVars = ['ELAI','ASA', 'FSDS','FSR']

# 2. Select the nearest grid cell
subset_ds = ds[plotVars].sel(lon=point_lon, lat=point_coord[1], method='nearest')

# 3. Plot
for i in range(len(plotVars)):
    plt.subplot(2,2,(i+1))
    subset_ds[plotVars[i]].plot() 
    if i == 0:
        plt.title(run_name+' subset for Boulder, CO') ;
    else:
        plt.title(None)

plt.tight_layout()
Click here for the solution

plot example

Figure: Plotting solution for single point.

2.4 Calculate an annual weighted mean and create customized plots#

Annual averages require a different kind of weighting: the number of days per month. This example creates python functions that allow you to easily calculate annual averages and create customized plots.

Python functions: In python, creating a function allows us to use the same calculation numerous times instead of writing the same code repeatedly.

2.4.1 Calculate monthly weights#

The below code creates a function weighted_annual_mean to calculate monthly weights. Use this function any time you want to calculate weighted annual means.

# create a function that will calculate an annual mean weighted by days per month
plotVars = ['ELAI','ASA']

def weighted_annual_mean(array):
    mon_day  = xr.DataArray(np.array([31,28,31,30,31,30,31,31,30,31,30,31]), dims=['month'])
    mon_wgt  = mon_day/mon_day.sum()
    return (array.rolling(time=12, center=False) # rolling
            .construct("month") # construct the array
            .isel(time=slice(11, None, 12)) # slice so that the first element is [1..12], second is [13..24]
            .dot(mon_wgt, dims=["month"]))

# generate annual means
for i in range(len(plotVars)):
    temp = weighted_annual_mean(
        ds[plotVars[i]].chunk({"time": 12}))
    
    if i ==0:
        dsAnn = temp.to_dataset(name=plotVars[i])
    else:
        dsAnn[plotVars[i]] = temp
# Make a simple plot for the first year of data
plot_year = 0
p = dsAnn.ELAI.isel(time=plot_year).plot(
    cmap='viridis',
    subplot_kws=dict(projection=ccrs.Robinson()),
    transform=ccrs.PlateCarree(),
    figsize=(7,3)
)
p.axes.set_global()
p.axes.coastlines()
p.axes.set_title(run_name + " mean annual LAI, year " +
                 str(dsAnn.time[plot_year].dt.year.values));
Click here for the solution

plot example

Figure: Plotting solution.

Extra credit challenge#

If you have extra time & energy, try running through this notebook with other variables. Interesting options could include:

  • Latent heat flux (the sum of FCTR+FCEV+FGEV) or

  • Gross Primary Production (GPP)

HINT: pay attention to units for these challenges.

Claude code#

If you have access to AI, consider trying AI to generate plots for you.

First cd to a directory with model output:

cd /glade/campaign/cgd/tss/tutorials/clm_2026/diagnostics/cases_claude

Here you may give Claude (or other AI) this prompt:

I would like a map of ELAI averaged from the last 20 years of the Hist simulation here; model output is under lnd/hist in the h0a files; can you generate that?

You may get a response like this one after about 5 minutes:

Files:
- Map: /glade/work/<user>/tmp/claude-<user-id>/<some long path>/scratchpad/ELAI_Hist_2004-2023.png
- The averaged field, as NetCDF: /glade/work/<user>/tmp/claude-<user-id>/<some long path>/scratchpad/ELAI_Hist_2004-2023.nc
- Script, if you want to rerun or tweak it: /glade/work/<user>/tmp/claude-<user-id>/<some long path>/scratchpad/elai_map.py

How it was averaged:
- Period: the run goes from 1850 to 2023, so the last 20 years are 2004–2023. That's the 240 monthly h0a files from 2004-01 through 2023-12.
- Date check: the time_bounds in these files show that each file's date is the month it averages (for example, 2023-12 covers Dec 1 to Jan 1). That means none of the months is shifted by one.
- Weighting: each month is weighted by its number of days, so it's a true time mean.
- Plot: Robinson projection, YlGn color scale from 0 to 10.

Results: the highest value is about 9.2 m²/m², in the Amazon, Congo and Maritime Continent rainforests. The average over land grid cells is about 1.15. That average doesn't account for differences in grid-cell area, so it isn't a true global mean.

I can add a land-area-weighted global mean, seasonal maps, or a comparison with the pSASU case if you want.

…and here we copied the file from the tmp/claude path to where the figure would be visible from this notebook, i.e. ~/CLM-Tutorial/images/diagnostics/clm_ctsm/.

plot example