Search code examples
pythonmatplotlibnetcdfpython-xarraynetcdf4

working with netCDF on python with matplotlib


So I am pretty new in programming, currently doing some research on netCDF .nc files to work with python. I have the following code which I am sure it will not work. The objective here is to plot a graph simple line graph of 10m u-component of winds over time. The problem I think is that 10m u-component of winds has 4D shape of (time=840, expver=2, latitude=19, longitude=27) while time being only (time=840). Any replies or ideas will be much appreciated! The code is as shown:

from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np

nc = Dataset(r'C:\WAIG\Python\ERA5_py01\Downloaded_nc_file/test_era5.nc','r')

for i in nc.variables:
    print(i)

lat = nc.variables['latitude'][:]
lon = nc.variables['longitude'][:]
time = nc.variables['time'][:]
u = nc.variables['u10'][:]


plt.plot(np.squeeze(u), np.squeeze(time))
plt.show()

Solution

  • Right, you have winds that represent the 10m wind at every location of the model grid (lat,lon) as well as dimensioned on exper--not sure what that last one is. You need to select a subset of u. For example, let's pick exper=1, and lat/lon indexes of lat=8, lon=12 (not sure where those are going to be:

    exper_index = 1
    lat_index = 8
    lon_index = 12
    # ':' below means "full slice"--take everything along that dimension
    plt.plot(u[:, exper_index, lat_index, lon_index], time)
    plt.title(f'U at latitude {lat[lat_index]}, longitude {lon[lon_index]}')
    plt.show()