Python/PlotMetData

From mn/geo/geoit
Jump to: navigation, search

Plotting Meteorological Data with Python

This is a very brief introduction to using pygrib and NetCDFFile in order to plot met data in Python. Note that you should read the Python/SettingPaths section in order to be sure that you'll be able to import the appropriate modules.

Let's get started with some test data::

   mkdir test
  cd test
  cp ~sec/kleinproject/FUKU/geop_april* .
  

Now, start ipython in your shell, or create a python file in the test directory::

   ipython
  
Next, let's take care of some basic imports::
import matplotlib.pyplot as plt
import pygrib
from netCDF4 import Dataset as NetCDFFile

Now, we'll write some python code to plot the netcdf variables::
nci = NetCDFFile('geopot_april_01.nc')
nci.variables #will print a listing of the variables (note: nci.variables is a dictionary)
z = nci.variables['z']
z.shape #what shape is the 'z' array?

for i in range(3):
 plt.figure()
 plt.imshow(z[0,i,:,:]) #we take the i'th slab
 plt.title('netcdf geopot {0}'.format(i))
 plt.colorbar()
 plt.savefig('nc_geopot_{}'.format(i))
Now, let's take a look at the grib data::
grbs = pygrib.open('geop_april_01_2011.grib')
for grb in grbs:
 grb
This will print a listing of all the gribs in the grib file. Make sure we reset the grbs back to the beginning::
grbs.seek(0)
ghs = grbs.select(name='Geopotential')

for i,grb in enumerate(ghs):
 plt.figure()
 g = grb
 plt.imshow(g.values)
 title = g.name + ' at level ' + str(g.level) + ' [' + g.units + ']'
 plt.title(title)
 plt.colorbar()
 plt.savefig(g.name + str(i) + '.png')
That's it! In your folder you should have some test plots.