cartopy.mpl.geoaxes.GeoAxes

class cartopy.mpl.geoaxes.GeoAxes(*args, **kwargs)[source]

A subclass of matplotlib.axes.Axes which represents a map Projection.

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 a standard map for latlon data for multiple subplots
fig, geo_axes = plt.subplots(nrows=2, ncols=2,
                    subplot_kw={'projection': ccrs.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())
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 are cartopy.io.img_nest.NestedImageCollection and cartopy.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 instance

raster_source may be any object which implements the RasterSource interface, including instances of objects such as WMSRasterSource and WMTSRasterSource. 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’s getmap_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.

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’s gettile_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, taking into account the projection of the geoaxes.

See imshow() for more details.

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.

property background_patch

DEPRECATED. 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.

  • 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.

cla()[source]

Clear the current axes and adds boundary lines.

coastlines(resolution='auto', color='black', **kwargs)[source]

Add coastal outlines to the current axes from the Natural Earth “coastline” shapefile collection.

Parameters

resolution (str or cartopy.feature.Scaler, optional) – A named resolution to use from the Natural Earth dataset. Currently can be one of “auto” (default), “110m”, “50m”, and “10m”, or a Scaler object.

contour(*args, **kwargs)[source]

Add the “transform” keyword to contour().

Parameters
  • transform – A Projection.

  • transform_first (bool, optional) – If True, this will transform the input arguments into projection-space before computing the contours, which is much faster than computing the contours in data-space and projecting the filled polygons. Using this method does not handle wrapped coordinates as well and can produce misleading contours in the middle of the domain. To use the projection-space method the input arguments X and Y must be provided and be 2-dimensional. The default is False, to compute the contours in data-space.

contourf(*args, **kwargs)[source]

Add the “transform” keyword to contourf().

Parameters
  • transform – A Projection.

  • transform_first (bool, optional) – If True, this will transform the input arguments into projection-space before computing the contours, which is much faster than computing the contours in data-space and projecting the filled polygons. Using this method does not handle wrapped coordinates as well and can produce misleading contours in the middle of the domain. To use the projection-space method the input arguments X and Y must be provided and be 2-dimensional. The default is False, to compute the contours in data-space.

draw(renderer=None, **kwargs)[source]

Extend the standard behaviour of matplotlib.axes.Axes.draw().

Draw grid lines and image factory results before invoking standard Matplotlib drawing. A global range is used if no limits have yet been set.

format_coord(x, y)[source]
Returns

A string formatted for the Matplotlib GUI status bar.

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.

get_tightbbox(renderer, *args, **kwargs)[source]

Extend the standard behaviour of matplotlib.axes.Axes.get_tightbbox().

Adjust the axes aspect ratio, background patch location, and add gridliners before calculating the tight bounding box.

gridlines(crs=None, draw_labels=False, xlocs=None, ylocs=None, dms=False, x_inline=None, y_inline=None, auto_inline=True, xformatter=None, yformatter=None, xlim=None, ylim=None, rotate_labels=None, xlabel_style=None, ylabel_style=None, labels_bbox_style=None, xpadding=5, ypadding=5, offset_angle=25, auto_update=False, formatter_kwargs=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 to cartopy.crs.PlateCarree.

  • draw_labels (optional) –

    Toggle whether to draw labels. For finer control, attributes of Gridliner may be modified individually. Defaults to False.

    • string: “x” or “y” to only draw labels of the respective coordinate in the CRS.

    • list: Can contain the side identifiers and/or coordinate types to select which ones to draw. For all labels one would use ["x", "y", "top", "bottom", "left", "right", "geo"].

    • dict: The keys are the side identifiers (“top”, “bottom”, “left”, “right”) and the values are the coordinates (“x”, “y”); this way you can precisely decide what kind of label to draw and where. For x labels on the bottom and y labels on the right you could pass in {"bottom": "x", "left": "y"}.

    Note that, by default, x and y labels are not drawn on left/right and top/bottom edges respectively unless explicitly requested.

  • 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.

  • dms (bool) – When default longitude and latitude locators and formatters are used, ticks are able to stop on minutes and seconds if minutes is set to True, and not fraction of degrees. This keyword is passed to Gridliner and has no effect if xlocs and ylocs are explicitly set.

  • x_inline (optional) – Toggle whether the x labels drawn should be inline.

  • y_inline (optional) – Toggle whether the y labels drawn should be inline.

  • auto_inline (optional) – Set x_inline and y_inline automatically based on projection

  • xformatter (optional) – A matplotlib.ticker.Formatter instance to format labels for x-coordinate gridlines. It defaults to None, which implies the use of a cartopy.mpl.ticker.LongitudeFormatter initiated with the dms argument, if the crs is of PlateCarree type.

  • yformatter (optional) – A matplotlib.ticker.Formatter instance to format labels for y-coordinate gridlines. It defaults to None, which implies the use of a cartopy.mpl.ticker.LatitudeFormatter initiated with the dms argument, if the crs is of PlateCarree type.

  • xlim (optional) – Set a limit for the gridlines so that they do not go all the way to the edge of the boundary. xlim can be a single number or a (min, max) tuple. If a single number, the limits will be (-xlim, +xlim).

  • ylim (optional) – Set a limit for the gridlines so that they do not go all the way to the edge of the boundary. ylim can be a single number or a (min, max) tuple. If a single number, the limits will be (-ylim, +ylim).

  • rotate_labels (optional, bool, str) –

    Allow the rotation of non-inline labels.

    • False: Do not rotate the labels.

    • True: Rotate the labels parallel to the gridlines.

    • None: no rotation except for some projections (default).

    • A float: Rotate labels by this value in degrees.

  • xlabel_style (dict) – A dictionary passed through to ax.text on x label creation for styling of the text labels.

  • ylabel_style (dict) – A dictionary passed through to ax.text on y label creation for styling of the text labels.

  • labels_bbox_style (dict) – bbox style for all text labels.

  • xpadding (float) – Padding for x labels. If negative, the labels are drawn inside the map.

  • ypadding (float) – Padding for y labels. If negative, the labels are drawn inside the map.

  • offset_angle (float) – Difference of angle in degrees from 90 to define when a label must be flipped to be more readable. For example, a value of 10 makes a vertical top label to be flipped only at 100 degrees.

  • auto_update (bool) – Whether to update the grilines and labels when the plot is refreshed.

  • formatter_kwargs (dict, optional) – Options passed to the default formatters. See LongitudeFormatter and LatitudeFormatter

  • Parameters (Keyword) –

  • ------------------

  • **kwargs (dict) – All other keywords control line properties. These are passed through to matplotlib.collections.Collection.

Returns

gridliner – A cartopy.mpl.gridliner.Gridliner instance.

Notes

The “x” and “y” for locations and inline settings do not necessarily correspond to X and Y, but to the first and second coordinates of the specified CRS. For the common case of PlateCarree gridlines, these correspond to longitudes and latitudes. Depending on the projection used for the map, meridians and parallels can cross both the X axis and the Y axis.

hexbin(x, y, *args, **kwargs)[source]

Add the “transform” keyword to hexbin().

The points are first transformed into the projection of the axes and then the hexbin algorithm is computed using the data in the axes projection.

Parameters

transform – A Projection.

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.

imshow(img, *args, **kwargs)[source]

Add the “transform” keyword to imshow().

Parameters
  • img – The image to be displayed.

  • transform (Projection or matplotlib transform) – The coordinate system in which the given image is rectangular.

  • regrid_shape (int or pair of ints) – The shape of the desired image if it needs to be transformed. If a single integer is given then that will be used as the minimum length dimension, while the other dimension will be scaled up according to the target extent’s aspect ratio. The default is for the minimum dimension of a transformed image to have length 750, so for an image being transformed into a global PlateCarree projection the resulting transformed image would have a shape of (750, 1500).

  • extent (tuple) – The corner coordinates of the image in the form (left, right, bottom, top). The coordinates should be in the coordinate system passed to the transform keyword.

  • origin ({'lower', 'upper'}) – The origin of the vertical pixels. See matplotlib.pyplot.imshow() for further details. Default is 'upper'. Prior to 0.18, it was 'lower'.

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 the PathCollection constructor.

Returns

The created PathCollection.

property outline_patch

DEPRECATED. The patch that provides the line bordering the projection.

Use GeoAxes.spines[‘geo’] or default Axes properties instead.

pcolor(*args, **kwargs)[source]

Add the “transform” keyword to pcolor().

Parameters

transform – A Projection.

pcolormesh(*args, **kwargs)[source]

Add the “transform” keyword to pcolormesh().

Parameters

transform – A Projection.

projection

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.

  • 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

scatter(*args, **kwargs)[source]

Add the “transform” keyword to scatter().

Parameters

transform – A Projection.

set_boundary(path, transform=None, use_as_clip_path=None)[source]

Given a path, update spines['geo'] and patch.

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.

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

extents – 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.

  • 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 to cartopy.feature.ShapelyFeature.