Colorized Grid Data

Notebook Python-AWIPS Tutorial Notebook


Objectives

  • Create a colorized plot for the continental US of model data (grib).

  • Access the model data from an EDEX server and limit the data returned by using model specific parameters.

  • Use both pcolormesh and contourf to create colorized plots, and compare the differences between the two.


Table of Contents


1 Imports

Start by importing both the python-awips specific library, as well as the libraries needed for plotting and manipulating the data

from awips.dataaccess import DataAccessLayer
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from scipy.constants import convert_temperature

Top


2 Define Data Request

If you read through the python-awips: How to Access Data training, you will know that we need to set an EDEX url to access our server, and then we create a data request. In this example we use grid as the data type to define our request. In addition to setting the data type, the location, parameters and levels are also set as RAP13, T (for temperature), and 2.0FHAG (for Fixed Height Above Ground in meters), respectively.

DataAccessLayer.changeEDEXHost("edex-cloud.unidata.ucar.edu")
request = DataAccessLayer.newDataRequest()
request.setDatatype("grid")
request.setLocationNames("RAP13")
request.setParameters("T")
request.setLevels("2.0FHAG")

# Take a look at our request
print(request)
DefaultDataRequest(datatype=grid, identifiers={}, parameters=['T'], levels=[<dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.level.Level.Level object at 0x11127bfd0>], locationNames=['RAP13'], envelope=None)

Top


3 Limit Results Based on Time

Models produce many different time variants during their runs, so let’s limit the data to the most recent time and forecast run.

Note: You can play around with different times and forecast runs to see the differences.

cycles = DataAccessLayer.getAvailableTimes(request, True)
times = DataAccessLayer.getAvailableTimes(request)
fcstRun = DataAccessLayer.getForecastRun(cycles[-1], times)

# Get the most recent grid data
response = DataAccessLayer.getGridData(request, [fcstRun[0]])

print('Number of available times:', len(times))
print('Number of available forecast runs:', len(fcstRun))
Number of available times: 74
Number of available forecast runs: 8

Top


4 Function: make_map()

In order to plot more than one image, it’s easiest to define common logic in a function. Here, a new function called make_map is defined. This function uses the matplotlib.pyplot package (plt) to create a figure and axis. The coastlines (continental boundaries) are added, along with lat/lon grids.

def make_map(bbox, projection=ccrs.PlateCarree()):
    fig, ax = plt.subplots(figsize=(16, 9),
            subplot_kw=dict(projection=projection))
    ax.set_extent(bbox)
    ax.coastlines(resolution='50m')
    gl = ax.gridlines(draw_labels=True)
    gl.top_labels = gl.right_labels = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    return fig, ax

Top


5 Use the Grid Data!

Here we get our grid data object from our previous response, and then get the raw data array off that object. We also get the latitude and longitude arrays, and create a bounding box that we’ll use when creating our plots (by calling make_map defined above). Finally, we’ll convert our data from degrees Kelvin to Farenheit to make the plot more understandable.

grid = response[0]
data = grid.getRawData()
lons, lats = grid.getLatLonCoords()
bbox = [lons.min(), lons.max(), lats.min(), lats.max()]

# Convert temp from Kelvin to F
destUnit = 'F'
data = convert_temperature(data, 'K', destUnit)

5.1 Plot Using pcolormesh

This example shows how to use matplotlib.pyplot.pcolormesh to create a colorized plot. We use our make_map function to create a subplot and then we create a color scale (cs) and colorbar (cbar) with a label for our plot.

Note: You may see a warning appear with a red background, this is okay, and will go away with subsequent runs of the cell.

cmap = plt.get_cmap('rainbow')
fig, ax = make_map(bbox=bbox)
cs = ax.pcolormesh(lons, lats, data, cmap=cmap)
cbar = fig.colorbar(cs, shrink=0.7, orientation='horizontal')
cbar.set_label(grid.getLocationName() +" "+ grid.getLevel() + " " \
               + grid.getParameter() + " (" + destUnit + ") " \
               + "valid " + str(grid.getDataTime().getRefTime()))
/Users/scarter/opt/miniconda3/envs/python3-awips/lib/python3.9/site-packages/cartopy/mpl/geoaxes.py:1598: UserWarning: The input coordinates to pcolormesh are interpreted as cell centers, but are not monotonically increasing or decreasing. This may lead to incorrectly calculated cell edges, in which case, please supply explicit cell edges to pcolormesh.
  X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
../../_images/Colorized_Grid_Data_21_1.png

5.2 Plot Using contourf

This example shows how to use matplotlib.pyplot.contourf to create a colorized plot. We use our make_map function to create a subplot and then we create a color scale (cs2) and colorbar (cbar2) with a label for our plot.

fig2, ax2 = make_map(bbox=bbox)
cs2 = ax2.contourf(lons, lats, data, 80, cmap=cmap,
                  vmin=data.min(), vmax=data.max())
cbar2 = fig2.colorbar(cs2, shrink=0.7, orientation='horizontal')
cbar2.set_label(grid.getLocationName() +" "+ grid.getLevel() + " " \
               + grid.getParameter() + " (" + destUnit + ") " \
               + "valid " + str(grid.getDataTime().getRefTime()))
../../_images/Colorized_Grid_Data_23_0.png

Top


6 See Also

6.2 Additional Documentation

python-awips:

matplotlib:

Top