deafrica_tools.plotting

Functions for plotting Digital Earth Africa data.

License

The code in this notebook is licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Africa data is licensed under the Creative Commons by Attribution 4.0 license (https://creativecommons.org/licenses/by/4.0/).

Contact

If you need assistance, please post a question on the Open Data Cube Slack channel (http://slack.opendatacube.org/) or on the GIS Stack Exchange (https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the open-data-cube tag (you can view previously asked questions here: https://gis.stackexchange.com/questions/tagged/open-data-cube).

If you would like to report an issue with this script, file one on Github: https://github.com/digitalearthafrica/deafrica-sandbox-notebooks/issues/new

Functions

display_map(x, y[, crs, margin, zoom_bias])

Given a set of x and y coordinates, this function generates an interactive map with a bounded rectangle overlayed on Google Maps imagery.

map_shapefile(gdf, attribute[, continuous, …])

Plots a geopandas GeoDataFrame over an interactive ipyleaflet basemap, with features coloured based on attribute column values.

rgb(ds[, bands, index, index_dim, robust, …])

Takes an xarray dataset and plots RGB images using three imagery bands (e.g [‘red’, ‘green’, ‘blue’]).

xr_animation(ds[, bands, output_path, …])

Takes an xarray timeseries and animates the data as either a three-band (e.g.

deafrica_tools.plotting.display_map(x, y, crs='EPSG:4326', margin=- 0.5, zoom_bias=0)

Given a set of x and y coordinates, this function generates an interactive map with a bounded rectangle overlayed on Google Maps imagery.

Last modified: September 2019

Modified from function written by Otto Wagner available here: https://github.com/ceos-seo/data_cube_utilities/tree/master/data_cube_utilities

Parameters
  • x ((float, float)) – A tuple of x coordinates in (min, max) format.

  • y ((float, float)) – A tuple of y coordinates in (min, max) format.

  • crs (string, optional) – A string giving the EPSG CRS code of the supplied coordinates. The default is ‘EPSG:4326’.

  • margin (float) – A numeric value giving the number of degrees lat-long to pad the edges of the rectangular overlay polygon. A larger value results more space between the edge of the plot and the sides of the polygon. Defaults to -0.5.

  • zoom_bias (float or int) – A numeric value allowing you to increase or decrease the zoom level by one step. Defaults to 0; set to greater than 0 to zoom in, and less than 0 to zoom out.

Returns

  • folium.Map (A map centered on the supplied coordinate bounds. A)

  • rectangle is drawn on this map detailing the perimeter of the x, y

  • bounds. A zoom level is calculated such that the resulting

  • viewport is the closest it can possibly get to the centered

  • bounding rectangle without clipping it.

deafrica_tools.plotting.map_shapefile(gdf, attribute, continuous=False, cmap='viridis', basemap=ipyleaflet.basemaps.Esri.WorldImagery, default_zoom=None, hover_col=True, **style_kwargs)

Plots a geopandas GeoDataFrame over an interactive ipyleaflet basemap, with features coloured based on attribute column values. Optionally, can be set up to print selected data from features in the GeoDataFrame.

Last modified: February 2020

Parameters
  • gdf (geopandas.GeoDataFrame) – A GeoDataFrame containing the spatial features to be plotted over the basemap.

  • attribute (string, required) – An required string giving the name of any column in the GeoDataFrame you wish to have coloured on the choropleth.

  • continuous (boolean, optional) – Whether to plot data as a categorical or continuous variable. Defaults to remapping the attribute which is suitable for categorical data. For continuous data set continuous to True.

  • cmap (string, optional) – A string giving the name of a matplotlib.cm colormap that will be used to style the features in the GeoDataFrame. Features will be coloured based on the selected attribute. Defaults to the ‘viridis’ colormap.

  • basemap (ipyleaflet.basemaps object, optional) – An optional ipyleaflet.basemaps object used as the basemap for the interactive plot. Defaults to basemaps.Esri.WorldImagery.

  • default_zoom (int, optional) – An optional integer giving a default zoom level for the interactive ipyleaflet plot. Defaults to None, which infers the zoom level from the extent of the data.

  • hover_col (boolean or str, optional) – If True (the default), the function will print values from the GeoDataFrame’s attribute column above the interactive map when a user hovers over the features in the map. Alternatively, a custom shapefile field can be specified by supplying a string giving the name of the field to print. Set to False to prevent any attributes from being printed.

  • **style_kwargs – Optional keyword arguments to pass to the style paramemter of the ipyleaflet.Choropleth function. This can be used to control the appearance of the shapefile, for example ‘stroke’ and ‘weight’ (controlling line width), ‘fillOpacity’ (polygon transparency) and ‘dashArray’ (whether to plot lines/outlines with dashes). For more information: https://ipyleaflet.readthedocs.io/en/latest/api_reference/choropleth.html

deafrica_tools.plotting.rgb(ds, bands=['red', 'green', 'blue'], index=None, index_dim='time', robust=True, percentile_stretch=None, col_wrap=4, size=6, aspect=None, savefig_path=None, savefig_kwargs={}, **kwargs)

Takes an xarray dataset and plots RGB images using three imagery bands (e.g [‘red’, ‘green’, ‘blue’]). The index parameter allows easily selecting individual or multiple images for RGB plotting. Images can be saved to file by specifying an output path using savefig_path.

This function was designed to work as an easier-to-use wrapper around xarray’s .plot.imshow() functionality.

Last modified: April 2021

Parameters
  • ds (xarray Dataset) – A two-dimensional or multi-dimensional array to plot as an RGB image. If the array has more than two dimensions (e.g. multiple observations along a ‘time’ dimension), either use index to select one (index=0) or multiple observations (index=[0, 1]), or create a custom faceted plot using e.g. col=”time”.

  • bands (list of strings, optional) – A list of three strings giving the band names to plot. Defaults to ‘[‘red’, ‘green’, ‘blue’]’. If the dataset does not contain bands named ‘red’, ‘green’, ‘blue’, then bands must be specified.

  • index (integer or list of integers, optional) – index can be used to select one (index=0) or multiple observations (index=[0, 1]) from the input dataset for plotting. If multiple images are requested these will be plotted as a faceted plot.

  • index_dim (string, optional) – The dimension along which observations should be plotted if multiple observations are requested using index. Defaults to time.

  • robust (bool, optional) – Produces an enhanced image where the colormap range is computed with 2nd and 98th percentiles instead of the extreme values. Defaults to True.

  • percentile_stretch (tuple of floats) – An tuple of two floats (between 0.00 and 1.00) that can be used to clip the colormap range to manually specified percentiles to get more control over the brightness and contrast of the image. The default is None; ‘(0.02, 0.98)’ is equivelent to robust=True. If this parameter is used, robust will have no effect.

  • col_wrap (integer, optional) – The number of columns allowed in faceted plots. Defaults to 4.

  • size (integer, optional) – The height (in inches) of each plot. Defaults to 6.

  • aspect (integer, optional) – Aspect ratio of each facet in the plot, so that aspect * size gives width of each facet in inches. Defaults to None, which will calculate the aspect based on the x and y dimensions of the input data.

  • savefig_path (string, optional) – Path to export image file for the RGB plot. Defaults to None, which does not export an image file.

  • savefig_kwargs (dict, optional) – A dict of keyword arguments to pass to matplotlib.pyplot.savefig when exporting an image file. For all available options, see: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html

  • **kwargs (optional) – Additional keyword arguments to pass to xarray.plot.imshow(). For example, the function can be used to plot into an existing matplotlib axes object by passing an ax keyword argument. For more options, see: http://xarray.pydata.org/en/stable/generated/xarray.plot.imshow.html

Returns

  • An RGB plot of one or multiple observations, and optionally an image

  • file written to file.

deafrica_tools.plotting.xr_animation(ds, bands=None, output_path='animation.mp4', width_pixels=500, interval=100, percentile_stretch=(0.02, 0.98), image_proc_funcs=None, show_gdf=None, show_date='%d %b %Y', show_text=None, show_colorbar=True, gdf_kwargs={}, annotation_kwargs={}, imshow_kwargs={}, colorbar_kwargs={}, limit=None)

Takes an xarray timeseries and animates the data as either a three-band (e.g. true or false colour) or single-band animation, allowing changes in the landscape to be compared across time.

Animations can be customised to include text and date annotations or use specific combinations of input bands. Vector data can be overlaid and animated on top of imagery, and custom image processing functions can be applied to each frame.

Supports .mp4 (ideal for Twitter/social media) and .gif (ideal for all purposes, but can have large file sizes) format files.

Last modified: October 2020

Parameters
  • ds (xarray.Dataset) – An xarray dataset with multiple time steps (i.e. multiple observations along the time dimension).

  • bands (list of strings) – An list of either one or three band names to be plotted, all of which must exist in ds.

  • output_path (str, optional) – A string giving the output location and filename of the resulting animation. File extensions of ‘.mp4’ and ‘.gif’ are accepted. Defaults to ‘animation.mp4’.

  • width_pixels (int, optional) – An integer defining the output width in pixels for the resulting animation. The height of the animation is set automatically based on the dimensions/ratio of the input xarray dataset. Defaults to 500 pixels wide.

  • interval (int, optional) – An integer defining the milliseconds between each animation frame used to control the speed of the output animation. Higher values result in a slower animation. Defaults to 100 milliseconds between each frame.

  • percentile_stretch (tuple of floats, optional) – An optional tuple of two floats that can be used to clip one or three-band arrays by percentiles to produce a more vibrant, visually attractive image that is not affected by outliers/ extreme values. The default is (0.02, 0.98) which is equivalent to xarray’s robust=True. This parameter is ignored completely if vmin and vmax are provided as kwargs to imshow_kwargs.

  • image_proc_funcs (list of funcs, optional) – An optional list containing functions that will be applied to each animation frame (timestep) prior to animating. This can include image processing functions such as increasing contrast, unsharp masking, saturation etc. The function should take AND return a numpy.ndarray with shape [y, x, bands]. If your function has parameters, you can pass in custom values using a lambda function: image_proc_funcs=[lambda x: custom_func(x, param1=10)].

  • show_gdf (geopandas.GeoDataFrame, optional) – Vector data (e.g. ESRI shapefiles or GeoJSON) can be optionally plotted over the top of imagery by supplying a geopandas.GeoDataFrame object. To customise colours used to plot the vector features, create a new column in the GeoDataFrame called ‘colors’ specifying the colour used to plot each feature: e.g. gdf[‘colors’] = ‘red’. To plot vector features at specific moments in time during the animation, create new ‘start_time’ and/or ‘end_time’ columns in the GeoDataFrame that define the time range used to plot each feature. Dates can be provided in any string format that can be converted using the pandas.to_datetime(). e.g. gdf[‘end_time’] = [‘2001’, ‘2005-01’, ‘2009-01-01’]

  • show_date (string or bool, optional) – An optional string or bool that defines how (or if) to plot date annotations for each animation frame. Defaults to ‘%d %b %Y’; can be customised to any format understood by strftime (https://strftime.org/). Set to False to remove date annotations completely.

  • show_text (str or list of strings, optional) – An optional string or list of strings with a length equal to the number of timesteps in ds. This can be used to display a static text annotation (using a string), or a dynamic title (using a list) that displays different text for each timestep. By default, no text annotation will be plotted.

  • show_colorbar (bool, optional) – An optional boolean indicating whether to include a colourbar for single-band animations. Defaults to True.

  • gdf_kwargs (dict, optional) – An optional dictionary of keyword arguments to customise the appearance of a geopandas.GeoDataFrame supplied to show_gdf. Keyword arguments are passed to GeoSeries.plot (see http://geopandas.org/reference.html#geopandas.GeoSeries.plot). For example: gdf_kwargs = {‘linewidth’: 2}.

  • annotation_kwargs (dict, optional) – An optional dict of keyword arguments for controlling the appearance of text annotations. Keyword arguments are passed to plt.annotate from matplotlib. (see https://matplotlib.org/api/_as_gen/matplotlib.pyplot.annotate.html for options). For example, annotation_kwargs={‘fontsize’:20, ‘color’:’red’, ‘family’:’serif’}.

  • imshow_kwargs (dict, optional) – An optional dict of keyword arguments for controlling the appearance of arrays passed to matplotlib’s plt.imshow (see https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html for options). For example, a green colour scheme and custom stretch could be specified using: onebandplot_kwargs={‘cmap’:’Greens, ‘vmin’:0.2, ‘vmax’:0.9}`. (some parameters like ‘cmap’ will only have an effect for single-band animations, not three-band RGB animations).

  • colorbar_kwargs (dict, optional) – An optional dict of keyword arguments used to control the appearance of the colourbar. Keyword arguments are passed to matplotlib.pyplot.tick_params (see https://matplotlib.org/api/_as_gen/matplotlib.pyplot.tick_params.html for options). This can be used to customise the colourbar ticks, e.g. changing tick label colour depending on the background of the animation: colorbar_kwargs={‘colors’: ‘black’}.

  • limit (int, optional) – An optional integer specifying how many animation frames to render (e.g. limit=50 will render the first 50 frames). This can be useful for quickly testing animations without rendering the entire time-series.