Stream: python-questions

Topic: Plotting CAM SE


view this post on Zulip Fred Castruccio (Sep 03 2021 at 15:50):

Hi, I saw several questions about plotting CAM SE. I wrote this small function to facilitate plotting the CAM SE grid with matplotlib and cartopy. It's far from perfect and doesn't work with all the projection but it's a start...

def camse_shift_cnt_lon(ds, central_longitude=0, eps=1e-3):
    dso = ds.copy()
    # cnt_lon-180 < lon < cnt_lon+180
    dso.lon.data = np.where(dso.lon > 180.0, dso.lon - 360.0, dso.lon)
    if central_longitude < 0:
        dso.lon.data = np.where(dso.lon > central_longitude+180.0, dso.lon - 360.0, dso.lon)
    elif central_longitude > 0:
        dso.lon.data = np.where(dso.lon < central_longitude-180.0, dso.lon + 360.0, dso.lon)
    dso = dso.sortby(dso.lon)
    # periodicity
    ds1 = dso.where(dso.lon < central_longitude-180+eps).dropna(dim='ncol')
    ds2 = dso.where(dso.lon > central_longitude+180-eps).dropna(dim='ncol')
    ds1.lon.data[:] = central_longitude+180
    ds2.lon.data[:] = central_longitude-180
    # Concatenate
    dso = xr.concat([ds2, dso, ds1], dim='ncol')

    return dso

And here is an example of how I used it

import xarray as xr
import numpy as np
import cartopy.crs as ccrs
import matplotlib as mpl
import matplotlib.pyplot as plt

scrdir = '/glade/work/fredc/'
ds = xr.open_dataset(scrdir+'TREFHT_CAMne120.nc').isel(time=0)

cmap = plt.cm.viridis
clevs = np.arange(0,15,1)*10+200

cnt_lon=0
ds1 = camse_shift_cnt_lon(ds, central_longitude=cnt_lon)
fig1 = plt.figure(dpi=300)
ax1 = plt.axes(projection=ccrs.PlateCarree(central_longitude=cnt_lon))
cf1 = ax1.tricontourf(ds1.lon, ds1.lat, ds1.TREFHT,
                     cmap=cmap,
                     norm=mpl.colors.BoundaryNorm(clevs, ncolors=cmap.N),
                     transform=ccrs.PlateCarree()
                     )
ax1.coastlines()
ax1.set_global()
plt.colorbar(cf1, shrink=0.6)

TREFHT_ne120.png

view this post on Zulip Fred Castruccio (Sep 03 2021 at 16:08):

With the figure this time...

TREFHT_ne120.png


Last updated: Jan 30 2022 at 12:01 UTC