Lecture 10: Maps in Scientific Python¶
Making maps is a fundamental part of geoscience research. Maps differ from regular figures in the following principle ways:
- Maps require a projection of geographic coordinates on the 3D Earth to the 2D space of your figure.
- Maps often include extra decorations besides just our data (e.g. continents, country borders, etc.)
Mapping is a notoriously hard and complicated problem, mostly due to the complexities of projection.
In this lecture, we will learn about Cartopy, one of the most common packages for making maps within python.
Introducing Cartopy¶
Cartopy makes use of the powerful PROJ.4, numpy and shapely libraries and includes a programatic interface built on top of Matplotlib for the creation of publication quality maps.
Key features of cartopy are its object oriented projection definitions, and its ability to transform points, lines, vectors, polygons and images between those projections.
Cartopy Projections and other reference systems¶
In Cartopy, each projection is a class. Most classes of projection can be configured in projection-specific ways, although Cartopy takes an opinionated stance on sensible defaults.
Let's create a Plate Carree projection instance.
To do so, we need cartopy's crs module. This is typically imported as ccrs
(Cartopy Coordinate Reference Systems).
import cartopy.crs as ccrs
import cartopy
Cartopy's projection list tells us that the Plate Carree projection is available with the ccrs.PlateCarree
class:
https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html
Note: we need to instantiate the class in order to do anything projection-y with it!
import cartopy.crs as ccrs
import cartopy
ccrs.PlateCarree()
<cartopy.crs.PlateCarree object at 0x10da98910>
Drawing a map¶
Cartopy optionally depends upon matplotlib, and each projection knows how to create a matplotlib Axes (or AxesSubplot) that can represent itself.
The Axes that the projection creates is a cartopy.mpl.geoaxes.GeoAxes. This Axes subclass overrides some of matplotlib's existing methods, and adds a number of extremely useful ones for drawing maps.
We'll go back and look at those methods shortly, but first, let's actually see the cartopy+matplotlib dance in action:
import matplotlib.pyplot as plt
plt.axes(projection=ccrs.PlateCarree())
<GeoAxes: >
That was a little underwhelming, but we can see that the Axes created is indeed one of those GeoAxes[Subplot] instances.
One of the most useful methods that this class adds on top of the standard matplotlib Axes class is the coastlines
method. With no arguments, it will add the Natural Earth 1:110,000,000
scale coastline data to the map.
plt.figure()
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
<cartopy.mpl.feature_artist.FeatureArtist at 0x10f10d640>
We could just as equally created a matplotlib subplot with one of the many approaches that exist. For example, the plt.subplots
function could be used:
fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
ax.coastlines()
<cartopy.mpl.feature_artist.FeatureArtist at 0x10f11de20>
Projection classes have options we can use to customize the map
ccrs.PlateCarree?
Init signature: ccrs.PlateCarree(central_longitude=0.0, globe=None) Docstring: The abstract class which denotes cylindrical projections where we want to allow x values to wrap around. Init docstring: Parameters ---------- proj4_params: iterable of key-value pairs The proj4 parameters required to define the desired CRS. The parameters should not describe the desired elliptic model, instead create an appropriate Globe instance. The ``proj4_params`` parameters will override any parameters that the Globe defines. globe: :class:`~cartopy.crs.Globe` instance, optional If omitted, the default Globe instance will be created. See :class:`~cartopy.crs.Globe` for details. File: ~/opt/anaconda3/envs/research_computing_scipy/lib/python3.9/site-packages/cartopy/crs.py Type: ABCMeta Subclasses:
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
ax.coastlines()
<cartopy.mpl.feature_artist.FeatureArtist at 0x10f09e160>
Useful methods of a GeoAxes¶
The cartopy.mpl.geoaxes.GeoAxes class adds a number of useful methods.
Let's take a look at:
set_global - zoom the map out as much as possible
set_extent - zoom the map to the given bounding box
gridlines - add a graticule (and optionally labels) to the axes
coastlines - add Natural Earth coastlines to the axes
stock_img - add a low-resolution Natural Earth background image to the axes
imshow - add an image (numpy array) to the axes
add_geometries - add a collection of geometries (Shapely) to the axes
Some More Examples of Different Global Projections¶
projections = [ccrs.PlateCarree(),
ccrs.Mercator(),
ccrs.AzimuthalEquidistant()
]
for proj in projections:
plt.figure()
ax = plt.axes(projection=proj)
ax.stock_img()
ax.coastlines()
ax.set_title(f'{type(proj)}')
Regional Maps¶
To create a regional map, we use the set_extent
method of GeoAxis to limit the size of the region.
ax.set_extent?
Signature: ax.set_extent(extents, crs=None) Docstring: Set the extent (x0, x1, y0, y1) of the map in the given coordinate system. If no crs is given, the extents' coordinate system will be assumed to be the Geodetic version of this axes' projection. Parameters ---------- extents Tuple of floats representing the required extent (x0, x1, y0, y1). File: ~/opt/anaconda3/envs/research_computing_scipy/lib/python3.9/site-packages/cartopy/mpl/geoaxes.py Type: method
central_lon, central_lat = -10, 45
extent = [-40, 20, 30, 60]
ax = plt.axes(projection=ccrs.Orthographic(central_lon, central_lat))
ax.set_extent(extent)
ax.gridlines()
ax.coastlines(resolution='50m')
<cartopy.mpl.feature_artist.FeatureArtist at 0x17e1ce6a0>
Adding Features to the Map¶
To give our map more styles and details, we add cartopy.feature
objects.
Many useful features are built in. These "default features" are at coarse (110m) resolution.
Name | Description |
---|---|
cartopy.feature.BORDERS |
Country boundaries |
cartopy.feature.COASTLINE |
Coastline, including major islands |
cartopy.feature.LAKES |
Natural and artificial lakes |
cartopy.feature.LAND |
Land polygons, including major islands |
cartopy.feature.OCEAN |
Ocean polygons |
cartopy.feature.RIVERS |
Single-line drainages, including lake centerlines |
cartopy.feature.STATES |
(limited to the United States at this scale) |
Below we illustrate these features in a customized map of North America.
import cartopy.feature as cfeature
import numpy as np
central_lat = 37.5
central_lon = -96
extent = [-120, -70, 24, 50.5]
central_lon = np.mean(extent[:2])
central_lat = np.mean(extent[2:])
plt.figure(figsize=(12, 6))
ax = plt.axes(projection=ccrs.AlbersEqualArea(central_lon, central_lat))
ax.set_extent(extent)
ax.add_feature(cartopy.feature.OCEAN)
ax.add_feature(cartopy.feature.LAND, edgecolor='black')
ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
ax.add_feature(cartopy.feature.RIVERS)
ax.gridlines()
<cartopy.mpl.gridliner.Gridliner at 0x17e6e76d0>
Adding Data to the Map¶
Now that we know how to create a map, let's add our data to it! That's the whole point.
Because our map is a matplotlib axis, we can use all the familiar maptplotlib commands to make plots.
By default, the map extent will be adjusted to match the data. We can override this with the .set_global
or .set_extent
commands.
# create some test data
new_york = dict(lon=-74.0060, lat=40.7128)
honolulu = dict(lon=-157.8583, lat=21.3069)
lons = [new_york['lon'], honolulu['lon']]
lats = [new_york['lat'], honolulu['lat']]
Key point: the data also have to be transformed to the projection space.
This is done via the transform=
keyword in the plotting method. The argument is another cartopy.crs
object.
If you don't specify a transform, Cartopy assume that the data are using the same projection as the underlying GeoAxis.
From the Cartopy Documentation
The core concept is that the projection of your axes is independent of the coordinate system your data is defined in. The
projection
argument is used when creating plots and determines the projection of the resulting plot (i.e. what the plot looks like). Thetransform
argument to plotting functions tells Cartopy what coordinate system your data are defined in.
ax = plt.axes(projection=ccrs.PlateCarree())
ax.plot(lons, lats, label='Equirectangular straight line')
ax.plot(lons, lats, label='Great Circle', transform=ccrs.Geodetic())
ax.coastlines()
ax.legend()
ax.set_global()
Plotting 2D (Raster) Data¶
The same principles apply to 2D data. Below we create some example data defined in regular lat / lon coordinates.
import numpy as np
lon = np.linspace(-80, 80, 25)
lat = np.linspace(30, 70, 25)
lon2d, lat2d = np.meshgrid(lon, lat)
data = np.cos(np.deg2rad(lat2d) * 4) + np.sin(np.deg2rad(lon2d) * 4)
plt.contourf(lon2d, lat2d, data)
<matplotlib.contour.QuadContourSet at 0x17e7bb460>
Now we create a PlateCarree
projection and plot the data on it without any transform
keyword.
This happens to work because PlateCarree
is the simplest projection of lat / lon data.
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines()
ax.contourf(lon, lat, data)
<cartopy.mpl.contour.GeoContourSet at 0x17e54e880>
However, if we try the same thing with a different projection, we get the wrong result.
projection = ccrs.RotatedPole(pole_longitude=-177.5, pole_latitude=37.5)
ax = plt.axes(projection=projection)
ax.set_global()
ax.coastlines()
ax.contourf(lon, lat, data)
<cartopy.mpl.contour.GeoContourSet at 0x17e3d8f10>
To fix this, we need to pass the correct transform argument to contourf
:
projection = ccrs.RotatedPole(pole_longitude=-177.5, pole_latitude=37.5)
ax = plt.axes(projection=projection)
ax.set_global()
ax.coastlines()
ax.contourf(lon, lat, data, transform=ccrs.PlateCarree())
<cartopy.mpl.contour.GeoContourSet at 0x17e612a00>
Xarray Integration¶
Cartopy transforms can be passed to xarray! This creates a very quick path for creating professional looking maps from netCDF data.
import xarray as xr
ds = xr.open_dataset('/Users/xiaomengjin/Downloads/CERES_EBAF-TOA_Edition4.0_200003-201701.condensed.nc')
ds
<xarray.Dataset> Dimensions: (lon: 360, time: 203, lat: 180) Coordinates: * lon (lon) float32 0.5 1.5 2.5 ... 357.5 358.5 359.5 * time (time) datetime64[ns] 2000-03-15 ... 2017-01-15 * lat (lat) float32 -89.5 -88.5 -87.5 ... 88.5 89.5 Data variables: (12/14) toa_sw_all_mon (time, lat, lon) float32 ... toa_lw_all_mon (time, lat, lon) float32 ... toa_net_all_mon (time, lat, lon) float32 ... toa_sw_clr_mon (time, lat, lon) float32 ... toa_lw_clr_mon (time, lat, lon) float32 ... toa_net_clr_mon (time, lat, lon) float32 ... ... ... toa_cre_net_mon (time, lat, lon) float32 ... solar_mon (time, lat, lon) float32 ... cldarea_total_daynight_mon (time, lat, lon) float32 ... cldpress_total_daynight_mon (time, lat, lon) float32 ... cldtemp_total_daynight_mon (time, lat, lon) float32 ... cldtau_total_day_mon (time, lat, lon) float32 ... Attributes: title: CERES EBAF (Energy Balanced and Filled) TOA Fluxes. Mo... institution: NASA/LaRC (Langley Research Center) Hampton, Va Conventions: CF-1.4 comment: Data is from East to West and South to North. Version: Edition 4.0; Release Date March 7, 2017 Fill_Value: Fill Value is -999.0 DOI: 10.5067/TERRA+AQUA/CERES/EBAF-TOA_L3B.004.0 Production_Files: List of files used in creating the present Master netC...
toa_sw_mean = ds['toa_sw_all_mon'].mean(dim = 'time')
fig = plt.figure(figsize=(9,6))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
ax.gridlines()
toa_sw_mean.plot(ax=ax, transform=ccrs.PlateCarree(),
cmap = 'Reds', cbar_kwargs={'shrink': 0.4})
<cartopy.mpl.geocollection.GeoQuadMesh at 0x18525da00>
central_lat = 37.5
central_lon = -96
extent = [-120, -70, 24, 50.5]
central_lon = np.mean(extent[:2])
central_lat = np.mean(extent[2:])
plt.figure(figsize=(12, 6))
ax = plt.axes(projection=ccrs.AlbersEqualArea(central_lon, central_lat))
ax.set_extent(extent)
toa_sw_mean.plot(ax=ax, transform=ccrs.PlateCarree(),
cmap = 'jet', vmin = 60, vmax = 125, cbar_kwargs={'shrink': 0.4})
ax.add_feature(cartopy.feature.STATES, edgecolor='black')
ax.coastlines()
ax.gridlines()
<cartopy.mpl.gridliner.Gridliner at 0x185c54640>