Plotting netCDF data

NetCDF is one of the most widely used file formats in climate science. earthkit-plots reads netCDF files through earthkit-data and exposes the same plotting API as for GRIB or xarray sources — no format-specific code is needed.

[1]:
import earthkit.data as ekd

import earthkit.plots as ekp

Loading a netCDF file

ekd.from_source("sample", ...) fetches a small ERA5 sample file. The same call works for any local or remote netCDF path — just replace "sample" with "file" and provide the path.

[2]:
nc = ekd.from_source("sample", "era5-monthly-mean-2t-199312.nc")
nc
[2]:
NetCDF file

path/var/folders/vt/7j2c2tmx4m14gn_sg3zpf5l00000gn/T/tmpl1xoe9a0/url-0d91e43857fd5c6930d272d2375eb78bde0454b84e995565b359433049aa1605.nc
size2 MiB
typesxarray, pandas, fieldlist, numpy, array

Plotting directly from the earthkit-data object

earthkit-plots can consume the earthkit-data object directly. Units conversion and auto-styling work out of the box because the CF-convention metadata is read from the file automatically.

[3]:
chart = ekp.Map(domain="Europe")
chart.contourf(nc, units="celsius")
chart.legend()
chart.coastlines()
chart.title("{variable_name} – {time:%B %Y}")
chart.show()
../../../_images/examples_examples_source-types_source-netcdf_5_0.png

Automatic style selection

For well-known variables plot() chooses the method and style automatically — no need to decide between contourf, contour, etc.

[4]:
chart = ekp.Map(domain="Europe")
chart.plot(nc, units="celsius")
chart.legend()
chart.coastlines()
chart.title("{variable_name} – {time:%B %Y}")
chart.show()
../../../_images/examples_examples_source-types_source-netcdf_7_0.png

Format agnosticism

The plotting code above is essentially identical to the GRIB and xarray examples — the only line that changes is how the data object is created:

# GRIB
data = ekd.from_source("sample", "era5-monthly-mean-2t-199312.grib")

# netCDF
data = ekd.from_source("sample", "era5-monthly-mean-2t-199312.nc")

# xarray
data = ekd.from_source("sample", "era5-monthly-mean-2t-199312.nc").to_xarray()

# In every case, the plot call is identical:
chart = ekp.Map(domain="Europe")
chart.plot(data, units="celsius")

This format agnosticism is a deliberate design goal of earthkit-plots: your visualisation code should not need to change just because your data arrives in a different format.