figanos.matplotlib package#

Figanos plotting module.

Submodules#

figanos.matplotlib.plot module#

figanos.matplotlib.plot.gdfmap(df: ~geopandas.geodataframe.GeoDataFrame, df_col: str, ax: ~cartopy.mpl.geoaxes.GeoAxes | None = None, fig_kw: dict[str, ~typing.Any] | None = None, plot_kw: dict[str, ~typing.Any] | None = None, projection: ~cartopy.crs.Projection = <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, features: list[str] | dict[str, dict[str, ~typing.Any]] | None = None, cmap: str | ~matplotlib.colors.Colormap | None = None, levels: int | list[int | float] | None = None, divergent: bool | int | float = False, cbar: bool = True, frame: bool = False) Axes[source]#

Create a map plot from geometries.

Parameters#

dfgeopandas.GeoDataFrame

Dataframe containing the geometries and the data to plot. Must have a column named ‘geometry’.

df_colstr

Name of the column of ‘df’ containing the data to plot using the colorscale.

axcartopy.mpl.geoaxes.GeoAxes or cartopy.mpl.geoaxes.GeoaxesSubplot, optional

Matplotlib axis built with a projection, on which to plot.

fig_kwdict, optional

Arguments to pass to plt.figure().

plot_kwdict, optional

Arguments to pass to the GeoDataFrame.plot() method.

projectionccrs.Projection

The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.

featureslist or dict, optional

Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from cartopy.feature: [‘coastline’, ‘borders’, ‘lakes’, ‘land’, ‘ocean’, ‘rivers’, ‘states’].

cmapmatplotlib.colors.Colormap or str

Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors). If None, look for common variables (from data/ipcc_colors/varaibles_groups.json) in the name of df_col and use corresponding colormap, aligned with the IPCC visual style guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).

levelsint or list, optional

Number of levels or list of level boundaries (in data units) to use to divide the colormap.

divergentbool or int or float

If int or float, becomes center of cmap. Default center is 0.

cbarbool

Show colorbar. Default ‘True’.

framebool

Show or hide frame. Default False.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.gridmap(data: dict[str, ~typing.Any] | ~xarray.core.dataarray.DataArray | ~xarray.core.dataset.Dataset, ax: ~matplotlib.axes._axes.Axes | None = None, use_attrs: dict[str, ~typing.Any] | None = None, fig_kw: dict[str, ~typing.Any] | None = None, plot_kw: dict[str, ~typing.Any] | None = None, projection: ~cartopy.crs.Projection = <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, transform: ~cartopy.crs.Projection | None = None, features: list[str] | dict[str, dict[str, ~typing.Any]] | None = None, geometries_kw: dict[str, ~typing.Any] | None = None, contourf: bool = False, cmap: str | ~matplotlib.colors.Colormap | None = None, levels: int | list | ~numpy.ndarray | None = None, divergent: bool | int | float = False, show_time: bool | str | int | tuple[float, float] = False, frame: bool = False) Axes[source]#

Create map from 2D data.

Parameters#

datadict, DataArray or Dataset

Input data do plot. If dictionary, must have only one entry.

axmatplotlib axis, optional

Matplotlib axis on which to plot, with the same projection as the one specified.

use_attrsdict, optional

Dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’, ‘cbar_label’: ‘long_name’, ‘cbar_units’: ‘units’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.figure().

plot_kw: dict, optional

Arguments to pass to the xarray.plot.pcolormesh() or ‘xarray.plot.contourf()’ function.

projectionccrs.Projection

The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.

transformccrs.Projection, optional

Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching ccrs.PlateCarree() or ccrs.RotatedPole().

featureslist or dict, optional

Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from cartopy.feature: [‘coastline’, ‘borders’, ‘lakes’, ‘land’, ‘ocean’, ‘rivers’, ‘states’].

geometries_kwdict, optional

Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.

contourfbool

By default False, use plt.pcolormesh(). If True, use plt.contourf().

cmapmatplotlib.colors.Colormap or str, optional

Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors). If None, look for common variables (from data/ipcc_colors/varaibles_groups.json) in the name of the DataArray or its ‘history’ attribute and use corresponding colormap, aligned with the IPCC visual style guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).

levelsint, list, np.ndarray, optional

Number of levels to divide the colormap into or list of level boundaries (in data units).

divergentbool or int or float

If int or float, becomes center of cmap. Default center is 0.

show_timebool, tuple, string or int.

If True, show time (as date) at the bottom right of the figure. Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location of the text. If a string or an int, the same values as those of the ‘loc’ parameter of matplotlib’s legends are accepted.

Location String

Location Code

‘upper right’

1

‘upper left’

2

‘lower left’

3

‘lower right’

4

‘right’

5

‘center left’

6

‘center right’

7

‘lower center’

8

‘upper center’

9

‘center’

10

framebool

Show or hide frame. Default False.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.hatchmap(data: dict[str, ~typing.Any] | ~xarray.core.dataarray.DataArray | ~xarray.core.dataset.Dataset, ax: ~matplotlib.axes._axes.Axes | None = None, use_attrs: dict[str, ~typing.Any] | None = None, fig_kw: dict[str, ~typing.Any] | None = None, plot_kw: dict[str, ~typing.Any] | None = None, projection: ~cartopy.crs.Projection = <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, transform: ~cartopy.crs.Projection | None = None, features: list[str] | dict[str, dict[str, ~typing.Any]] | None = None, geometries_kw: dict[str, ~typing.Any] | None = None, levels: int | None = None, legend_kw: dict[str, ~typing.Any] | None = None, show_time: bool | str | int | tuple[float, float] = False, frame: bool = False) Axes[source]#

Create map of hatches from 2D data.

Parameters#

datadict, DataArray or Dataset

Input data do plot.

axmatplotlib axis, optional

Matplotlib axis on which to plot, with the same projection as the one specified.

use_attrsdict, optional

Dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.figure().

plot_kw: dict, optional

Arguments to pass to ‘xarray.plot.contourf()’ function. If ‘data’ is a dictionary, can be a nested dictionary with the same keys as ‘data’.

projectionccrs.Projection

The projection to use, taken from the cartopy.ccrs options. Ignored if ax is not None.

transformccrs.Projection, optional

Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching ccrs.PlateCarree() or ccrs.RotatedPole().

featureslist or dict, optional

Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from cartopy.feature: [‘coastline’, ‘borders’, ‘lakes’, ‘land’, ‘ocean’, ‘rivers’, ‘states’].

geometries_kwdict, optional

Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.

legend_kwdict, optional

Arguments to pass to ax.legend().

show_timebool, tuple, string or int.

If True, show time (as date) at the bottom right of the figure. Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location of the text. If a string or an int, the same values as those of the ‘loc’ parameter of matplotlib’s legends are accepted.

Location String

Location Code

‘upper right’

1

‘upper left’

2

‘lower left’

3

‘lower right’

4

‘right’

5

‘center left’

6

‘center right’

7

‘lower center’

8

‘upper center’

9

‘center’

10

framebool

Show or hide frame. Default False.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.heatmap(data: DataArray | Dataset | dict[str, Any], ax: Axes | None = None, use_attrs: dict[str, Any] | None = None, fig_kw: dict[str, Any] | None = None, plot_kw: dict[str, Any] | None = None, transpose: bool = False, cmap: str | Colormap | None = 'RdBu', divergent: bool | int | float = False) Axes[source]#

Create heatmap from a DataArray.

Parameters#

datadict or DataArray or Dataset

Input data do plot. If dictionary, must have only one entry.

axmatplotlib axis, optional

Matplotlib axis on which to plot, with the same projection as the one specified.

use_attrsdict, optional

Dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘cbar_label’: ‘long_name’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.figure().

plot_kwdict, optional

Arguments to pass to the ‘seaborn.heatmap()’ function. If ‘data’ is a dictionary, can be a nested dictionary with the same key as ‘data’.

transposebool

If true, the 2D data will be transposed, so that the original x-axis becomes the y-axis and vice versa.

cmapmatplotlib.colors.Colormap or str, optional

Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors). If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray or its ‘history’ attribute and use corresponding colormap, aligned with the IPCC Visual Style Guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).

divergentbool or int or float

If int or float, becomes center of cmap. Default center is 0.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.partition(data: DataArray | Dataset, ax: Axes | None = None, start_year: str | None = None, show_num: bool = True, fill_kw: dict[str, Any] | None = None, line_kw: dict[str, Any] | None = None, fig_kw: dict[str, Any] | None = None, legend_kw: dict[str, Any] | None = None) Axes[source]#

Figure of the partition of total uncertainty by components.

Uncertainty fractions can be computed with xclim (https://xclim.readthedocs.io/en/stable/api.html#uncertainty-partitioning). Make sure the use fraction=True in the xclim function call.

Parameters#

data: xr.DataArray or xr.Dataset

Variance over time of the different components of uncertainty. Output of a xclim.ensembles._partitioning function.

axmatplotlib axis, optional

Matplotlib axis on which to plot

start_year: str

If None, the x-axis will be the time in year. If str, the x-axis will show the number of year since start_year.

show_num: bool

If True, show the number of elements for each uncertainty components in parenthesis in the legend. data should have attributes named after the components with a list its the elements.

fill_kw: dict

Keyword arguments passed to ax.fill_between. It is possible to pass a dictionary of keywords for each component (uncertainty coordinates).

line_kw: dict

Keyword arguments passed to ax.plot for the lines in between the components. The default is {color=”k”, lw=2}. We recommend always using lw>=2.

fig_kw: dict

Keyword arguments passed to plt.subplots.

legend_kw: dict

Keyword arguments passed to ax.legend.

Returns#

mpl.axes.Axes

figanos.matplotlib.plot.scattermap(data: dict[str, ~typing.Any] | ~xarray.core.dataarray.DataArray | ~xarray.core.dataset.Dataset, ax: ~matplotlib.axes._axes.Axes | None = None, use_attrs: dict[str, ~typing.Any] | None = None, fig_kw: dict[str, ~typing.Any] | None = None, plot_kw: dict[str, ~typing.Any] | None = None, projection: ~cartopy.crs.Projection = <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, transform: ~cartopy.crs.Projection | None = <Projected CRS: +proj=eqc +ellps=WGS84 +a=6378137.0 +lon_0=0.0 +to ...> Name: unknown Axis Info [cartesian]: - E[east]: Easting (unknown) - N[north]: Northing (unknown) - h[up]: Ellipsoidal height (metre) Area of Use: - undefined Coordinate Operation: - name: unknown - method: Equidistant Cylindrical Datum: Unknown based on WGS 84 ellipsoid - Ellipsoid: WGS 84 - Prime Meridian: Greenwich, features: list[str] | dict[str, dict[str, ~typing.Any]] | None = None, geometries_kw: dict[str, ~typing.Any] | None = None, sizes: str | bool | None = None, size_range: tuple = (10, 60), cmap: str | ~matplotlib.colors.Colormap | None = None, levels: int | None = None, divergent: bool | int | float = False, legend_kw: dict[str, ~typing.Any] | None = None, show_time: bool | str | int | tuple[float, float] = False, frame: bool = False) Axes[source]#

Make a scatter plot of georeferenced data on a map.

Parameters#

datadict, DataArray or Dataset

Input data do plot. If dictionary, must have only one entry.

axmatplotlib axis, optional

Matplotlib axis on which to plot, with the same projection as the one specified.

use_attrsdict, optional

Dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’, ‘cbar_label’: ‘long_name’, ‘cbar_units’: ‘units’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.figure().

plot_kwdict, optional

Arguments to pass to plt.scatter(). If ‘data’ is a dictionary, can be a dictionary with the same key as ‘data’.

projectionccrs.Projection

The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.

transformccrs.Projection, optional

Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching ccrs.PlateCarree() or ccrs.RotatedPole().

featureslist or dict, optional

Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from cartopy.feature: [‘coastline’, ‘borders’, ‘lakes’, ‘land’, ‘ocean’, ‘rivers’, ‘states’].

geometries_kwdict, optional

Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.

sizesbool or str, optional

String name of the coordinate to use for determining point size. If True, use the same data as in the colorbar.

size_rangetuple

Tuple of the minimum and maximum size of the points.

cmapmatplotlib.colors.Colormap or str, optional

Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors). If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray or its ‘history’ attribute and use corresponding colormap, aligned with the IPCC Visual Style Guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).

levelsint, optional

Number of levels to divide the colormap into.

divergentbool or int or float

If int or float, becomes center of cmap. Default center is 0.

legend_kwdict, optional
Arguments to pass to plt.legend(). Some defaults {“loc”: “lower left”, “facecolor”: “w”, “framealpha”: 1,

“edgecolor”: “w”, “bbox_to_anchor”: (-0.05, 0)}

show_timebool, tuple, string or int.

If True, show time (as date) at the bottom right of the figure. Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location of the text. If a string or an int, the same values as those of the ‘loc’ parameter of matplotlib’s legends are accepted.

Location String

Location Code

‘upper right’

1

‘upper left’

2

‘lower left’

3

‘lower right’

4

‘right’

5

‘center left’

6

‘center right’

7

‘lower center’

8

‘upper center’

9

‘center’

10

framebool

Show or hide frame. Default False.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.stripes(data: dict[str, Any] | DataArray | Dataset, ax: Axes | None = None, fig_kw: dict[str, Any] | None = None, divide: int | None = None, cmap: str | Colormap | None = None, cmap_center: int | float = 0, cbar: bool = True, cbar_kw: dict[str, Any] | None = None) Axes[source]#

Create stripes plot with or without multiple scenarios.

Parameters#

datadict or DataArray or Dataset

Data to plot. If a dictionary of xarray objects, each will correspond to a scenario.

axmatplotlib.axes.Axes, optional

Matplotlib axis on which to plot.

fig_kw: dict, optional

Arguments to pass to plt.subplots(). Only works if ax is not provided.

divideint, optional

Year at which the plot is divided into scenarios. If not provided, the horizontal separators will extend over the full time axis.

cmapmatplotlib.colors.Colormap or str, optional

Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors). If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray or its ‘history’ attribute and use corresponding diverging colormap, aligned with the IPCC Visual Style Guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).

cmap_centerint or float

Center of the colormap in data coordinates. Default is 0.

cbarbool

Show colorbar.

cbar_kwdict, optional

Arguments to pass to plt.colorbar.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.taylordiagram(data: DataArray | dict[str, DataArray], plot_kw: dict[str, Any] | None = None, fig_kw: dict[str, Any] | None = None, std_range: tuple = (0, 1.5), contours: int | None = 4, contours_kw: dict[str, Any] | None = None, legend_kw: dict[str, Any] | None = None, std_label: str | None = None, corr_label: str | None = None)[source]#

Build a Taylor diagram.

Based on the following code: https://gist.github.com/ycopin/3342888.

Parameters#

dataxr.DataArray or dict

DataArray or dictionary of DataArrays created by xclim.sdba.measures.taylordiagram, each corresponding to a point on the diagram. The dictionary keys will become their labels.

plot_kwdict, optional

Arguments to pass to the plot() function. Changes how the markers look. If ‘data’ is a dictionary, must be a nested dictionary with the same keys as ‘data’.

fig_kwdict, optional

Arguments to pass to plt.figure().

std_rangetuple

Range of the x and y axes, in units of the highest standard deviation in the data.

contoursint, optional

Number of rsme contours to plot.

contours_kwdict, optional

Arguments to pass to plt.contour() for the rmse contours.

legend_kwdict, optional

Arguments to pass to plt.legend().

std_labelstr, optional

Label for the standard deviation (x and y) axes.

corr_labelstr, optional

Label for the correlation axis.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.timeseries(data: dict[str, Any] | DataArray | Dataset, ax: Axes | None = None, use_attrs: dict[str, Any] | None = None, fig_kw: dict[str, Any] | None = None, plot_kw: dict[str, Any] | None = None, legend: str = 'lines', show_lat_lon: bool | str | int | tuple[float, float] = True) Axes[source]#

Plot time series from 1D Xarray Datasets or DataArrays as line plots.

Parameters#

datadict or Dataset/DataArray

Input data to plot. It can be a DataArray, Dataset or a dictionary of DataArrays and/or Datasets.

axmatplotlib.axes.Axes, optional

Matplotlib axis on which to plot.

use_attrsdict, optional

A dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’, ‘ylabel’: ‘long_name’, ‘yunits’: ‘units’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.subplots(). Only works if ax is not provided.

plot_kwdict, optional

Arguments to pass to the plot() function. Changes how the line looks. If ‘data’ is a dictionary, must be a nested dictionary with the same keys as ‘data’.

legendstr (default ‘lines’) or dict
‘full’ (lines and shading), ‘lines’ (lines only), ‘in_plot’ (end of lines),

‘edge’ (out of plot), ‘facetgrid’ under figure, ‘none’ (no legend). If dict, arguments to pass to ax.legend().

show_lat_lonbool, tuple, str or int

If True, show latitude and longitude at the bottom right of the figure. Can be a tuple of axis coordinates (from 0 to 1, as a fraction of the axis length) representing the location of the text. If a string or an int, the same values as those of the ‘loc’ parameter of matplotlib’s legends are accepted.

Location String

Location Code

‘upper right’

1

‘upper left’

2

‘lower left’

3

‘lower right’

4

‘right’

5

‘center left’

6

‘center right’

7

‘lower center’

8

‘upper center’

9

‘center’

10

Returns#

matplotlib.axes.Axes

figanos.matplotlib.plot.violin(data: dict[str, Any] | DataArray | Dataset, ax: Axes | None = None, use_attrs: dict[str, Any] | None = None, fig_kw: dict[str, Any] | None = None, plot_kw: dict[str, Any] | None = None, color: str | int | list[str | int] | None = None) Axes[source]#

Make violin plot using seaborn.

Parameters#

datadict or Dataset/DataArray

Input data to plot. If a dict, must contain DataArrays and/or Datasets.

axmatplotlib.axes.Axes, optional

Matplotlib axis on which to plot.

use_attrsdict, optional

A dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’, ‘ylabel’: ‘long_name’, ‘yunits’: ‘units’}. Only the keys found in the default dict can be used.

fig_kwdict, optional

Arguments to pass to plt.subplots(). Only works if ax is not provided.

plot_kwdict, optional

Arguments to pass to the seaborn.violinplot() function.

colorstr, int or list, optional

Unique color or list of colors to use. Integers point to the applied stylesheet’s colors, in zero-indexed order. Passing ‘color’ or ‘palette’ in plot_kw overrides this argument.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.utils module#

Utility functions for figanos figure-creation.

figanos.matplotlib.utils.TERMS: dict = {'correlation': {'fr': 'corrélation'}, 'min-max range': {'fr': 'intervalle min-max'}, 'pearson correlation': {'fr': 'corrélation de Pearson'}, 'reference': {'fr': 'référence'}, 'standard deviation': {'fr': 'écart-type'}, 'time': {'fr': 'temps'}, '{}th-{}th percentiles': {'fr': '{}e-{}e centiles'}}#

A translation directory for special terms to appear on the plots.

Keys are terms to translate and they map to “locale”: “translation” dictionaries. The “official” figanos terms are based on figanos/data/terms.yml.

figanos.matplotlib.utils.add_cartopy_features(ax: Axes, features: list[str] | dict[str, dict[str, Any]]) Axes[source]#

Add cartopy features to matplotlib axes.

Parameters#

axmatplotlib.axes.Axes

The axes on which to add the features.

featureslist or dict

List of features, or nested dictionary of format {‘feature’: {‘kwarg’:’value’}}

Returns#

matplotlib.axes.Axes

The axis with added features.

figanos.matplotlib.utils.add_features_map(data, ax, use_attrs, projection, features, geometries_kw, frame) Axes[source]#

Add features such as cartopy, time label, and geometries to a map on a given matplotlib axis.

Parameters#

datadict, DataArray or Dataset

Input data do plot. If dictionary, must have only one entry.

axmatplotlib axis

Matplotlib axis on which to plot, with the same projection as the one specified.

use_attrsdict

Dict linking a plot element (key, e.g. ‘title’) to a DataArray attribute (value, e.g. ‘Description’). Default value is {‘title’: ‘description’, ‘cbar_label’: ‘long_name’, ‘cbar_units’: ‘units’}. Only the keys found in the default dict can be used.

projectionccrs.Projection

The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.

featureslist or dict

Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from cartopy.feature: [‘coastline’, ‘borders’, ‘lakes’, ‘land’, ‘ocean’, ‘rivers’, ‘states’].

geometries_kwdict

Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.

framebool

Show or hide frame. Default False.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.utils.categorical_colors() dict[str, str][source]#

Get a list of the categorical colors associated with certain substrings (SSP,RCP,CMIP).

figanos.matplotlib.utils.check_timeindex(xr_objs: DataArray | Dataset | dict[str, Any]) DataArray | Dataset | dict[str, Any][source]#

Check if the time index of Xarray objects in a dict is CFtime and convert to pd.DatetimeIndex if True.

Parameters#

xr_objsxr.DataArray or xr.Dataset or dict

Dictionary containing Xarray DataArrays or Datasets.

Returns#

xr.DataArray or xr.Dataset or dict

Dictionary of xarray objects with a pandas DatetimeIndex

figanos.matplotlib.utils.convert_scen_name(name: str) str[source]#

Convert strings containing SSP, RCP or CMIP to their proper format.

figanos.matplotlib.utils.create_cmap(var_group: str | None = None, divergent: bool | int = False, filename: str | None = None) Colormap[source]#

Create colormap according to variable group.

Parameters#

var_groupstr, optional

Variable group from IPCC scheme.

divergentbool or int

Diverging colormap. If False, use sequential colormap.

filenamestr, optional

Name of IPCC colormap file. If not None, ‘var_group’ and ‘divergent’ are not used.

Returns#

matplotlib.colors.Colormap

figanos.matplotlib.utils.custom_cmap_norm(cmap, vmin: int | float, vmax: int | float, levels: int | list[int | float] | None = None, divergent: bool | int | float = False, linspace_out: bool = False) Normalize | ndarray[source]#

Get matplotlib normalization according to main function arguments.

Parameters#

cmap: matplotlib.colormap

Colormap to be used with the normalization.

vmin: int or float

Minimum of the data to be plotted with the colormap.

vmax: int or float

Maximum of the data to be plotted with the colormap.

levelsint or list, optional

Number of levels or list of level boundaries (in data units) to use to divide the colormap.

divergentbool or int or float

If int or float, becomes center of cmap. Default center is 0.

linspace_out: bool

If True, return array created by np.linspace() instead of normalization instance.

Returns#

matplotlib.colors.Normalize

figanos.matplotlib.utils.empty_dict(param) dict[source]#

Return empty dict if input is None.

figanos.matplotlib.utils.fill_between_label(sorted_lines: dict[str, Any], name: str, array_categ: dict[str, Any], legend: str) str[source]#

Create a label for the shading around a line in line plots.

Parameters#

sorted_linesdict

Dictionary created by the sort_lines() function.

namestr

Key associated with the object being plotted in the ‘data’ argument of the timeseries() function.

array_categdict

The categories of the array, as created by the get_array_categ function.

legendstr

Legend mode.

Returns#

str

Label to be applied to the legend element representing the shading.

Read a logo file.

figanos.matplotlib.utils.get_array_categ(array: DataArray | Dataset) str[source]#

Get an array category, which determines how to plot the array.

Parameters#

arrayDataset or DataArray

The array being categorized.

Returns#

str

ENS_PCT_VAR_DS: ensemble percentiles stored as variables ENS_PCT_DIM_DA: ensemble percentiles stored as dimension coordinates, DataArray ENS_PCT_DIM_DS: ensemble percentiles stored as dimension coordinates, DataSet ENS_STATS_VAR_DS: ensemble statistics (min, mean, max) stored as variables ENS_REALS_DA: ensemble with ‘realization’ dim, as DataArray ENS_REALS_DS: ensemble with ‘realization’ dim, as Dataset DS: any Dataset that is not recognized as an ensemble DA: DataArray

figanos.matplotlib.utils.get_attributes(string: str, xr_obj: DataArray | Dataset, locale: str | None = None) str[source]#

Fetch attributes or dims corresponding to keys from Xarray objects.

Searches DataArray attributes first, then the first variable (DataArray) of the Dataset, then Dataset attributes. If a locale is activated in xclim’s options or a locale is passed, a localized version is given if available.

Parameters#

stringstr

String corresponding to an attribute name.

xr_objDataArray or Dataset

The Xarray object containing the attributes.

localestr, optional

A 2-letter locale name to translate to. Default is None, which will pull the locale from xclim’s “metadata_locales” option (taking the first).

Returns#

str

Xarray attribute value as string or empty string if not found

figanos.matplotlib.utils.get_localized_term(term, locale=None)[source]#

Get term translated into locale.

Terms are pulled from the TERMS dictionary.

Parameters#

termstr

A word or short phrase to translate.

localestr, optional

A 2-letter locale name to translate to. Default is None, which will pull the locale from xclim’s “metadata_locales” option (taking the first).

Return#

str : Translated term.

figanos.matplotlib.utils.get_mpl_styles() dict[str, str][source]#

Get the available matplotlib styles and their paths, as a dictionary.

figanos.matplotlib.utils.get_rotpole(xr_obj: DataArray | Dataset) RotatedPole | None[source]#

Create a Cartopy crs rotated pole projection/transform from DataArray or Dataset attributes.

Parameters#

xr_objxr.DataArray or xr.Dataset

The xarray object from which to look for the attributes.

Returns#

ccrs.RotatedPole or None

figanos.matplotlib.utils.get_scen_color(name: str, path_to_dict: str | Path) str[source]#

Get color corresponding to SSP,RCP, model or CMIP substring from a dictionary.

figanos.matplotlib.utils.get_suffix(string: str) str[source]#

Get suffix of typical Xclim variable names.

figanos.matplotlib.utils.get_var_group(path_to_json: str | Path, da: DataArray | None = None, unique_str: str | None = None) str[source]#

Get IPCC variable group from DataArray or a string using a json file (figanos/data/ipcc_colors/variable_groups.json).

If da is a Dataset, look in the DataArray of the first variable.

figanos.matplotlib.utils.gpd_to_ccrs(df: GeoDataFrame, proj: CRS) GeoDataFrame[source]#

Open shapefile with geopandas and convert to cartopy projection.

Parameters#

dfgpd.GeoDataFrame

GeoDataFrame (geopandas) geometry to be added to axis.

projccrs.CRS

Projection to use, taken from the cartopy.crs options.

Returns#

gpd.GeoDataFrame

GeoDataFrame adjusted to given projection

figanos.matplotlib.utils.load_image(im: str | Path, height: float | None, width: float | None, keep_ratio: bool = True) ndarray[source]#

Scale an image to a specified height and width.

Parameters#

imstr or Path

The image to be scaled. PNG and SVG formats are supported.

heightfloat, optional

The desired height of the image. If None, the original height is used.

widthfloat, optional

The desired width of the image. If None, the original width is used.

keep_ratiobool

If True, the aspect ratio of the original image is maintained. Default is True.

Returns#

np.ndarray

The scaled image.

figanos.matplotlib.utils.loc_mpl(loc: str | tuple[int | float, int | float] | int) tuple[tuple[float, float], tuple[int | float, int | float], str, str][source]#

Find coordinates and alignment associated to loc string.

Parameters#

locstring, int, or tuple[float, float]

Location of text, replicating https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html. If a tuple, must be in axes coordinates.

Returns#

tuple(float, float), tuple(float, float), str, str

figanos.matplotlib.utils.masknan_sizes_key(data, sizes) Dataset[source]#

Mask the np.Nan values between variables used to plot hue and markersize in xr.plot.scatter().

Parameters#

data: xr.Dataset

xr.Dataset used to plot

sizes: str

Variable used to plot markersize

Returns#

xr.Dataset

figanos.matplotlib.utils.norm2range(data: ndarray, target_range: tuple, data_range: tuple | None = None) ndarray[source]#

Normalize data across a specific range.

figanos.matplotlib.utils.plot_coords(ax: Axes | None, xr_obj: DataArray | Dataset, loc: str | tuple[float, float] | int, param: str | None = None, backgroundalpha: float = 1) Axes[source]#

Place coordinates on plot area.

Parameters#

axmatplotlib.axes.Axes or None

Matplotlib axes object on which to place the text. If None, will use plt.figtext instead (should be used for facetgrids).

xr_objxr.DataArray or xr.Dataset

The xarray object from which to fetch the text content.

param{“location”, “time”}, optional

The parameter used.

locstring, int or tuple

Location of text, replicating https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html. If a tuple, must be in axes coordinates.

backgroundalphafloat

Transparency of the text background. 1 is opaque, 0 is transparent.

Returns#

matplotlib.axes.Axes

Place logo of plot area.

Parameters#

axmatplotlib.axes.Axes

Matplotlib axes object on which to place the text.

locstring, int or tuple

Location of text, replicating https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html. If a tuple, must be in axes coordinates.

logostr, Path, figanos.Logos, optional

A name (str) or Path to a logo file, or a name of an already-installed logo. If an existing is not found, the logo will be installed and accessible via the filename. The default logo is the Figanos logo. To install the Ouranos (or another) logo consult the Usage page. The logo must be in ‘png’ format.

heightfloat, optional

The desired height of the image. If None, the original height is used.

widthfloat, optional

The desired width of the image. If None, the original width is used.

keep_ratiobool, optional

If True, the aspect ratio of the original image is maintained. Default is True.

**offset_image_kwargs

Arguments to pass to matplotlib.offsetbox.OffsetImage().

Returns#

matplotlib.axes.Axes

figanos.matplotlib.utils.process_keys(dct: dict[str, Any], func: Callable) dict[str, Any][source]#

Apply function to dictionary keys.

figanos.matplotlib.utils.set_mpl_style(*args: str, reset: bool = False) None[source]#

Set the matplotlib style using one or more stylesheets.

Parameters#

argsstr

Name(s) of figanos matplotlib style (‘ouranos’, ‘paper, ‘poster’) or path(s) to matplotlib stylesheet(s).

resetbool

If True, reset style to matplotlib default before applying the stylesheets.

Returns#

None

figanos.matplotlib.utils.set_plot_attrs(attr_dict: dict[str, Any], xr_obj: DataArray | Dataset, ax: Axes | None = None, title_loc: str = 'center', facetgrid: FacetGrid | None = None, wrap_kw: dict[str, Any] | None = None) Axes[source]#

Set plot elements according to Dataset or DataArray attributes.

Uses get_attributes() to check for and get the string.

Parameters#

attr_dictdict

Dictionary containing specified attribute keys.

xr_objDataset or DataArray

The Xarray object containing the attributes.

axmatplotlib axis

The matplotlib axis of the plot.

title_locstr

Location of the title.

wrap_kwdict, optional

Arguments to pass to the wrap_text function for the title.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.utils.size_legend_elements(data: ndarray, sizes: ndarray, marker: str, max_entries: int = 6) list[Line2D][source]#

Create handles to use in a point-size legend.

Parameters#

datanp.ndarray

Data used to determine the point sizes.

sizesnp.ndarray

Array of point sizes.

max_entriesint

Maximum number of entries in the legend.

marker: str

Marker to use in legend.

Returns#

list of matplotlib.lines.Line2D

figanos.matplotlib.utils.sort_lines(array_dict: dict[str, Any]) dict[str, str][source]#

Label arrays as ‘middle’, ‘upper’ and ‘lower’ for ensemble plotting.

Parameters#

array_dictdict

Dictionary of format {‘name’: array…}.

Returns#

dict

Dictionary of {‘middle’: ‘name’, ‘upper’: ‘name’, ‘lower’: ‘name’}.

figanos.matplotlib.utils.split_legend(ax: Axes, in_plot: bool = False, axis_factor: float = 0.15, label_gap: float = 0.02) Axes[source]#

Draw line labels at the end of each line, or outside the plot.

Parameters#

axmatplotlib.axes.Axes

The axis containing the legend.

in_plotbool

If True, prolong plot area to fit labels. If False, print labels outside of plot area. Default: False.

axis_factorfloat

If in_plot is True, fraction of the x-axis length to add at the far right of the plot. Default: 0.15.

label_gapfloat

If in_plot is True, fraction of the x-axis length to add as a gap between line and label. Default: 0.02.

Returns#

matplotlib.axes.Axes

figanos.matplotlib.utils.wrap_text(text: str, min_line_len: int = 18, max_line_len: int = 30) str[source]#

Wrap text.

Arguments#

textstr

The text to wrap.

min_line_lenint

Minimum length of each line.

max_line_lenint

Maximum length of each line.

Returns#

str

Wrapped text