dea_tools.plotting

Plotting and animating Digital Earth Australia products and 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 Australia 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 Discord chat (https://discord.com/invite/4hhBQVas5U) 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: GeoscienceAustralia/dea-notebooks#new

Last modified: April 2023

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.

plot_fmask(fmask[, legend])

Plot an enumerated FMask flag image with human-readable colours.

plot_variable_images(img_collection)

Plot a dynamic number of images from a xarray dataset that includes Date and Index in the title.

plot_wo(wo[, legend])

Plot a water observation bit flag image.

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

Takes an xarray dataset and plots RGB images using three imagery bands (e.g ['nbart_red', 'nbart_green', 'nbart_blue']).

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

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.

dea_tools.plotting.display_map(x, y, crs='EPSG:4326', margin=-0.5, zoom_bias=0)[source]

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: February 2023

Modified from function written by Otto Wagner available here: ceos-seo/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.

dea_tools.plotting.plot_fmask(fmask, legend=True, **plot_kwargs)[source]

Plot an enumerated FMask flag image with human-readable colours.

Parameters:
  • fmask (xr.DataArray) – A DataArray containing Fmask flags.

  • legend (bool) – Whether to plot a legend. Default True.

  • plot_kwargs (dict) – Keyword arguments passed on to DataArray.plot.

Return type:

plot

dea_tools.plotting.plot_variable_images(img_collection)[source]

Plot a dynamic number of images from a xarray dataset that includes Date and Index in the title. Optional ability to also include the sensor in the title if a ‘sensor’ attribute is added to the dataset using dataset.assign_attrs :param img_collection: A Dataset containing imagery with RBG bands :type img_collection: xr.Dataset

Return type:

plot

dea_tools.plotting.plot_wo(wo, legend=True, **plot_kwargs)[source]

Plot a water observation bit flag image.

Parameters:
  • wo (xr.DataArray) – A DataArray containing water observation bit flags.

  • legend (bool) – Whether to plot a legend. Default True.

  • plot_kwargs (dict) – Keyword arguments passed on to DataArray.plot.

Return type:

plot

dea_tools.plotting.rgb(ds, bands=['nbart_red', 'nbart_green', 'nbart_blue'], index=None, index_dim='time', robust=True, percentile_stretch=None, col_wrap=4, size=6, aspect=None, titles=None, savefig_path=None, savefig_kwargs={}, **kwargs)[source]

Takes an xarray dataset and plots RGB images using three imagery bands (e.g [‘nbart_red’, ‘nbart_green’, ‘nbart_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: September 2020

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 ‘[‘nbart_red’, ‘nbart_green’, ‘nbart_blue’]’.

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

  • titles (string or list of strings, optional) – Replace the xarray ‘time’ dimension on plot titles with a string or list of string titles, when a list of index values are provided, of your choice. Defaults to None.

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

dea_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)[source]

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: April 2023

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 matplotlib’s plt.annotate (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.