PyEarthScience: Python examples for Earth Scientists

Contour plots

Using matplotlib and cartopy

Contour plot with

  • filled contour areas
  • labelbar
  • Orthographic projection

In [1]:
import netCDF4 as nc
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs

Show the plot inside notebook.


In [2]:
%matplotlib inline

Define function to read netCDF file.


In [3]:
def read_netCDF_file():
   """Read netcdf file and return arrays: ``lat``,``lon``, ``var``."""
   
   file_name = '/Users/k204045/NCL/general/data/new_data/rectilinear_grid_2D.nc'
   
   with nc.Dataset(file_name) as nco:
       var   = nco.variables['tsurf'][0,:,:]
       lat   = nco.variables['lat'][:]
       lon   = nco.variables['lon'][:]

   return lat, lon, var

Define main.


In [4]:
def main():
    ax = plt.axes(projection=ccrs.Orthographic())

    lat, lon, var = read_netCDF_file()

    plot = ax.contourf(lon, lat, var, transform=ccrs.PlateCarree(), cmap='spectral')
    ax.coastlines()
    ax.set_global()

    plt.colorbar(plot, orientation='horizontal')  # draw colorbar

    plt.show()

Run main.


In [5]:
if __name__ == '__main__':
    main()


/Users/k204045/local/miniconda2/lib/python2.7/site-packages/numpy/lib/shape_base.py:431: FutureWarning: in the future np.array_split will retain the shape of arrays with a zero size, instead of replacing them by `array([])`, which always has a shape of (0,).
  FutureWarning)
/Users/k204045/local/miniconda2/lib/python2.7/site-packages/matplotlib/collections.py:590: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if self._edgecolors == str('face'):