ICON Training - Hands-on Session - Basic plot script using Matplotlib and Cartopy

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
import matplotlib as mpl
import matplotlib.pyplot as plt

Define the directory and filenames.

user   = getpass.getuser()
EXPDIR = f"/scratch/{user[0]}/{user}/exercise_lam/"

# file name
filename_ll = f"{EXPDIR}/ilfff01000000ML.nc"

# output file
output_filename1 = "./TQV_regular.png"
output_filename2 = "./TQC_regular.png"

# colorbar and label
plot_color    = "gist_rainbow"
plot_label    = "kg m-2"

#select the timestep to be plotted (note that we have only 1 timestep per file)
timestep = 0

Then open the regular (lat/lon) datafile and preload coordinate arrays:

ds_ll = xr.open_dataset(filename_ll)
lon   = ds_ll["tqv_dia"].lon
lat   = ds_ll["tqv_dia"].lat

Create 2 plots. One for tqv and one for tqc

# process tqv_dia
#
fig1 = plt.figure(figsize=(9, 9))
tqv = ds_ll["tqv_dia"][timestep,:,:]

plot_min = np.round(np.amin(tqv))
plot_max = np.round(np.amax(tqv))

ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.BORDERS,edgecolor='gray')
ax.contourf(lon, lat, tqv, 60, cmap = plot_color, transform = cartopy.crs.PlateCarree())
ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
plt.colorbar(plt.cm.ScalarMappable(cmap=plot_color,norm=plt.Normalize(plot_min,plot_max)),ax=ax, orientation='horizontal', label=plot_label)

plt.show()

# process tqc_dia
#
fig2 = plt.figure(figsize=(9, 9))

tqc           = ds_ll["tqc_dia"][timestep,:,:]

plot_min = np.round(np.amin(tqc))
plot_max = np.round(np.amax(tqc))

ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.BORDERS,edgecolor='gray')
ax.contourf(lon, lat, tqc, 60, cmap = plot_color, transform = cartopy.crs.PlateCarree())
ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
plt.colorbar(plt.cm.ScalarMappable(cmap=plot_color,norm=plt.Normalize(plot_min,plot_max)),ax=ax, orientation='horizontal', label=plot_label)

plt.show()

fig1.savefig(output_filename1, dpi=200)
fig2.savefig(output_filename2, dpi=200)

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.