Cartopy Matplotlib integration reference document¶
The primary class for integrating cartopy into Matplotlib is the GeoAxes, which is a subclass of a normal Matplotlib Axes. The GeoAxes class adds extra functionality to an axes which is specific to drawing maps. The majority of the methods which have been specialised from the original Axes are there to add improved -expected- behaviour, but some are to work around limitations that the standard Matplotlib axes treats data in a Cartesian way (most of which either have, or will be, submitted back to the Matplotlib project).
-
class
cartopy.mpl.geoaxes.
GeoAxes
(*args, **kwargs)[source]¶ A subclass of
matplotlib.axes.Axes
which represents a mapProjection
.This class replaces the Matplotlib
Axes
class when created with the projection keyword. For example:# Set up a standard map for latlon data. geo_axes = plt.axes(projection=cartopy.crs.PlateCarree()) # Set up an OSGB map. geo_axes = plt.subplot(2, 2, 1, projection=cartopy.crs.OSGB())
When a source projection is provided to one of it’s plotting methods, using the transform keyword, the standard Matplotlib plot result is transformed from source coordinates to the target projection. For example:
# Plot latlon data on an OSGB map. plt.axes(projection=cartopy.crs.OSGB()) plt.contourf(x, y, data, transform=cartopy.crs.PlateCarree())
Create a GeoAxes object using standard matplotlib
Axes
args and kwargs.Parameters: map_projection (optional) – The target Projection
of this Axes object.All other args and keywords are passed through to
matplotlib.axes.Axes
.-
add_feature
(feature, **kwargs)[source]¶ Add the given
Feature
instance to the axes.Parameters: feature – An instance of Feature
.Returns: A cartopy.mpl.feature_artist.FeatureArtist
instance – The instance responsible for drawing the feature.Note
Matplotlib keyword arguments can be used when drawing the feature. This allows standard Matplotlib control over aspects such as ‘facecolor’, ‘alpha’, etc.
-
add_geometries
(geoms, crs, **kwargs)[source]¶ Add the given shapely geometries (in the given crs) to the axes.
Parameters: - geoms – A collection of shapely geometries.
- crs – The cartopy CRS in which the provided geometries are defined.
- styler – A callable that returns matplotlib patch styling given a geometry.
Returns: A
cartopy.mpl.feature_artist.FeatureArtist
instance – The instance responsible for drawing the feature.Note
Matplotlib keyword arguments can be used when drawing the feature. This allows standard Matplotlib control over aspects such as ‘facecolor’, ‘alpha’, etc.
-
add_image
(factory, *args, **kwargs)[source]¶ Add an image “factory” to the Axes.
Any image “factory” added will be asked to retrieve an image with associated metadata for a given bounding box at draw time. The advantage of this approach is that the limits of the map do not need to be known when adding the image factory, but can be deferred until everything which can effect the limits has been added.
Parameters: factory – Currently an image “factory” is just an object with an image_for_domain
method. Examples of image factories arecartopy.io.img_nest.NestedImageCollection
andcartopy.io.image_tiles.GoogleTiles
.
-
add_raster
(raster_source, **slippy_image_kwargs)[source]¶ Add the given raster source to the GeoAxes.
Parameters: raster_source – cartopy.io.RasterSource
like instanceraster_source
may be any object which implements the RasterSource interface, including instances of objects such asWMSRasterSource
andWMTSRasterSource
. Note that image retrievals are done at draw time, not at creation time.
-
add_wms
(wms, layers, wms_kwargs=None, **kwargs)[source]¶ Add the specified WMS layer to the axes.
This function requires owslib and PIL to work.
Parameters: - wms (string or
owslib.wms.WebMapService
instance) – The web map service URL or owslib WMS instance to use. - layers (string or iterable of string) – The name of the layer(s) to use.
- wms_kwargs (dict or None, optional) – Passed through to the
WMSRasterSource
constructor’sgetmap_extra_kwargs
for defining getmap time keyword arguments.
All other keywords are passed through to the construction of the image artist. See
imshow()
for more details.- wms (string or
-
add_wmts
(wmts, layer_name, wmts_kwargs=None, **kwargs)[source]¶ Add the specified WMTS layer to the axes.
This function requires owslib and PIL to work.
Parameters: - wmts – The URL of the WMTS, or an owslib.wmts.WebMapTileService instance.
- layer_name – The name of the layer to use.
- wmts_kwargs (dict or None, optional) – Passed through to the
WMTSRasterSource
constructor’sgettile_extra_kwargs
(e.g. time).
All other keywords are passed through to the construction of the image artist. See
imshow()
for more details.
-
autoscale_view
(tight=None, scalex=True, scaley=True)[source]¶ Autoscale the view limits using the data limits.
You can selectively autoscale only a single axis, e.g., the xaxis by setting scaley to False. The autoscaling preserves any axis direction reversal that has already been done.
If tight is False, the axis major locator will be used to expand the view limits if rcParams[‘axes.autolimit_mode’] is ‘round_numbers’. Note that any margins that are in effect will be applied first, regardless of whether tight is True or False. Specifying tight as True or False saves the setting as a private attribute of the Axes; specifying it as None (the default) applies the previously saved value.
The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use
matplotlib.axes.Axes.relim()
prior to calling autoscale_view.
-
background_img
(name='ne_shaded', resolution='low', extent=None, cache=False)[source]¶ Add a background image to the map, from a selection of pre-prepared images held in a directory specified by the CARTOPY_USER_BACKGROUNDS environment variable. That directory is checked with func:
self.read_user_background_images
and needs to contain a JSON file which defines for the image metadata.Parameters: - name (optional) – The name of the image to read according to the contents of the JSON file. A typical file might have, for instance: ‘ne_shaded’ : Natural Earth Shaded Relief ‘ne_grey’ : Natural Earth Grey Earth.
- resolution (optional) – The resolution of the image to read, according to the contents of the JSON file. A typical file might have the following for each name of the image: ‘low’, ‘med’, ‘high’, ‘vhigh’, ‘full’.
- extent (optional) –
Using a high resolution background image zoomed into a small area will take a very long time to render as the image is prepared globally, even though only a small area is used. Adding the extent will only render a particular geographic region. Specified as [longitude start, longitude end, latitude start, latitude end].
e.g. [-11, 3, 48, 60] for the UK or [167.0, 193.0, 47.0, 68.0] to cross the date line. - cache (optional) – Logical flag as to whether or not to cache the loaded images into memory. The images are stored before the extent is used.
-
background_patch
= None¶ The patch that provides the filled background of the projection.
-
barbs
(x, y, u, v, *args, **kwargs)[source]¶ Plot a field of barbs.
Parameters: - x – An array containing the x-positions of data points.
- y – An array containing the y-positions of data points.
- u – An array of vector data in the u-direction.
- v – An array of vector data in the v-direction.
Other Parameters: - transform (
cartopy.crs.Projection
or Matplotlib transform) – The coordinate system in which the vectors are defined. - regrid_shape (int or 2-tuple of ints) – If given, specifies that the points where the barbs are located will be interpolated onto a regular grid in projection space. If a single integer is given then that will be used as the minimum grid length dimension, while the other dimension will be scaled up according to the target extent’s aspect ratio. If a pair of ints are given they determine the grid length in the x and y directions respectively.
- target_extent (4-tuple) – If given, specifies the extent in the target CRS that the regular grid defined by regrid_shape will have. Defaults to the current extent of the map projection.
See
matplotlib.pyplot.barbs()
for details on arguments and other keyword arguments.Note
The vector components must be defined as grid eastward and grid northward.
-
coastlines
(resolution='110m', color='black', **kwargs)[source]¶ Add coastal outlines to the current axes from the Natural Earth “coastline” shapefile collection.
Parameters: resolution – A named resolution to use from the Natural Earth dataset. Currently can be one of “110m”, “50m”, and “10m”, or a Scaler object.
-
get_extent
(crs=None)[source]¶ Get the extent (x0, x1, y0, y1) of the map in the given coordinate system.
If no crs is given, the returned extents’ coordinate system will be the CRS of this Axes.
-
gridlines
(crs=None, draw_labels=False, xlocs=None, ylocs=None, **kwargs)[source]¶ Automatically add gridlines to the axes, in the given coordinate system, at draw time.
Parameters: - crs (optional) – The
cartopy._crs.CRS
defining the coordinate system in which gridlines are drawn. Defaults tocartopy.crs.PlateCarree
. - draw_labels (optional) – Label gridlines like axis ticks, around the edge.
- xlocs (optional) – An iterable of gridline locations or a
matplotlib.ticker.Locator
instance which will be used to determine the locations of the gridlines in the x-coordinate of the given CRS. Defaults to None, which implies automatic locating of the gridlines. - ylocs (optional) – An iterable of gridline locations or a
matplotlib.ticker.Locator
instance which will be used to determine the locations of the gridlines in the y-coordinate of the given CRS. Defaults to None, which implies automatic locating of the gridlines.
Returns: gridliner – A
cartopy.mpl.gridliner.Gridliner
instance.Note
All other keywords control line properties. These are passed through to
matplotlib.collections.Collection
.- crs (optional) – The
-
hold_limits
(hold=True)[source]¶ Keep track of the original view and data limits for the life of this context manager, optionally reverting any changes back to the original values after the manager exits.
Parameters: hold (bool, optional) – Whether to revert the data and view limits after the context manager exits. Defaults to True.
-
natural_earth_shp
(name='land', resolution='110m', category='physical', **kwargs)[source]¶ Add the geometries from the specified Natural Earth shapefile to the Axes as a
PathCollection
.Parameters: - name (optional) – Name of the shapefile geometry to add. Defaults to ‘land’.
- resolution (optional) – Resolution of shapefile geometry to add. Defaults to ‘110m’.
- category (optional) – Category of shapefile geometry to add. Defaults to ‘physical’.
**kwargs
are passed through to thePathCollection
constructor.Returns: The created PathCollection
.
-
outline_patch
= None¶ The patch that provides the line bordering the projection.
-
projection
= None¶ The
cartopy.crs.Projection
of this GeoAxes.
-
quiver
(x, y, u, v, *args, **kwargs)[source]¶ Plot a field of arrows.
Parameters: - x – An array containing the x-positions of data points.
- y – An array containing the y-positions of data points.
- u – An array of vector data in the u-direction.
- v – An array of vector data in the v-direction.
Other Parameters: - transform (
cartopy.crs.Projection
or Matplotlib transform) – The coordinate system in which the vectors are defined. - regrid_shape (int or 2-tuple of ints) – If given, specifies that the points where the arrows are located will be interpolated onto a regular grid in projection space. If a single integer is given then that will be used as the minimum grid length dimension, while the other dimension will be scaled up according to the target extent’s aspect ratio. If a pair of ints are given they determine the grid length in the x and y directions respectively.
- target_extent (4-tuple) – If given, specifies the extent in the target CRS that the regular grid defined by regrid_shape will have. Defaults to the current extent of the map projection.
See
matplotlib.pyplot.quiver()
for details on arguments and other keyword arguments.Note
The vector components must be defined as grid eastward and grid northward.
-
read_user_background_images
(verify=True)[source]¶ Read the metadata in the specified CARTOPY_USER_BACKGROUNDS environment variable to populate the dictionaries for background_img.
If CARTOPY_USER_BACKGROUNDS is not set then by default the image in lib/cartopy/data/raster/natural_earth/ will be made available.
The metadata should be a standard JSON file which specifies a two level dictionary. The first level is the image type. For each image type there must be the fields: __comment__, __source__ and __projection__ and then an element giving the filename for each resolution.
An example JSON file can be found at: lib/cartopy/data/raster/natural_earth/images.json
-
set_boundary
(path, transform=None, use_as_clip_path=True)[source]¶ Given a path, update the
outline_patch
andbackground_patch
to take its shape.Parameters: - path (
matplotlib.path.Path
) – The path of the desired boundary. - transform (None or
matplotlib.transforms.Transform
, optional) – The coordinate system of the given path. Currently this must be convertible to data coordinates, and therefore cannot extend beyond the limits of the axes’ projection. - use_as_clip_path (bool, optional) – Whether axes.patch should be updated. Updating axes.patch means that any artists subsequently created will inherit clipping from this path, rather than the standard unit square in axes coordinates.
- path (
-
set_extent
(extents, crs=None)[source]¶ 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: extent – Tuple of floats representing the required extent (x0, x1, y0, y1).
-
set_global
()[source]¶ Set the extent of the Axes to the limits of the projection.
Note
In some cases where the projection has a limited sensible range the
set_global
method does not actually make the whole globe visible. Instead, the most appropriate extents will be used (e.g. Ordnance Survey UK will set the extents to be around the British Isles.
-
set_xticks
(ticks, minor=False, crs=None)[source]¶ Set the x ticks.
Parameters: - ticks – List of floats denoting the desired position of x ticks.
- minor (optional) – flag indicating whether the ticks should be minor ticks i.e. small and unlabelled (defaults to False).
- crs (optional) – An instance of
CRS
indicating the coordinate system of the provided tick values. If no coordinate system is specified then the values are assumed to be in the coordinate system of the projection. Only transformations from one rectangular coordinate system to another rectangular coordinate system are supported (defaults to None).
Note
This interface is subject to change whilst functionality is added to support other map projections.
-
set_yticks
(ticks, minor=False, crs=None)[source]¶ Set the y ticks.
Parameters: - ticks – List of floats denoting the desired position of y ticks.
- minor (optional) – flag indicating whether the ticks should be minor ticks i.e. small and unlabelled (defaults to False).
- crs (optional) – An instance of
CRS
indicating the coordinate system of the provided tick values. If no coordinate system is specified then the values are assumed to be in the coordinate system of the projection. Only transformations from one rectangular coordinate system to another rectangular coordinate system are supported (defaults to None).
Note
This interface is subject to change whilst functionality is added to support other map projections.
-
stock_img
(name='ne_shaded')[source]¶ Add a standard image to the map.
Currently, the only (and default) option is a downsampled version of the Natural Earth shaded relief raster.
-
streamplot
(x, y, u, v, **kwargs)[source]¶ Plot streamlines of a vector flow.
Parameters: - x – An array containing the x-positions of data points.
- y – An array containing the y-positions of data points.
- u – An array of vector data in the u-direction.
- v – An array of vector data in the v-direction.
Other Parameters: transform (
cartopy.crs.Projection
or Matplotlib transform.) – The coordinate system in which the vector field is defined.See
matplotlib.pyplot.streamplot()
for details on arguments and keyword arguments.Note
The vector components must be defined as grid eastward and grid northward.
-
tissot
(rad_km=500, lons=None, lats=None, n_samples=80, **kwargs)[source]¶ Add Tissot’s indicatrices to the axes.
Parameters: - rad_km – The radius in km of the the circles to be drawn.
- lons – A numpy.ndarray, list or tuple of longitude values that locate the centre of each circle. Specifying more than one dimension allows individual points to be drawn whereas a 1D array produces a grid of points.
- lats – A numpy.ndarray, list or tuple of latitude values that that locate the centre of each circle. See lons.
- n_samples – Integer number of points sampled around the circumference of each circle.
**kwargs
are passed through toclass:ShapelyFeature
.
-
-
class
cartopy.mpl.geoaxes.
GeoAxesSubplot
¶
-
cartopy.mpl.patch.
path_to_geos
(path, force_ccw=False)[source]¶ Create a list of Shapely geometric objects from a
matplotlib.path.Path
.Parameters: path – A matplotlib.path.Path
instance.Other Parameters: force_ccw – Boolean flag determining whether the path can be inverted to enforce ccw. Defaults to False. Returns: A list of instances of the following type(s) – shapely.geometry.polygon.Polygon
,shapely.geometry.linestring.LineString
and/orshapely.geometry.multilinestring.MultiLineString
.
-
cartopy.mpl.patch.
geos_to_path
(shape)[source]¶ Create a list of
matplotlib.path.Path
objects that describe a shape.Parameters: shape – A list, tuple or single instance of any of the following types: shapely.geometry.point.Point
,shapely.geometry.linestring.LineString
,shapely.geometry.polygon.Polygon
,shapely.geometry.multipoint.MultiPoint
,shapely.geometry.multipolygon.MultiPolygon
,shapely.geometry.multilinestring.MultiLineString
,shapely.geometry.collection.GeometryCollection
, or any type with a _as_mpl_path() method.Returns: paths – A list of matplotlib.path.Path
objects.