WEMC Tech Blog #2: Plotting NetCDF with Python
This example will examine how to plot time series wind measurements stored as NetCDF datasets, using Python3 (for info on installing Python3 and packages, see our previous blog).
If you would like to use the same NetCDF files, they can be retrieved from ECMWF using their web API. Once you have created an account with ECMWF, you can find the Python retrieval scripts for U and V wind components on my Github here.
Python has a wealth of package options for processing different types of data. For plotting NetCDF files in this example, the following packages are required:
Once the necessary packages and dependancies are installed, import them:
The xarray package provides some very convenient tools for working with NetCDF files. This example uses the xarray open_dataset function, to open two .nc files (for u and v wind components):
Typing the variable name and executing gives you some quick info on the dataset:
You can see the dataset ‘ds2’ contains hourly time-series, grid referenced data. With the variable v10 (describing the v component taken at 10 metre height). ERA5 data is taken at 0.25 degree resolution:
From these two datasets you can calculate the total wind speed. It’s important to perform this calculation before doing any time or location extractions, to ensure integrity of the data:
As there is one month of hourly data, the time series would be too long to efficiently plot across your x-axis. Luckily, xarray supports ‘group by’ operations. So you can quickly take an day’s hourly average, using the xarray groupby and mean function:
Next, select your desired grid reference, again using xarray’s sel function, calling the ‘nearest‘ method:
Finally, you can plot the data using matplotlib:
Depending on your grid locations, you should get a plot that looks something like this:
Repeating the above steps you can easily build multiple plots to compare different data sets:
For more examples on this, see matplotlib documentation.
The code for this example is on my GitHub
by Luke Sanger (WEMC, 2018)