ICON Training - Hands-on Session - Basic plot script using Matplotlib and Cartopy#
This is a Python 3 Jupyter notebook. We start by loading the necessary modules.
import getpass
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import cartopy.feature as cf
import matplotlib as mpl
import matplotlib.pyplot as plt
Define the directory and filenames.
user = getpass.getuser()
EXPDIR = f"/scratch/{user[0]}/{user}/exercise_realdata/"
# file names
filename = f"{EXPDIR}/NWP_DOM01_ML_0001.nc"
filename_ll = f"{EXPDIR}/NWP_lonlat_DOM01_ML_0001.nc"
#select the timestep to be plotted
timestep = 8
Open the unstructured datafile and preload coordinate arrays. We use the xarray package for this purpose.
ds = xr.open_dataset(filename)
cx = np.rad2deg(ds["clon"])
cy = np.rad2deg(ds["clat"])
Then open the regular (lat/lon) datafile and preload coordinate arrays:
ds_ll = xr.open_dataset(filename_ll)
lon = ds_ll["t_2m"].lon
lat = ds_ll["t_2m"].lat
We use this plot script to demonstrate the creation of a custom discrete color bar:
cmap = mpl.colors.ListedColormap(["navy", "crimson", "limegreen", "gold"])
norm = mpl.colors.BoundaryNorm(np.linspace(10, 30, cmap.N+1), cmap.N)
cmap.set_under('w')
cmap.set_over('w')
Create a panel containing multiple subplots and fill each subplot with content.
The Python packages matplotlib and cartopy make this straightforward.
crs = ccrs.PlateCarree()
fig, ax = plt.subplots(2, 2, subplot_kw={"projection":crs})
def axis_settings(ax, title):
gl = ax.gridlines(crs=crs, draw_labels=True,
linewidth=.6, color='gray', alpha=0.5, linestyle='-.')
ax.add_feature(cf.COASTLINE.with_scale("50m"), lw=0.5)
ax.add_feature(cf.BORDERS.with_scale("50m"), lw=0.3)
ax.set_title(title)
axis_settings(ax[0,0], "T_2M [K], triangular grid")
filled_c0 = ax[0,0].tricontourf(cx, cy, ds["t_2m"][timestep,0,:], transform=crs)
fig.colorbar(filled_c0, orientation='horizontal', ax=ax[0,0])
axis_settings(ax[1,0], "T_2M [K], lonlat grid")
filled_c1 = ax[1,0].contourf(lon,lat,ds_ll["t_2m"][timestep,0,:,:],transform=crs)
fig.colorbar(filled_c1, orientation='horizontal', ax=ax[1,0])
axis_settings(ax[0,1], "TQV [kg/m2], triangular grid")
filled_c2 = ax[0,1].tricontourf(cx, cy, ds["tqv"][timestep,:], transform=crs)
fig.colorbar(filled_c2, orientation='horizontal', ax=ax[0,1])
axis_settings(ax[1,1], "GUST_10M [m/s], triangular grid")
filled_c3 = ax[1,1].tricontourf(cx, cy, ds["gust10"][timestep,0,:], transform=crs, cmap=cmap, norm=norm, extend='both')
fig.colorbar(filled_c3, orientation='horizontal', ax=ax[1,1])
plt.show()
plt.rcParams["figure.figsize"] = (30,24)
Author info: Deutscher Wetterdienst (DWD) 2025 :: icon@dwd.de. For a full list of contributors, see CONTRIBUTING in the root directory. License info: see LICENSE file.