pythonnetcdf

Read .nc (netcdf) files using python


I am trying to learn how to read netcdf files using Python in the most easiest/fastest way. I heard that it can be done with 3 lines of code but I really don't know how.

I am running the MITgcm numerical model. I'm trying to get an easy way to visualize the output data in the same way as programs like NCview does but with Python, so I can customise the parameters to read and everything.

I found this:

from matplotlib import pyplot as plt
import pandas as pd
import netCDF4
fp='uwstemp.nc'
nc = netCDF4.Dataset(fp)
plt.imshow(nc['Temp'][1,:,0,:])
plt.show()

It worked roughly like I want it, but I would like to understand word by word what is it doing. I guess 'Temp' is one of my variables, but I don't know how to figure out what all my variables are.

Specially, I don't understand plt.imshow(nc['Temp'][1,:,0,:]) that [1,:,0,:] I tried to change it and does not compile; but I don't understand what is it doing and why this numbers.


Solution

  • I use the MITgcm too. Say you have your state.nc output. First of all make sure you import all you need:

    from scipy.io import netcdf
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    

    The easiest way to read the data is:

    file2read = netcdf.NetCDFFile(path+'state.nc','r')
    temp = file2read.variables[var] # var can be 'Theta', 'S', 'V', 'U' etc..
    data = temp[:]*1
    file2read.close()
    

    Then a quick way to plot say layer z at time t is:

    plt.contourf(data[t,z,:,:])
    

    To answer your question I commented the code:

    from matplotlib import pyplot as plt # import libraries
    import pandas as pd # import libraries
    import netCDF4 # import libraries
    fp='uwstemp.nc' # your file name with the eventual path
    nc = netCDF4.Dataset(fp) # reading the nc file and creating Dataset
    """ in this dataset each component will be 
    in the form nt,nz,ny,nx i.e. all the variables will be flipped. """
    plt.imshow(nc['Temp'][1,:,0,:]) 
    """ imshow is a 2D plot function
    according to what I have said before this will plot the second
    iteration of the vertical slize with y = 0, one of the vertical
    boundaries of your model. """
    plt.show() # this shows the plot
    

    If you want to check the various dimensions of your data so you know what you can plot simply do print(nc['Temp'].shape)