• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Ouranosinc / figanos / 13903624835

17 Mar 2025 03:40PM UTC coverage: 8.111% (-0.01%) from 8.124%
13903624835

push

github

web-flow
fix get_rotpole (#308)

<!-- Please ensure the PR fulfills the following requirements! -->
<!-- If this is your first PR, make sure to add your details to the
AUTHORS.rst! -->
### Pull Request Checklist:
- [ ] This PR addresses an already opened issue (for bug fixes /
features)
  - This PR fixes #xyz
- [ ] (If applicable) Documentation has been added / updated (for bug
fixes / features).
- [ ] (If applicable) Tests have been added.
- [x] CHANGELOG.rst has been updated (with summary of main changes).
- [x] Link to issue (:issue:`number`) and pull request (:pull:`number`)
has been added.

### What kind of change does this PR introduce?

* Instead of assuming the information for rotated pole is in
`rotated_pole`, use the `grid_mapping` attrs to guess the name. Inspired
by `xscen.spatial.get_grid_mapping`.
* small fix in the doc also

### Does this PR introduce a breaking change?
no

### Other information:
This is useful for the CRCM5 which uses the attr `crs`. It was decided
in the Outils Communs meeting that we would change the code, not the
data.

Note that another way to get this information is :

```
ds.cf.grid_mapping_names # Mapping grid mapping type -> [ nom_de_la_var ]
ds[DATAVAR].cf.grid_mapping_name  # Nom du type de grid mapping
# donc pour obtenir la variable contenant les informations
# sur le grid mapping de la variable DATAVAR: 
ds[ds.cf.grid_mapping_names[ds[DATAVAR].cf.grid_mapping_name][0]]
```
but this doesn't work if you only have a DataArray.

Is it worth it to add this also in the case where we have a ds without
at `grid_mapping` attrs but the right cf.attrs ? Does that even happen ?

0 of 9 new or added lines in 2 files covered. (0.0%)

1 existing line in 1 file now uncovered.

155 of 1911 relevant lines covered (8.11%)

0.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

3.66
/src/figanos/matplotlib/plot.py
1
# noqa: D100
2
from __future__ import annotations
6✔
3

4
import copy
6✔
5
import logging
6✔
6
import math
6✔
7
import string
6✔
8
import warnings
6✔
9
from collections.abc import Iterable
6✔
10
from inspect import signature
6✔
11
from pathlib import Path
6✔
12
from typing import Any
6✔
13

14
import cartopy.mpl.geoaxes
6✔
15
import geopandas as gpd
6✔
16
import matplotlib
6✔
17
import matplotlib.axes
6✔
18
import matplotlib.cm
6✔
19
import matplotlib.colors
6✔
20
import matplotlib.pyplot as plt
6✔
21
import mpl_toolkits.axisartist.grid_finder as gf
6✔
22
import numpy as np
6✔
23
import pandas as pd
6✔
24
import seaborn as sns
6✔
25
import xarray as xr
6✔
26
from cartopy import crs as ccrs
6✔
27
from matplotlib.cm import ScalarMappable
6✔
28
from matplotlib.lines import Line2D
6✔
29
from matplotlib.projections import PolarAxes
6✔
30
from matplotlib.tri import Triangulation
6✔
31
from mpl_toolkits.axisartist.floating_axes import FloatingSubplot, GridHelperCurveLinear
6✔
32

33
from figanos.matplotlib.utils import (  # masknan_sizes_key,
6✔
34
    add_cartopy_features,
35
    add_features_map,
36
    check_timeindex,
37
    convert_scen_name,
38
    create_cmap,
39
    custom_cmap_norm,
40
    empty_dict,
41
    fill_between_label,
42
    get_array_categ,
43
    get_attributes,
44
    get_localized_term,
45
    get_rotpole,
46
    get_scen_color,
47
    get_var_group,
48
    gpd_to_ccrs,
49
    norm2range,
50
    plot_coords,
51
    process_keys,
52
    set_plot_attrs,
53
    size_legend_elements,
54
    sort_lines,
55
    split_legend,
56
    wrap_text,
57
)
58

59
logger = logging.getLogger(__name__)
6✔
60

61

62
def _plot_realizations(
6✔
63
    ax: matplotlib.axes.Axes,
64
    da: xr.DataArray,
65
    name: str,
66
    plot_kw: dict[str, Any],
67
    non_dict_data: dict[str, Any],
68
) -> matplotlib.axes.Axes:
69
    """Plot realizations from a DataArray, inside or outside a Dataset.
70

71
    Parameters
72
    ----------
73
    ax : matplotlib.axes.Axes
74
        The Matplotlib axis object.
75
    da : DataArray
76
        The DataArray containing the realizations.
77
    name : str
78
        The label to be used in the first part of a composite label.
79
        Can be the name of the parent Dataset or that of the DataArray.
80
    plot_kw : dict
81
        Dictionary of kwargs coming from the timeseries() input.
82
    non_dict_data : dict
83
        TBD.
84

85
    Returns
86
    -------
87
    matplotlib.axes.Axes
88
    """
89
    ignore_label = False
×
90

91
    for r in da.realization.values:
×
92
        if plot_kw[name]:  # if kwargs (all lines identical)
×
93
            if not ignore_label:  # if label not already in legend
×
94
                label = "" if non_dict_data is True else name
×
95
                ignore_label = True
×
96
            else:
97
                label = ""
×
98
        else:
99
            label = str(r) if non_dict_data is True else (name + "_" + str(r))
×
100

101
        ax.plot(
×
102
            da.sel(realization=r)["time"],
103
            da.sel(realization=r).values,
104
            label=label,
105
            **plot_kw[name],
106
        )
107

108
    return ax
×
109

110

111
def _plot_timeseries(
6✔
112
    ax: matplotlib.axes.Axes,
113
    name: str,
114
    arr: xr.DataArray | xr.Dataset,
115
    plot_kw: dict[str, Any],
116
    non_dict_data: bool,
117
    array_categ: dict[str, Any],
118
    legend: str,
119
) -> matplotlib.axes.Axes:
120
    """Plot figanos timeseries.
121

122
    Parameters
123
    ----------
124
    ax: matplotlib.axes.Axes
125
        Axe to be used for plotting.
126
    name : str
127
        Dictionary key of the plotted data.
128
    arr : Dataset/DataArray
129
        Data to be plotted.
130
    plot_kw : dict
131
        Dictionary of kwargs coming from the timeseries() input.
132
    non_dic_data : bool
133
        If True, plot_kw is not a dictionary.
134
    array_categ: dict
135
        Categories of data.
136
    legend: str
137
        Legend type.
138

139
    Returns
140
    -------
141
    matplotlib.axes.Axes
142
    """
143
    lines_dict = {}  # created to facilitate accessing line properties later
×
144
    # look for SSP, RCP, CMIP model color
145
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
146
    if get_scen_color(name, cat_colors):
×
147
        plot_kw[name].setdefault("color", get_scen_color(name, cat_colors))
×
148

149
    #  remove 'label' to avoid error due to double 'label' args
150
    if "label" in plot_kw[name]:
×
151
        del plot_kw[name]["label"]
×
152
        warnings.warn(f'"label" entry in plot_kw[{name}] will be ignored.')
×
153

154
    if array_categ[name] == "ENS_REALS_DA":
×
155
        _plot_realizations(ax, arr, name, plot_kw, non_dict_data)
×
156

157
    elif array_categ[name] == "ENS_REALS_DS":
×
158
        if len(arr.data_vars) >= 2:
×
159
            raise TypeError(
×
160
                "To plot multiple ensembles containing realizations, use DataArrays outside a Dataset"
161
            )
162
        for k, sub_arr in arr.data_vars.items():
×
163
            _plot_realizations(ax, sub_arr, name, plot_kw, non_dict_data)
×
164

165
    elif array_categ[name] == "ENS_PCT_DIM_DS":
×
166
        for k, sub_arr in arr.data_vars.items():
×
167
            sub_name = (
×
168
                sub_arr.name if non_dict_data is True else (name + "_" + sub_arr.name)
169
            )
170

171
            # extract each percentile array from the dims
172
            array_data = {}
×
173
            for pct in sub_arr.percentiles.values:
×
174
                array_data[str(pct)] = sub_arr.sel(percentiles=pct)
×
175

176
            # create a dictionary labeling the middle, upper and lower line
177
            sorted_lines = sort_lines(array_data)
×
178

179
            # plot
180
            lines_dict[sub_name] = ax.plot(
×
181
                array_data[sorted_lines["middle"]]["time"],
182
                array_data[sorted_lines["middle"]].values,
183
                label=sub_name,
184
                **plot_kw[name],
185
            )
186

187
            ax.fill_between(
×
188
                array_data[sorted_lines["lower"]]["time"],
189
                array_data[sorted_lines["lower"]].values,
190
                array_data[sorted_lines["upper"]].values,
191
                color=lines_dict[sub_name][0].get_color(),
192
                linewidth=0.0,
193
                alpha=0.2,
194
                label=fill_between_label(sorted_lines, name, array_categ, legend),
195
            )
196

197
    # other ensembles
198
    elif array_categ[name] in [
×
199
        "ENS_PCT_VAR_DS",
200
        "ENS_STATS_VAR_DS",
201
        "ENS_PCT_DIM_DA",
202
    ]:
203
        # extract each array from the datasets
204
        array_data = {}
×
205
        if array_categ[name] == "ENS_PCT_DIM_DA":
×
206
            for pct in arr.percentiles:
×
207
                array_data[str(int(pct))] = arr.sel(percentiles=int(pct))
×
208
        else:
209
            for k, v in arr.data_vars.items():
×
210
                array_data[k] = v
×
211

212
        # create a dictionary labeling the middle, upper and lower line
213
        sorted_lines = sort_lines(array_data)
×
214

215
        # plot
216
        lines_dict[name] = ax.plot(
×
217
            array_data[sorted_lines["middle"]]["time"],
218
            array_data[sorted_lines["middle"]].values,
219
            label=name,
220
            **plot_kw[name],
221
        )
222

223
        ax.fill_between(
×
224
            array_data[sorted_lines["lower"]]["time"],
225
            array_data[sorted_lines["lower"]].values,
226
            array_data[sorted_lines["upper"]].values,
227
            color=lines_dict[name][0].get_color(),
228
            linewidth=0.0,
229
            alpha=0.2,
230
            label=fill_between_label(sorted_lines, name, array_categ, legend),
231
        )
232

233
    #  non-ensemble Datasets
234
    elif array_categ[name] == "DS":
×
235
        ignore_label = False
×
236
        for k, sub_arr in arr.data_vars.items():
×
237
            sub_name = (
×
238
                sub_arr.name if non_dict_data is True else (name + "_" + sub_arr.name)
239
            )
240

241
            #  if kwargs are specified by user, all lines are the same and we want one legend entry
242
            if plot_kw[name]:
×
243
                label = name if not ignore_label else ""
×
244
                ignore_label = True
×
245
            else:
246
                label = sub_name
×
247

248
            lines_dict[sub_name] = ax.plot(
×
249
                sub_arr["time"], sub_arr.values, label=label, **plot_kw[name]
250
            )
251

252
    #  non-ensemble DataArrays
253
    elif array_categ[name] in ["DA"]:
×
254
        lines_dict[name] = ax.plot(arr["time"], arr.values, label=name, **plot_kw[name])
×
255

256
    else:
257
        raise ValueError(
×
258
            "Data structure not supported"
259
        )  # can probably be removed along with elif logic above,
260
        # given that get_array_categ() also does this check
261
    return ax
×
262

263

264
def timeseries(
6✔
265
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
266
    ax: matplotlib.axes.Axes | None = None,
267
    use_attrs: dict[str, Any] | None = None,
268
    fig_kw: dict[str, Any] | None = None,
269
    plot_kw: dict[str, Any] | None = None,
270
    legend: str = "lines",
271
    show_lat_lon: bool | str | int | tuple[float, float] = True,
272
    enumerate_subplots: bool = False,
273
) -> matplotlib.axes.Axes:
274
    """Plot time series from 1D Xarray Datasets or DataArrays as line plots.
275

276
    Parameters
277
    ----------
278
    data : dict or Dataset/DataArray
279
        Input data to plot. It can be a DataArray, Dataset or a dictionary of DataArrays and/or Datasets.
280
    ax : matplotlib.axes.Axes, optional
281
        Matplotlib axis on which to plot.
282
    use_attrs : dict, optional
283
        A dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
284
        Default value is {'title': 'description', 'ylabel': 'long_name', 'yunits': 'units'}.
285
        Only the keys found in the default dict can be used.
286
    fig_kw : dict, optional
287
        Arguments to pass to `plt.subplots()`. Only works if `ax` is not provided.
288
    plot_kw : dict, optional
289
        Arguments to pass to the `plot()` function. Changes how the line looks.
290
        If 'data' is a dictionary, must be a nested dictionary with the same keys as 'data'.
291
    legend : str (default 'lines') or dict
292
        'full' (lines and shading), 'lines' (lines only), 'in_plot' (end of lines),
293
         'edge' (out of plot), 'facetgrid' under figure, 'none' (no legend). If dict, arguments to pass to ax.legend().
294
    show_lat_lon : bool, tuple, str or int
295
        If True, show latitude and longitude at the bottom right of the figure.
296
        Can be a tuple of axis coordinates (from 0 to 1, as a fraction of the axis length) representing
297
        the location of the text. If a string or an int, the same values as those of the 'loc' parameter
298
        of matplotlib's legends are accepted.
299

300
        ==================   =============
301
        Location String      Location Code
302
        ==================   =============
303
        'upper right'        1
304
        'upper left'         2
305
        'lower left'         3
306
        'lower right'        4
307
        'right'              5
308
        'center left'        6
309
        'center right'       7
310
        'lower center'       8
311
        'upper center'       9
312
        'center'             10
313
        ==================   =============
314
    enumerate_subplots: bool
315
        If True, enumerate subplots with letters.
316
        Only works with facetgrids (pass `col` or `row` in plot_kw).
317

318
    Returns
319
    -------
320
    matplotlib.axes.Axes
321
    """
322
    # convert SSP, RCP, CMIP formats in keys
323
    if isinstance(data, dict):
×
324
        data = process_keys(data, convert_scen_name)
×
325
    if isinstance(plot_kw, dict):
×
326
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
327

328
    # create empty dicts if None
329
    use_attrs = empty_dict(use_attrs)
×
330
    fig_kw = empty_dict(fig_kw)
×
331
    plot_kw = empty_dict(plot_kw)
×
332

333
    # if only one data input, insert in dict.
334
    non_dict_data = False
×
335
    if not isinstance(data, dict):
×
336
        non_dict_data = True
×
337
        data = {"_no_label": data}  # mpl excludes labels starting with "_" from legend
×
338
        plot_kw = {"_no_label": empty_dict(plot_kw)}
×
339

340
    # assign keys to plot_kw if not there
341
    if non_dict_data is False:
×
342
        for name in data:
×
343
            if name not in plot_kw:
×
344
                plot_kw[name] = {}
×
345
        for key in plot_kw:
×
346
            if key not in data:
×
347
                raise KeyError(
×
348
                    'plot_kw must be a nested dictionary with keys corresponding to the keys in "data"'
349
                )
350

351
    # check: type
352
    for name, arr in data.items():
×
353
        if not isinstance(arr, (xr.Dataset, xr.DataArray)):
×
354
            raise TypeError(
×
355
                '"data" must be a xr.Dataset, a xr.DataArray or a dictionary of such objects.'
356
            )
357

358
    # check: 'time' dimension and calendar format
359
    data = check_timeindex(data)
×
360

361
    # set fig, ax if not provided
362
    if ax is None and (
×
363
        "row" not in list(plot_kw.values())[0].keys()
364
        and "col" not in list(plot_kw.values())[0].keys()
365
    ):
366
        fig, ax = plt.subplots(**fig_kw)
×
367
    elif ax is not None and (
×
368
        "col" in list(plot_kw.values())[0].keys()
369
        or "row" in list(plot_kw.values())[0].keys()
370
    ):
371
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
372
    elif ax is None:
×
373
        cfig_kw = fig_kw.copy()
×
374
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
375
            list(plot_kw.values())[0].setdefault("figsize", fig_kw["figsize"])
×
376
            cfig_kw.pop("figsize")
×
377
        if cfig_kw:
×
378
            for v in plot_kw.values():
×
379
                {"subplots_kws": cfig_kw} | v
×
380
            warnings.warn(
×
381
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid."
382
            )
383

384
    # set default use_attrs values
385
    if ax:
×
386
        use_attrs.setdefault("title", "description")
×
387
    else:
388
        use_attrs.setdefault("suptitle", "description")
×
389
    use_attrs.setdefault("ylabel", "long_name")
×
390
    use_attrs.setdefault("yunits", "units")
×
391

392
    # dict of array 'categories'
393
    array_categ = {name: get_array_categ(array) for name, array in data.items()}
×
394
    cp_plot_kw = copy.deepcopy(plot_kw)
×
395
    # get data and plot
396
    for name, arr in data.items():
×
397
        if ax:
×
398
            _plot_timeseries(ax, name, arr, plot_kw, non_dict_data, array_categ, legend)
×
399
        else:
400
            if name == list(data.keys())[0]:
×
401
                # create empty DataArray with same dimensions as data first entry to create an empty xr.plot.FacetGrid
402
                if isinstance(arr, xr.Dataset):
×
403
                    da = arr[list(arr.keys())[0]]
×
404
                else:
405
                    da = arr
×
406
                da = da.where(da == np.nan)
×
407
                im = da.plot(**plot_kw[name], color="white")
×
408

409
            [
×
410
                cp_plot_kw[name].pop(key)
411
                for key in ["row", "col", "figsize"]
412
                if key in cp_plot_kw[name].keys()
413
            ]
414

415
            # plot data in every axis of the facetgrid
416
            for i in range(0, im.axs.shape[0]):
×
417
                for j in range(0, im.axs.shape[1]):
×
418
                    sel_arr = {}
×
419

420
                    if "row" in plot_kw[name]:
×
421
                        sel_arr[plot_kw[name]["row"]] = i
×
422
                    if "col" in plot_kw[name]:
×
423
                        sel_arr[plot_kw[name]["col"]] = j
×
424

425
                    _plot_timeseries(
×
426
                        im.axs[i, j],
427
                        name,
428
                        arr.isel(**sel_arr).squeeze(),
429
                        cp_plot_kw,
430
                        non_dict_data,
431
                        array_categ,
432
                        legend,
433
                    )
434

435
    #  add/modify plot elements according to the first entry.
436
    if ax:
×
437
        set_plot_attrs(
×
438
            use_attrs,
439
            list(data.values())[0],
440
            ax,
441
            title_loc="left",
442
            wrap_kw={"min_line_len": 35, "max_line_len": 48},
443
        )
444
        ax.set_xlabel(
×
445
            get_localized_term("time").capitalize()
446
        )  # check_timeindex() already checks for 'time'
447

448
        # other plot elements
449
        if show_lat_lon:
×
450
            if show_lat_lon is True:
×
451
                plot_coords(
×
452
                    ax,
453
                    list(data.values())[0],
454
                    param="location",
455
                    loc="lower right",
456
                    backgroundalpha=1,
457
                )
458
            elif isinstance(show_lat_lon, (str, tuple, int)):
×
459
                plot_coords(
×
460
                    ax,
461
                    list(data.values())[0],
462
                    param="location",
463
                    loc=show_lat_lon,
464
                    backgroundalpha=1,
465
                )
466
            else:
467
                raise TypeError(" show_lat_lon must be a bool, string, int, or tuple")
×
468

469
        if legend is not None:
×
470
            if not ax.get_legend_handles_labels()[0]:  # check if legend is empty
×
471
                pass
×
472
            elif legend == "in_plot":
×
473
                split_legend(ax, in_plot=True)
×
474
            elif legend == "edge":
×
475
                split_legend(ax, in_plot=False)
×
476
            elif isinstance(legend, dict):
×
477
                ax.legend(**legend)
×
478
            else:
479
                ax.legend()
×
480

481
        return ax
×
482
    else:
483
        if legend is not None:
×
484
            if not im.axs[-1, -1].get_legend_handles_labels()[
×
485
                0
486
            ]:  # check if legend is empty
487
                pass
×
488
            elif legend == "in_plot":
×
489
                split_legend(im.axs[-1, -1], in_plot=True)
×
490
            elif legend == "edge":
×
491
                split_legend(im.axs[-1, -1], in_plot=False)
×
492
            elif isinstance(legend, dict):
×
493
                handles, labels = im.axs[-1, -1].get_legend_handles_labels()
×
494
                legend = {"handles": handles, "labels": labels} | legend
×
495
                im.fig.legend(**legend)
×
496
            elif legend == "facetgrid":
×
497
                handles, labels = im.axs[-1, -1].get_legend_handles_labels()
×
498
                im.fig.legend(
×
499
                    handles,
500
                    labels,
501
                    loc="lower center",
502
                    ncol=len(im.axs[-1, -1].lines),
503
                    bbox_to_anchor=(0.5, -0.05),
504
                )
505

506
        if show_lat_lon:
×
507
            if show_lat_lon is True:
×
508
                plot_coords(
×
509
                    None,
510
                    list(data.values())[0].isel(lat=0, lon=0),
511
                    param="location",
512
                    loc="lower right",
513
                    backgroundalpha=1,
514
                )
515
            elif isinstance(show_lat_lon, (str, tuple, int)):
×
516
                plot_coords(
×
517
                    None,
518
                    list(data.values())[0].isel(lat=0, lon=0),
519
                    param="location",
520
                    loc=show_lat_lon,
521
                    backgroundalpha=1,
522
                )
523
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
524
            for idx, ax in enumerate(im.axs.flat):
×
525
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
526

527
        return im
×
528

529

530
def gridmap(
6✔
531
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
532
    ax: matplotlib.axes.Axes | None = None,
533
    use_attrs: dict[str, Any] | None = None,
534
    fig_kw: dict[str, Any] | None = None,
535
    plot_kw: dict[str, Any] | None = None,
536
    projection: ccrs.Projection = ccrs.LambertConformal(),
537
    transform: ccrs.Projection | None = None,
538
    features: list[str] | dict[str, dict[str, Any]] | None = None,
539
    geometries_kw: dict[str, Any] | None = None,
540
    contourf: bool = False,
541
    cmap: str | matplotlib.colors.Colormap | None = None,
542
    levels: int | list | np.ndarray | None = None,
543
    divergent: bool | int | float = False,
544
    show_time: bool | str | int | tuple[float, float] = False,
545
    frame: bool = False,
546
    enumerate_subplots: bool = False,
547
) -> matplotlib.axes.Axes:
548
    """Create map from 2D data.
549

550
    Parameters
551
    ----------
552
    data : dict, DataArray or Dataset
553
        Input data do plot. If dictionary, must have only one entry.
554
    ax : matplotlib axis, optional
555
        Matplotlib axis on which to plot, with the same projection as the one specified.
556
    use_attrs : dict, optional
557
        Dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
558
        Default value is {'title': 'description', 'cbar_label': 'long_name', 'cbar_units': 'units'}.
559
        Only the keys found in the default dict can be used.
560
    fig_kw : dict, optional
561
        Arguments to pass to `plt.figure()`.
562
    plot_kw:  dict, optional
563
        Arguments to pass to the `xarray.plot.pcolormesh()` or 'xarray.plot.contourf()' function.
564
    projection : ccrs.Projection
565
        The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.
566
    transform : ccrs.Projection, optional
567
        Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching
568
        ccrs.PlateCarree() or ccrs.RotatedPole().
569
    features : list or dict, optional
570
        Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from
571
        cartopy.feature: ['coastline', 'borders', 'lakes', 'land', 'ocean', 'rivers', 'states'].
572
    geometries_kw : dict, optional
573
        Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.
574
    contourf : bool
575
        By default False, use plt.pcolormesh(). If True, use plt.contourf().
576
    cmap : matplotlib.colors.Colormap or str, optional
577
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
578
        If None, look for common variables (from data/ipcc_colors/varaibles_groups.json) in the name of the DataArray
579
        or its 'history' attribute and use corresponding colormap, aligned with the IPCC visual style guide 2022
580
        (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
581
    levels : int, list, np.ndarray, optional
582
        Number of levels to divide the colormap into or list of level boundaries (in data units).
583
    divergent : bool or int or float
584
        If int or float, becomes center of cmap. Default center is 0.
585
    show_time : bool, tuple, string or int.
586
        If True, show time (as date) at the bottom right of the figure.
587
        Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location
588
        of the text. If a string or an int, the same values as those of the 'loc' parameter
589
        of matplotlib's legends are accepted.
590

591
        ==================   =============
592
        Location String      Location Code
593
        ==================   =============
594
        'upper right'        1
595
        'upper left'         2
596
        'lower left'         3
597
        'lower right'        4
598
        'right'              5
599
        'center left'        6
600
        'center right'       7
601
        'lower center'       8
602
        'upper center'       9
603
        'center'             10
604
        ==================   =============
605
    frame : bool
606
        Show or hide frame. Default False.
607
    enumerate_subplots: bool
608
        If True, enumerate subplots with letters.
609
        Only works with facetgrids (pass `col` or `row` in plot_kw).
610

611
    Returns
612
    -------
613
    matplotlib.axes.Axes
614
    """
615
    # create empty dicts if None
616
    use_attrs = empty_dict(use_attrs)
×
617
    fig_kw = empty_dict(fig_kw)
×
618
    plot_kw = empty_dict(plot_kw)
×
619

620
    # set default use_attrs values
621
    use_attrs = {"cbar_label": "long_name", "cbar_units": "units"} | use_attrs
×
622
    if "row" not in plot_kw and "col" not in plot_kw:
×
623
        use_attrs.setdefault("title", "description")
×
624

625
    # extract plot_kw from dict if needed
626
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
627
        plot_kw = plot_kw[list(data.keys())[0]]
×
628

629
    # if data is dict, extract
630
    if isinstance(data, dict):
×
631
        if len(data) == 1:
×
632
            data = list(data.values())[0]
×
633
        else:
634
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
635

636
    # select data to plot
637
    if isinstance(data, xr.DataArray):
×
638
        plot_data = data.squeeze()
×
639
    elif isinstance(data, xr.Dataset):
×
640
        if len(data.data_vars) > 1:
×
641
            warnings.warn(
×
642
                "data is xr.Dataset; only the first variable will be used in plot"
643
            )
644
        plot_data = data[list(data.keys())[0]].squeeze()
×
645
    else:
646
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
647

648
    # setup transform
649
    if transform is None:
×
650
        if "lat" in data.dims and "lon" in data.dims:
×
651
            transform = ccrs.PlateCarree()
×
652
        if "rlat" in data.dims and "rlon" in data.dims:
×
NEW
653
            transform = get_rotpole(data)
×
654

655
    # setup fig, ax
656
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
657
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
658
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
659
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
660
    elif ax is None:
×
661
        plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
662
        cfig_kw = fig_kw.copy()
×
663
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
664
            plot_kw.setdefault("figsize", fig_kw["figsize"])
×
665
            cfig_kw.pop("figsize")
×
666
        if len(cfig_kw) >= 1:
×
667
            plot_kw = {"subplot_kws": {"projection": cfig_kw}} | plot_kw
×
668
            warnings.warn(
×
669
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid."
670
            )
671

672
    # create cbar label
673
    if (
×
674
        "cbar_units" in use_attrs
675
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
676
    ):  # avoids '[]' as label
677
        cbar_label = (
×
678
            get_attributes(use_attrs["cbar_label"], data)
679
            + " ("
680
            + get_attributes(use_attrs["cbar_units"], data)
681
            + ")"
682
        )
683
    else:
684
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
685

686
    # colormap
687
    if isinstance(cmap, str):
×
688
        if cmap not in plt.colormaps():
×
689
            try:
×
690
                cmap = create_cmap(filename=cmap)
×
691
            except FileNotFoundError as e:
×
692
                logger.error(e)
×
693
                pass
×
694

695
    elif cmap is None:
×
696
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
697
        cmap = create_cmap(
×
698
            get_var_group(path_to_json=cdata, da=plot_data),
699
            divergent=divergent,
700
        )
701
    plot_kw.setdefault("cmap", cmap)
×
702

703
    if levels is not None:
×
704
        if isinstance(levels, Iterable):
×
705
            lin = levels
×
706
        else:
707
            lin = custom_cmap_norm(
×
708
                cmap,
709
                np.nanmin(plot_data.values),
710
                np.nanmax(plot_data.values),
711
                levels=levels,
712
                divergent=divergent,
713
                linspace_out=True,
714
            )
715
        plot_kw.setdefault("levels", lin)
×
716

717
    elif (divergent is not False) and ("levels" not in plot_kw):
×
718
        norm = custom_cmap_norm(
×
719
            cmap,
720
            np.nanmin(plot_data.values),
721
            np.nanmax(plot_data.values),
722
            levels=levels,
723
            divergent=divergent,
724
        )
725
        plot_kw.setdefault("norm", norm)
×
726

727
    # set defaults
728
    if divergent is not False:
×
729
        if isinstance(divergent, (int, float)):
×
730
            plot_kw.setdefault("center", divergent)
×
731
        else:
732
            plot_kw.setdefault("center", 0)
×
733

734
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
735
        plot_kw.setdefault("cbar_kwargs", {})
×
736
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
737

738
    # bug xlim / ylim + transform in facetgrids
739
    # (see https://github.com/pydata/xarray/issues/8562#issuecomment-1865189766)
740
    if transform and ("xlim" in plot_kw and "ylim" in plot_kw):
×
741
        extent = [
×
742
            plot_kw["xlim"][0],
743
            plot_kw["xlim"][1],
744
            plot_kw["ylim"][0],
745
            plot_kw["ylim"][1],
746
        ]
747
        plot_kw.pop("xlim")
×
748
        plot_kw.pop("ylim")
×
749
    elif transform and ("xlim" in plot_kw or "ylim" in plot_kw):
×
750
        extent = None
×
751
        warnings.warn(
×
752
            "Requires both xlim and ylim with 'transform'. Xlim or ylim was dropped"
753
        )
754
        if "xlim" in plot_kw.keys():
×
755
            plot_kw.pop("xlim")
×
756
        if "ylim" in plot_kw.keys():
×
757
            plot_kw.pop("ylim")
×
758
    else:
759
        extent = None
×
760

761
    # plot
762
    if ax:
×
763
        plot_kw.setdefault("ax", ax)
×
764
    if transform:
×
765
        plot_kw.setdefault("transform", transform)
×
766

767
    if contourf is False:
×
768
        im = plot_data.plot.pcolormesh(**plot_kw)
×
769
    else:
770
        im = plot_data.plot.contourf(**plot_kw)
×
771

772
    if ax:
×
773
        if extent:
×
774
            ax.set_extent(extent)
×
775

776
        ax = add_features_map(
×
777
            data,
778
            ax,
779
            use_attrs,
780
            projection,
781
            features,
782
            geometries_kw,
783
            frame,
784
        )
785
        if show_time:
×
786
            if isinstance(show_time, bool):
×
787
                plot_coords(
×
788
                    ax,
789
                    plot_data,
790
                    param="time",
791
                    loc="lower right",
792
                    backgroundalpha=1,
793
                )
794
            elif isinstance(show_time, (str, tuple, int)):
×
795
                plot_coords(
×
796
                    ax,
797
                    plot_data,
798
                    param="time",
799
                    loc=show_time,
800
                    backgroundalpha=1,
801
                )
802

803
        # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
804
        if (frame is False) and (
×
805
            (getattr(im, "colorbar", None) is not None)
806
            or (getattr(im, "cbar", None) is not None)
807
        ):
808
            im.colorbar.outline.set_visible(False)
×
809
        return ax
×
810

811
    else:
812
        for i, fax in enumerate(im.axs.flat):
×
813
            add_features_map(
×
814
                data,
815
                fax,
816
                use_attrs,
817
                projection,
818
                features,
819
                geometries_kw,
820
                frame,
821
            )
822
            if extent:
×
823
                fax.set_extent(extent)
×
824

825
            # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
826
        if (frame is False) and (
×
827
            (getattr(im, "colorbar", None) is not None)
828
            or (getattr(im, "cbar", None) is not None)
829
        ):
830
            im.cbar.outline.set_visible(False)
×
831

832
        if show_time:
×
833
            if isinstance(show_time, bool):
×
834
                plot_coords(
×
835
                    None,
836
                    plot_data,
837
                    param="time",
838
                    loc="lower right",
839
                    backgroundalpha=1,
840
                )
841
            elif isinstance(show_time, (str, tuple, int)):
×
842
                plot_coords(
×
843
                    None,
844
                    plot_data,
845
                    param="time",
846
                    loc=show_time,
847
                    backgroundalpha=1,
848
                )
849

850
        use_attrs.setdefault("suptitle", "long_name")
×
851
        im = set_plot_attrs(use_attrs, data, facetgrid=im)
×
852
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
853
            for idx, ax in enumerate(im.axs.flat):
×
854
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
855

856
        return im
×
857

858

859
def gdfmap(
6✔
860
    df: gpd.GeoDataFrame,
861
    df_col: str,
862
    ax: cartopy.mpl.geoaxes.GeoAxes | cartopy.mpl.geoaxes.GeoAxesSubplot | None = None,
863
    fig_kw: dict[str, Any] | None = None,
864
    plot_kw: dict[str, Any] | None = None,
865
    projection: ccrs.Projection = ccrs.LambertConformal(),
866
    features: list[str] | dict[str, dict[str, Any]] | None = None,
867
    cmap: str | matplotlib.colors.Colormap | None = None,
868
    levels: int | list[int | float] | None = None,
869
    divergent: bool | int | float = False,
870
    cbar: bool = True,
871
    frame: bool = False,
872
) -> matplotlib.axes.Axes:
873
    """Create a map plot from geometries.
874

875
    Parameters
876
    ----------
877
    df : geopandas.GeoDataFrame
878
        Dataframe containing the geometries and the data to plot. Must have a column named 'geometry'.
879
    df_col : str
880
        Name of the column of 'df' containing the data to plot using the colorscale.
881
    ax : cartopy.mpl.geoaxes.GeoAxes or cartopy.mpl.geoaxes.GeoaxesSubplot, optional
882
        Matplotlib axis built with a projection, on which to plot.
883
    fig_kw : dict, optional
884
        Arguments to pass to `plt.figure()`.
885
    plot_kw :  dict, optional
886
        Arguments to pass to the GeoDataFrame.plot() method.
887
    projection : ccrs.Projection
888
        The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.
889
    features : list or dict, optional
890
        Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from
891
        cartopy.feature: ['coastline', 'borders', 'lakes', 'land', 'ocean', 'rivers', 'states'].
892
    cmap : matplotlib.colors.Colormap or str
893
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
894
        If None, look for common variables (from data/ipcc_colors/varaibles_groups.json) in the name of df_col
895
        and use corresponding colormap, aligned with the IPCC visual style guide 2022
896
        (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
897
    levels : int or list, optional
898
        Number of  levels or list of level boundaries (in data units) to use to divide the colormap.
899
    divergent : bool or int or float
900
        If int or float, becomes center of cmap. Default center is 0.
901
    cbar : bool
902
        Show colorbar. Default 'True'.
903
    frame : bool
904
        Show or hide frame. Default False.
905

906
    Returns
907
    -------
908
    matplotlib.axes.Axes
909
    """
910
    # create empty dicts if None
911
    fig_kw = empty_dict(fig_kw)
×
912
    plot_kw = empty_dict(plot_kw)
×
913
    features = empty_dict(features)
×
914

915
    # checks
916
    if not isinstance(df, gpd.GeoDataFrame):
×
917
        raise TypeError("df myst be an instance of class geopandas.GeoDataFrame")
×
918

919
    if "geometry" not in df.columns:
×
920
        raise ValueError("column 'geometry' not found in GeoDataFrame")
×
921

922
    # convert to projection
923
    if ax is None:
×
924
        df = gpd_to_ccrs(df=df, proj=projection)
×
925
    else:
926
        df = gpd_to_ccrs(df=df, proj=ax.projection)
×
927

928
    # setup fig, ax
929
    if ax is None:
×
930
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
931
        ax.set_aspect("equal")  # recommended by geopandas
×
932

933
    # add features
934
    if features:
×
935
        add_cartopy_features(ax, features)
×
936

937
    # colormap
938
    if isinstance(cmap, str):
×
939
        if cmap in plt.colormaps():
×
940
            cmap = matplotlib.colormaps[cmap]
×
941
        else:
942
            try:
×
943
                cmap = create_cmap(filename=cmap)
×
944
            except FileNotFoundError:
×
945
                warnings.warn("invalid cmap, using default")
×
946
                cmap = create_cmap(filename="slev_seq")
×
947

948
    elif cmap is None:
×
949
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
950
        cmap = create_cmap(
×
951
            get_var_group(unique_str=df_col, path_to_json=cdata),
952
            divergent=divergent,
953
        )
954

955
    # create normalization for colormap
956
    plot_kw.setdefault("vmin", df[df_col].min())
×
957
    plot_kw.setdefault("vmax", df[df_col].max())
×
958

959
    if (levels is not None) or (divergent is not False):
×
960
        norm = custom_cmap_norm(
×
961
            cmap,
962
            plot_kw["vmin"],
963
            plot_kw["vmax"],
964
            levels=levels,
965
            divergent=divergent,
966
        )
967
        plot_kw.setdefault("norm", norm)
×
968

969
    # colorbar
970
    if cbar:
×
971
        plot_kw.setdefault("legend", True)
×
972
        plot_kw.setdefault("legend_kwds", {})
×
973
        plot_kw["legend_kwds"].setdefault("label", df_col)
×
974
        plot_kw["legend_kwds"].setdefault("orientation", "horizontal")
×
975
        plot_kw["legend_kwds"].setdefault("pad", 0.02)
×
976

977
    # plot
978
    plot = df.plot(column=df_col, ax=ax, cmap=cmap, **plot_kw)
×
979

980
    if frame is False:
×
981
        # cbar
982
        plot.figure.axes[1].spines["outline"].set_visible(False)
×
983
        plot.figure.axes[1].tick_params(size=0)
×
984
        # main axes
985
        ax.spines["geo"].set_visible(False)
×
986

987
    return ax
×
988

989

990
def violin(
6✔
991
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
992
    ax: matplotlib.axes.Axes | None = None,
993
    use_attrs: dict[str, Any] | None = None,
994
    fig_kw: dict[str, Any] | None = None,
995
    plot_kw: dict[str, Any] | None = None,
996
    color: str | int | list[str | int] | None = None,
997
) -> matplotlib.axes.Axes:
998
    """Make violin plot using seaborn.
999

1000
    Parameters
1001
    ----------
1002
    data : dict or Dataset/DataArray
1003
        Input data to plot. If a dict, must contain DataArrays and/or Datasets.
1004
    ax : matplotlib.axes.Axes, optional
1005
        Matplotlib axis on which to plot.
1006
    use_attrs : dict, optional
1007
        A dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
1008
        Default value is {'title': 'description', 'ylabel': 'long_name', 'yunits': 'units'}.
1009
        Only the keys found in the default dict can be used.
1010
    fig_kw : dict, optional
1011
        Arguments to pass to `plt.subplots()`. Only works if `ax` is not provided.
1012
    plot_kw : dict, optional
1013
        Arguments to pass to the `seaborn.violinplot()` function.
1014
    color :  str, int or list, optional
1015
        Unique color or list of colors to use. Integers point to the applied stylesheet's colors, in zero-indexed order.
1016
        Passing 'color' or 'palette' in plot_kw overrides this argument.
1017

1018
    Returns
1019
    -------
1020
    matplotlib.axes.Axes
1021
    """
1022
    # create empty dicts if None
1023
    use_attrs = empty_dict(use_attrs)
×
1024
    fig_kw = empty_dict(fig_kw)
×
1025
    plot_kw = empty_dict(plot_kw)
×
1026

1027
    # if data is dict, assemble into one DataFrame
1028
    non_dict_data = True
×
1029
    if isinstance(data, dict):
×
1030
        non_dict_data = False
×
1031
        df = pd.DataFrame()
×
1032
        for key, xr_obj in data.items():
×
1033
            if isinstance(xr_obj, xr.Dataset):
×
1034
                # if one data var, use key
1035
                if len(list(xr_obj.data_vars)) == 1:
×
1036
                    df[key] = xr_obj[list(xr_obj.data_vars)[0]].values
×
1037
                # if more than one data var, use key + name of var
1038
                else:
1039
                    for data_var in list(xr_obj.data_vars):
×
1040
                        df[key + "_" + data_var] = xr_obj[data_var].values
×
1041

1042
            elif isinstance(xr_obj, xr.DataArray):
×
1043
                df[key] = xr_obj.values
×
1044

1045
            else:
1046
                raise TypeError(
×
1047
                    '"data" must be a xr.Dataset, a xr.DataArray or a dictionary of such objects.'
1048
                )
1049

1050
    elif isinstance(data, xr.Dataset):
×
1051
        # create dataframe
1052
        df = data.to_dataframe()
×
1053
        df = df[data.data_vars]
×
1054

1055
    elif isinstance(data, xr.DataArray):
×
1056
        # create dataframe
1057
        df = data.to_dataframe()
×
1058
        for coord in list(data.coords):
×
1059
            if coord in df.columns:
×
1060
                df = df.drop(columns=coord)
×
1061

1062
    else:
1063
        raise TypeError(
×
1064
            '"data" must be a xr.Dataset, a xr.DataArray or a dictionary of such objects.'
1065
        )
1066

1067
    # set fig, ax if not provided
1068
    if ax is None:
×
1069
        fig, ax = plt.subplots(**fig_kw)
×
1070

1071
    # set default use_attrs values
1072
    if "orient" in plot_kw and plot_kw["orient"] == "h":
×
1073
        use_attrs = {"xlabel": "long_name", "xunits": "units"} | use_attrs
×
1074
    else:
1075
        use_attrs = {"ylabel": "long_name", "yunits": "units"} | use_attrs
×
1076

1077
    #  add/modify plot elements according to the first entry.
1078
    if non_dict_data:
×
1079
        set_plot_obj = data
×
1080
    else:
1081
        set_plot_obj = list(data.values())[0]
×
1082

1083
    set_plot_attrs(
×
1084
        use_attrs,
1085
        xr_obj=set_plot_obj,
1086
        ax=ax,
1087
        title_loc="left",
1088
        wrap_kw={"min_line_len": 35, "max_line_len": 48},
1089
    )
1090

1091
    # color
1092
    if color:
×
1093
        style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
1094
        if isinstance(color, str):
×
1095
            plot_kw.setdefault("color", color)
×
1096
        elif isinstance(color, int):
×
1097
            try:
×
1098
                plot_kw.setdefault("color", style_colors[color])
×
1099
            except IndexError:
×
1100
                raise IndexError("Index out of range of stylesheet colors")
×
1101
        elif isinstance(color, list):
×
1102
            for c, i in zip(color, np.arange(len(color))):
×
1103
                if isinstance(c, int):
×
1104
                    try:
×
1105
                        color[i] = style_colors[c]
×
1106
                    except IndexError:
×
1107
                        raise IndexError("Index out of range of stylesheet colors")
×
1108
            plot_kw.setdefault("palette", color)
×
1109

1110
    # plot
1111
    sns.violinplot(df, ax=ax, **plot_kw)
×
1112

1113
    # grid
1114
    if "orient" in plot_kw and plot_kw["orient"] == "h":
×
1115
        ax.grid(visible=True, axis="x")
×
1116

1117
    return ax
×
1118

1119

1120
def stripes(
6✔
1121
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1122
    ax: matplotlib.axes.Axes | None = None,
1123
    fig_kw: dict[str, Any] | None = None,
1124
    divide: int | None = None,
1125
    cmap: str | matplotlib.colors.Colormap | None = None,
1126
    cmap_center: int | float = 0,
1127
    cbar: bool = True,
1128
    cbar_kw: dict[str, Any] | None = None,
1129
) -> matplotlib.axes.Axes:
1130
    """Create stripes plot with or without multiple scenarios.
1131

1132
    Parameters
1133
    ----------
1134
    data : dict or DataArray or Dataset
1135
        Data to plot. If a dictionary of xarray objects, each will correspond to a scenario.
1136
    ax : matplotlib.axes.Axes, optional
1137
        Matplotlib axis on which to plot.
1138
    fig_kw : : dict, optional
1139
        Arguments to pass to `plt.subplots()`. Only works if `ax` is not provided.
1140
    divide : int, optional
1141
        Year at which the plot is divided into scenarios. If not provided, the horizontal separators
1142
        will extend over the full time axis.
1143
    cmap : matplotlib.colors.Colormap or str, optional
1144
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
1145
        If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray
1146
        or its 'history' attribute and use corresponding diverging colormap, aligned with the IPCC Visual Style
1147
        Guide 2022 (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
1148
    cmap_center : int or float
1149
        Center of the colormap in data coordinates. Default is 0.
1150
    cbar : bool
1151
        Show colorbar.
1152
    cbar_kw : dict, optional
1153
        Arguments to pass to plt.colorbar.
1154

1155
    Returns
1156
    -------
1157
    matplotlib.axes.Axes
1158
    """
1159
    # create empty dicts if None
1160
    fig_kw = empty_dict(fig_kw)
×
1161
    cbar_kw = empty_dict(cbar_kw)
×
1162

1163
    # init main (figure) axis
1164
    if ax is None:
×
1165
        fig_kw.setdefault("figsize", (10, 5))
×
1166
        fig, ax = plt.subplots(**fig_kw)
×
1167
    ax.set_yticks([])
×
1168
    ax.set_xticks([])
×
1169
    ax.spines[["top", "bottom", "left", "right"]].set_visible(False)
×
1170

1171
    # init plot axis
1172
    ax_0 = ax.inset_axes([0, 0.15, 1, 0.75])
×
1173

1174
    # handle non-dict data
1175
    if not isinstance(data, dict):
×
1176
        data = {"_no_label": data}
×
1177

1178
    # convert SSP, RCP, CMIP formats in keys
1179
    data = process_keys(data, convert_scen_name)
×
1180

1181
    n = len(data)
×
1182

1183
    # extract DataArrays from datasets
1184
    for key, obj in data.items():
×
1185
        if isinstance(obj, xr.DataArray):
×
1186
            pass
×
1187
        elif isinstance(obj, xr.Dataset):
×
1188
            data[key] = obj[list(obj.data_vars)[0]]
×
1189
        else:
1190
            raise TypeError("data must contain xarray DataArrays or Datasets")
×
1191

1192
    # get time interval
1193
    time_index = list(data.values())[0].time.dt.year.values
×
1194
    delta_time = [
×
1195
        time_index[i] - time_index[i - 1] for i in np.arange(1, len(time_index), 1)
1196
    ]
1197

1198
    if all(i == delta_time[0] for i in delta_time):
×
1199
        dtime = delta_time[0]
×
1200
    else:
1201
        raise ValueError("Time delta between each array element must be constant")
×
1202

1203
    # modify axes
1204
    ax.set_xlim(min(time_index) - 0.5 * dtime, max(time_index) + 0.5 * dtime)
×
1205
    ax_0.set_xlim(min(time_index) - 0.5 * dtime, max(time_index) + 0.5 * dtime)
×
1206
    ax_0.set_ylim(0, 1)
×
1207
    ax_0.set_yticks([])
×
1208
    ax_0.xaxis.set_ticks_position("top")
×
1209
    ax_0.tick_params(axis="x", direction="out", zorder=10)
×
1210
    ax_0.spines[["top", "left", "right", "bottom"]].set_visible(False)
×
1211

1212
    # width of bars, to fill x axis limits
1213
    width = (max(time_index) + 0.5 - min(time_index) - 0.5) / len(time_index)
×
1214

1215
    # create historical/projection divide
1216
    if divide is not None:
×
1217
        # convert divide year to transAxes
1218
        divide_disp = ax_0.transData.transform(
×
1219
            (divide - width * 0.5, 1)
1220
        )  # left limit of stripe, 1 is placeholder
1221
        divide_ax = ax_0.transAxes.inverted().transform(divide_disp)
×
1222
        divide_ax = divide_ax[0]
×
1223
    else:
1224
        divide_ax = 0
×
1225

1226
    # create an inset ax for each da in data
1227
    subaxes = {}
×
1228
    for i in np.arange(n):
×
1229
        name = "subax_" + str(i)
×
1230
        y = (1 / n) * i
×
1231
        subaxes[name] = ax_0.inset_axes([0, y, 1, 1 / n], transform=ax_0.transAxes)
×
1232
        subaxes[name].set(xlim=ax_0.get_xlim(), ylim=(0, 1), xticks=[], yticks=[])
×
1233
        subaxes[name].spines[["top", "bottom", "left", "right"]].set_visible(False)
×
1234
        # lines separating axes
1235
        if i > 0:
×
1236
            subaxes[name].spines["bottom"].set_visible(True)
×
1237
            subaxes[name].spines["bottom"].set(
×
1238
                lw=2,
1239
                color="w",
1240
                bounds=(divide_ax, 1),
1241
                transform=subaxes[name].transAxes,
1242
            )
1243
            # circles
1244
            if divide:
×
1245
                circle = matplotlib.patches.Ellipse(
×
1246
                    xy=(divide_ax, y),
1247
                    width=0.01,
1248
                    height=0.03,
1249
                    color="w",
1250
                    transform=ax_0.transAxes,
1251
                    zorder=10,
1252
                )
1253
                ax_0.add_patch(circle)
×
1254

1255
    # get max and min of all data
1256
    data_min = 1e6
×
1257
    data_max = -1e6
×
1258
    for da in data.values():
×
1259
        if min(da.values) < data_min:
×
1260
            data_min = min(da.values)
×
1261
        if max(da.values) > data_max:
×
1262
            data_max = max(da.values)
×
1263

1264
    # colormap
1265
    if isinstance(cmap, str):
×
1266
        if cmap in plt.colormaps():
×
1267
            cmap = matplotlib.colormaps[cmap]
×
1268
        else:
1269
            try:
×
1270
                cmap = create_cmap(filename=cmap)
×
1271
            except FileNotFoundError as e:
×
1272
                logger.error(e)
×
1273
                pass
×
1274

1275
    elif cmap is None:
×
1276
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1277
        cmap = create_cmap(
×
1278
            get_var_group(path_to_json=cdata, da=list(data.values())[0]),
1279
            divergent=True,
1280
        )
1281

1282
    # create cmap norm
1283
    if cmap_center is not None:
×
1284
        norm = matplotlib.colors.TwoSlopeNorm(cmap_center, vmin=data_min, vmax=data_max)
×
1285
    else:
1286
        norm = matplotlib.colors.Normalize(data_min, data_max)
×
1287

1288
    # plot
1289
    for (name, subax), (key, da) in zip(subaxes.items(), data.items()):
×
1290
        subax.bar(da.time.dt.year, height=1, width=dtime, color=cmap(norm(da.values)))
×
1291
        if divide:
×
1292
            if key != "_no_label":
×
1293
                subax.text(
×
1294
                    0.99,
1295
                    0.5,
1296
                    key,
1297
                    transform=subax.transAxes,
1298
                    fontsize=14,
1299
                    ha="right",
1300
                    va="center",
1301
                    c="w",
1302
                    weight="bold",
1303
                )
1304

1305
    # colorbar
1306
    if cbar is True:
×
1307
        sm = ScalarMappable(cmap=cmap, norm=norm)
×
1308
        cax = ax.inset_axes([0.01, 0.05, 0.35, 0.06])
×
1309
        cbar_tcks = np.arange(math.floor(data_min), math.ceil(data_max), 2)
×
1310
        # label
1311
        da = list(data.values())[0]
×
1312
        label = get_attributes("long_name", da)
×
1313
        if label != "":
×
1314
            if "units" in da.attrs:
×
1315
                u = da.units
×
1316
                label += f" ({u})"
×
1317
            label = wrap_text(label, max_line_len=40)
×
1318

1319
        cbar_kw = {
×
1320
            "cax": cax,
1321
            "orientation": "horizontal",
1322
            "ticks": cbar_tcks,
1323
            "label": label,
1324
        } | cbar_kw
1325
        plt.colorbar(sm, **cbar_kw)
×
1326
        cax.spines["outline"].set_visible(False)
×
1327
        cax.set_xscale("linear")
×
1328

1329
    return ax
×
1330

1331

1332
def heatmap(
6✔
1333
    data: xr.DataArray | xr.Dataset | dict[str, Any],
1334
    ax: matplotlib.axes.Axes | None = None,
1335
    use_attrs: dict[str, Any] | None = None,
1336
    fig_kw: dict[str, Any] | None = None,
1337
    plot_kw: dict[str, Any] | None = None,
1338
    transpose: bool = False,
1339
    cmap: str | matplotlib.colors.Colormap | None = "RdBu",
1340
    divergent: bool | int | float = False,
1341
) -> matplotlib.axes.Axes:
1342
    """Create heatmap from a DataArray.
1343

1344
    Parameters
1345
    ----------
1346
    data : dict or DataArray or Dataset
1347
        Input data do plot. If dictionary, must have only one entry.
1348
    ax : matplotlib axis, optional
1349
        Matplotlib axis on which to plot, with the same projection as the one specified.
1350
    use_attrs : dict, optional
1351
        Dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
1352
        Default value is {'cbar_label': 'long_name'}.
1353
        Only the keys found in the default dict can be used.
1354
    fig_kw : dict, optional
1355
        Arguments to pass to `plt.figure()`.
1356
    plot_kw :  dict, optional
1357
        Arguments to pass to the 'seaborn.heatmap()' function.
1358
        If 'data' is a dictionary, can be a nested dictionary with the same key as 'data'.
1359
    transpose : bool
1360
        If true, the 2D data will be transposed, so that the original x-axis becomes the y-axis and vice versa.
1361
    cmap : matplotlib.colors.Colormap or str, optional
1362
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
1363
        If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray
1364
        or its 'history' attribute and use corresponding colormap, aligned with the IPCC Visual Style Guide 2022
1365
        (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
1366
    divergent : bool or int or float
1367
        If int or float, becomes center of cmap. Default center is 0.
1368

1369
    Returns
1370
    -------
1371
    matplotlib.axes.Axes
1372
    """
1373
    # create empty dicts if None
1374
    use_attrs = empty_dict(use_attrs)
×
1375
    fig_kw = empty_dict(fig_kw)
×
1376
    plot_kw = empty_dict(plot_kw)
×
1377

1378
    # set default use_attrs values
1379
    use_attrs.setdefault("cbar_label", "long_name")
×
1380

1381
    # if data is dict, extract
1382
    if isinstance(data, dict):
×
1383
        if plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1384
            plot_kw = plot_kw[list(data.keys())[0]]
×
1385
        if len(data) == 1:
×
1386
            data = list(data.values())[0]
×
1387
        else:
1388
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1389

1390
    # select data to plot
1391
    if isinstance(data, xr.DataArray):
×
1392
        da = data
×
1393
    elif isinstance(data, xr.Dataset):
×
1394
        if len(data.data_vars) > 1:
×
1395
            warnings.warn(
×
1396
                "data is xr.Dataset; only the first variable will be used in plot"
1397
            )
1398
        da = list(data.values())[0]
×
1399
    else:
1400
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1401

1402
    # setup fig, axis
1403
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
1404
        fig, ax = plt.subplots(**fig_kw)
×
1405
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
1406
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
1407
    elif ax is None:
×
1408
        if any([k != "figsize" for k in fig_kw.keys()]):
×
1409
            warnings.warn(
×
1410
                "Only figsize arguments can be passed to fig_kw when using facetgrid."
1411
            )
1412
        plot_kw.setdefault("col", None)
×
1413
        plot_kw.setdefault("row", None)
×
1414
        plot_kw.setdefault("margin_titles", True)
×
1415
        heatmap_dims = list(
×
1416
            set(da.dims)
1417
            - {d for d in [plot_kw["col"], plot_kw["row"]] if d is not None}
1418
        )
1419
        if da.name is None:
×
1420
            da = da.to_dataset(name="data").data
×
1421
        da_name = da.name
×
1422

1423
    # create cbar label
1424
    if (
×
1425
        "cbar_units" in use_attrs
1426
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1427
    ):  # avoids '()' as label
1428
        cbar_label = (
×
1429
            get_attributes(use_attrs["cbar_label"], data)
1430
            + " ("
1431
            + get_attributes(use_attrs["cbar_units"], data)
1432
            + ")"
1433
        )
1434
    else:
1435
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1436

1437
    # colormap
1438
    if isinstance(cmap, str):
×
1439
        if cmap not in plt.colormaps():
×
1440
            try:
×
1441
                cmap = create_cmap(filename=cmap)
×
1442
            except FileNotFoundError as e:
×
1443
                logger.error(e)
×
1444
                pass
×
1445

1446
    elif cmap is None:
×
1447
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1448
        cmap = create_cmap(
×
1449
            get_var_group(path_to_json=cdata, da=da),
1450
            divergent=divergent,
1451
        )
1452

1453
    # convert data to DataFrame
1454
    if transpose:
×
1455
        da = da.transpose()
×
1456
    if "col" not in plot_kw and "row" not in plot_kw:
×
1457
        if len(da.dims) != 2:
×
1458
            raise ValueError("DataArray must have exactly two dimensions")
×
1459
        df = da.to_pandas()
×
1460
    else:
1461
        if len(heatmap_dims) != 2:
×
1462
            raise ValueError("DataArray must have exactly two dimensions")
×
1463
        df = da.to_dataframe().reset_index()
×
1464

1465
    # set defaults
1466
    if divergent is not False:
×
1467
        if isinstance(divergent, (int, float)):
×
1468
            plot_kw.setdefault("center", divergent)
×
1469
        else:
1470
            plot_kw.setdefault("center", 0)
×
1471

1472
    if "cbar" not in plot_kw or plot_kw["cbar"] is not False:
×
1473
        plot_kw.setdefault("cbar_kws", {})
×
1474
        plot_kw["cbar_kws"].setdefault("label", wrap_text(cbar_label))
×
1475

1476
    plot_kw.setdefault("cmap", cmap)
×
1477

1478
    # plot
1479
    def draw_heatmap(*args, **kwargs):
×
1480
        data = kwargs.pop("data")
×
1481
        d = (
×
1482
            data
1483
            if len(args) == 0
1484
            # Any sorting should be performed before sending a DataArray in `fg.heatmap`
1485
            else data.pivot_table(
1486
                index=args[1], columns=args[0], values=args[2], sort=False
1487
            )
1488
        )
1489
        ax = sns.heatmap(d, **kwargs)
×
1490
        ax.set_xticklabels(
×
1491
            ax.get_xticklabels(),
1492
            rotation=45,
1493
            ha="right",
1494
            rotation_mode="anchor",
1495
        )
1496
        ax.tick_params(axis="both", direction="out")
×
1497
        set_plot_attrs(
×
1498
            use_attrs,
1499
            da,
1500
            ax,
1501
            title_loc="center",
1502
            wrap_kw={"min_line_len": 35, "max_line_len": 44},
1503
        )
1504
        return ax
×
1505

1506
    if ax is not None:
×
1507
        ax = draw_heatmap(data=df, ax=ax, **plot_kw)
×
1508
        return ax
×
1509
    elif "col" in plot_kw or "row" in plot_kw:
×
1510
        # When using xarray's FacetGrid, `plot_kw` can be used in the FacetGrid and in the plotting function
1511
        # With Seaborn, we need to be more careful and separate keywords.
1512
        plot_kw_hm = {
×
1513
            k: v for k, v in plot_kw.items() if k in signature(sns.heatmap).parameters
1514
        }
1515
        plot_kw_fg = {
×
1516
            k: v for k, v in plot_kw.items() if k in signature(sns.FacetGrid).parameters
1517
        }
1518
        unused_keys = (
×
1519
            set(plot_kw.keys()) - set(plot_kw_fg.keys()) - set(plot_kw_hm.keys())
1520
        )
1521
        if unused_keys != set():
×
1522
            raise ValueError(
×
1523
                f"`heatmap` got unexpected keywords in `plot_kw`: {unused_keys}. Keywords in `plot_kw` should be keywords "
1524
                "allowed in `sns.heatmap` or `sns.FacetGrid`. "
1525
            )
1526

1527
        g = sns.FacetGrid(df, **plot_kw_fg)
×
1528
        cax = g.fig.add_axes([0.95, 0.05, 0.02, 0.9])
×
1529
        g.map_dataframe(
×
1530
            draw_heatmap,
1531
            *heatmap_dims,
1532
            da_name,
1533
            **plot_kw_hm,
1534
            cbar=True,
1535
            cbar_ax=cax,
1536
        )
1537
        g.fig.subplots_adjust(right=0.9)
×
1538
        if "figsize" in fig_kw.keys():
×
1539
            g.fig.set_size_inches(*fig_kw["figsize"])
×
1540
        return g
×
1541

1542

1543
def scattermap(
6✔
1544
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1545
    ax: matplotlib.axes.Axes | None = None,
1546
    use_attrs: dict[str, Any] | None = None,
1547
    fig_kw: dict[str, Any] | None = None,
1548
    plot_kw: dict[str, Any] | None = None,
1549
    projection: ccrs.Projection = ccrs.LambertConformal(),
1550
    transform: ccrs.Projection | None = None,
1551
    features: list[str] | dict[str, dict[str, Any]] | None = None,
1552
    geometries_kw: dict[str, Any] | None = None,
1553
    sizes: str | bool | None = None,
1554
    size_range: tuple = (10, 60),
1555
    cmap: str | matplotlib.colors.Colormap | None = None,
1556
    levels: int | None = None,
1557
    divergent: bool | int | float = False,
1558
    legend_kw: dict[str, Any] | None = None,
1559
    show_time: bool | str | int | tuple[float, float] = False,
1560
    frame: bool = False,
1561
    enumerate_subplots: bool = False,
1562
) -> matplotlib.axes.Axes:
1563
    """Make a scatter plot of georeferenced data on a map.
1564

1565
    Parameters
1566
    ----------
1567
    data : dict, DataArray or Dataset
1568
        Input data do plot. If dictionary, must have only one entry.
1569
    ax : matplotlib axis, optional
1570
        Matplotlib axis on which to plot, with the same projection as the one specified.
1571
    use_attrs : dict, optional
1572
        Dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
1573
        Default value is {'title': 'description', 'cbar_label': 'long_name', 'cbar_units': 'units'}.
1574
        Only the keys found in the default dict can be used.
1575
    fig_kw : dict, optional
1576
        Arguments to pass to `plt.figure()`.
1577
    plot_kw :  dict, optional
1578
        Arguments to pass to `plt.scatter()`.
1579
        If 'data' is a dictionary, can be a dictionary with the same key as 'data'.
1580
    projection : ccrs.Projection
1581
        The projection to use, taken from the cartopy.crs options. Ignored if ax is not None.
1582
    transform : ccrs.Projection, optional
1583
        Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching
1584
        ccrs.PlateCarree() or ccrs.RotatedPole().
1585
    features : list or dict, optional
1586
        Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from
1587
        cartopy.feature: ['coastline', 'borders', 'lakes', 'land', 'ocean', 'rivers', 'states'].
1588
    geometries_kw : dict, optional
1589
        Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.
1590
    sizes : bool or str, optional
1591
        String name of the coordinate to use for determining point size. If True, use the same data as in the colorbar.
1592
    size_range : tuple
1593
        Tuple of the minimum and maximum size of the points.
1594
    cmap : matplotlib.colors.Colormap or str, optional
1595
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
1596
        If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray
1597
        or its 'history' attribute and use corresponding colormap, aligned with the IPCC Visual Style Guide 2022
1598
        (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
1599
    levels : int, optional
1600
        Number of levels to divide the colormap into.
1601
    divergent : bool or int or float
1602
        If int or float, becomes center of cmap. Default center is 0.
1603
    legend_kw : dict, optional
1604
        Arguments to pass to plt.legend(). Some defaults {"loc": "lower left", "facecolor": "w", "framealpha": 1,
1605
            "edgecolor": "w", "bbox_to_anchor": (-0.05, 0)}
1606
    show_time : bool, tuple, string or int.
1607
        If True, show time (as date) at the bottom right of the figure.
1608
        Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location
1609
        of the text. If a string or an int, the same values as those of the 'loc' parameter
1610
        of matplotlib's legends are accepted.
1611

1612
        ==================   =============
1613
        Location String      Location Code
1614
        ==================   =============
1615
        'upper right'        1
1616
        'upper left'         2
1617
        'lower left'         3
1618
        'lower right'        4
1619
        'right'              5
1620
        'center left'        6
1621
        'center right'       7
1622
        'lower center'       8
1623
        'upper center'       9
1624
        'center'             10
1625
        ==================   =============
1626
    frame : bool
1627
        Show or hide frame. Default False.
1628
    enumerate_subplots: bool
1629
        If True, enumerate subplots with letters.
1630
        Only works with facetgrids (pass `col` or `row` in plot_kw).
1631

1632
    Returns
1633
    -------
1634
    matplotlib.axes.Axes
1635
    """
1636
    # create empty dicts if None
1637
    use_attrs = empty_dict(use_attrs)
×
1638
    fig_kw = empty_dict(fig_kw)
×
1639
    plot_kw = empty_dict(plot_kw)
×
1640
    legend_kw = empty_dict(legend_kw)
×
1641

1642
    # set default use_attrs values
1643
    use_attrs = {"cbar_label": "long_name", "cbar_units": "units"} | use_attrs
×
1644
    if "row" not in plot_kw and "col" not in plot_kw:
×
1645
        use_attrs.setdefault("title", "description")
×
1646

1647
    # extract plot_kw from dict if needed
1648
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1649
        plot_kw = plot_kw[list(data.keys())[0]]
×
1650

1651
    # figanos does not use xr.plot.scatter default markersize
1652
    if "markersize" in plot_kw.keys():
×
1653
        if not sizes:
×
1654
            sizes = plot_kw["markersize"]
×
1655
        plot_kw.pop("markersize")
×
1656

1657
    # if data is dict, extract
1658
    if isinstance(data, dict):
×
1659
        if len(data) == 1:
×
1660
            data = list(data.values())[0].squeeze()
×
1661
            if len(data.data_vars) > 1:
×
1662
                warnings.warn(
×
1663
                    "data is xr.Dataset; only the first variable will be used in plot"
1664
                )
1665
        else:
1666
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1667

1668
    # select data to plot and its xr.Dataset
1669
    if isinstance(data, xr.DataArray):
×
1670
        plot_data = data
×
1671
        data = xr.Dataset({plot_data.name: plot_data})
×
1672
    elif isinstance(data, xr.Dataset):
×
1673
        if len(data.data_vars) > 1:
×
1674
            warnings.warn(
×
1675
                "data is xr.Dataset; only the first variable will be used in plot"
1676
            )
1677
        plot_data = data[list(data.keys())[0]]
×
1678
    else:
1679
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1680

1681
    # setup transform
1682
    if transform is None:
×
1683
        if "rlat" in data.dims and "rlon" in data.dims:
×
NEW
1684
            transform = get_rotpole(data)
×
1685
        elif (
×
1686
            "lat" in data.coords and "lon" in data.coords
1687
        ):  # need to work with station dims
1688
            transform = ccrs.PlateCarree()
×
1689

1690
    # setup fig, ax
1691
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
1692
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
1693
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
1694
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
1695
    elif ax is None:
×
1696
        plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1697
        cfig_kw = fig_kw.copy()
×
1698
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
1699
            plot_kw.setdefault("figsize", fig_kw["figsize"])
×
1700
            cfig_kw.pop("figsize")
×
1701
        if len(cfig_kw) >= 1:
×
1702
            plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1703
            warnings.warn(
×
1704
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid."
1705
            )
1706

1707
    # create cbar label
1708
    if (
×
1709
        "cbar_units" in use_attrs
1710
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1711
    ):  # avoids '[]' as label
1712
        cbar_label = (
×
1713
            get_attributes(use_attrs["cbar_label"], data)
1714
            + " ("
1715
            + get_attributes(use_attrs["cbar_units"], data)
1716
            + ")"
1717
        )
1718
    else:
1719
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1720

1721
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
1722
        plot_kw.setdefault("cbar_kwargs", {})
×
1723
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
1724
        plot_kw["cbar_kwargs"].setdefault("pad", 0.015)
×
1725

1726
    # colormap
1727
    if isinstance(cmap, str):
×
1728
        if cmap not in plt.colormaps():
×
1729
            try:
×
1730
                cmap = create_cmap(filename=cmap)
×
1731
            except FileNotFoundError as e:
×
1732
                logger.error(e)
×
1733
                pass
×
1734

1735
    elif cmap is None:
×
1736
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1737
        cmap = create_cmap(
×
1738
            get_var_group(path_to_json=cdata, da=plot_data),
1739
            divergent=divergent,
1740
        )
1741

1742
    # nans (not required for plotting since xarray.plot handles np.nan, but needs to be found for sizes legend and to
1743
    # inform user on how many stations were dropped)
1744
    mask = ~np.isnan(plot_data.values)
×
1745
    if np.sum(mask) < len(mask):
×
1746
        warnings.warn(
×
1747
            f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the color values"
1748
        )
1749

1750
    # point sizes
1751
    if sizes:
×
1752
        if sizes is True:
×
1753
            sdata = plot_data
×
1754
        elif isinstance(sizes, str):
×
1755
            if hasattr(data, "name") and getattr(data, "name") == sizes:
×
1756
                sdata = plot_data
×
1757
            elif sizes in list(data.coords.keys()):
×
1758
                sdata = plot_data[sizes]
×
1759
            else:
1760
                raise ValueError(f"{sizes} not found")
×
1761
        else:
1762
            raise TypeError("sizes must be a string or a bool")
×
1763

1764
        # nans sizes
1765
        smask = ~np.isnan(sdata.values) & mask
×
1766
        if np.sum(smask) < np.sum(mask):
×
1767
            warnings.warn(
×
1768
                f"{np.sum(mask) - np.sum(smask)} nan values were dropped when setting the point size"
1769
            )
1770
            mask = smask
×
1771

1772
        pt_sizes = norm2range(
×
1773
            data=sdata.where(mask).values,
1774
            target_range=size_range,
1775
            data_range=None,
1776
        )
1777
        plot_kw.setdefault("add_legend", False)
×
1778
        if ax:
×
1779
            plot_kw.setdefault("s", pt_sizes)
×
1780
        else:
1781
            plot_kw.setdefault("s", pt_sizes[0])
×
1782

1783
    # norm
1784
    plot_kw.setdefault("vmin", np.nanmin(plot_data.values[mask]))
×
1785
    plot_kw.setdefault("vmax", np.nanmax(plot_data.values[mask]))
×
1786
    if levels is not None:
×
1787
        if isinstance(levels, Iterable):
×
1788
            lin = levels
×
1789
        else:
1790
            lin = custom_cmap_norm(
×
1791
                cmap,
1792
                np.nanmin(plot_data.values[mask]),
1793
                np.nanmax(plot_data.values[mask]),
1794
                levels=levels,
1795
                divergent=divergent,
1796
                linspace_out=True,
1797
            )
1798
        plot_kw.setdefault("levels", lin)
×
1799

1800
    elif (divergent is not False) and ("levels" not in plot_kw):
×
1801
        norm = custom_cmap_norm(
×
1802
            cmap,
1803
            np.nanmin(plot_data.values[mask]),
1804
            np.nanmax(plot_data.values[mask]),
1805
            levels=levels,
1806
            divergent=divergent,
1807
        )
1808
        plot_kw.setdefault("norm", norm)
×
1809

1810
    # matplotlib.pyplot.scatter treats "edgecolor" and "edgecolors" as aliases so we accept "edgecolor" and convert it
1811
    if "edgecolor" in plot_kw and "edgecolors" not in plot_kw:
×
1812
        plot_kw["edgecolors"] = plot_kw["edgecolor"]
×
1813
        plot_kw.pop("edgecolor")
×
1814

1815
    # set defaults and create copy without vmin, vmax (conflicts with norm)
1816
    plot_kw = {
×
1817
        "cmap": cmap,
1818
        "transform": transform,
1819
        "zorder": 8,
1820
        "marker": "o",
1821
    } | plot_kw
1822

1823
    # check if edgecolors in plot_kw and match len of plot_data
1824
    if "edgecolors" in plot_kw:
×
1825
        if matplotlib.colors.is_color_like(plot_kw["edgecolors"]):
×
1826
            plot_kw["edgecolors"] = np.repeat(
×
1827
                plot_kw["edgecolors"], len(plot_data.where(mask).values)
1828
            )
1829
        elif len(plot_kw["edgecolors"]) != len(plot_data.values):
×
1830
            plot_kw["edgecolors"] = np.repeat(
×
1831
                plot_kw["edgecolors"][0], len(plot_data.where(mask).values)
1832
            )
1833
            warnings.warn(
×
1834
                "Length of edgecolors does not match length of data. Only first edgecolor is used for plotting."
1835
            )
1836
        else:
1837
            if isinstance(plot_kw["edgecolors"], list):
×
1838
                plot_kw["edgecolors"] = np.array(plot_kw["edgecolors"])
×
1839
            plot_kw["edgecolors"] = plot_kw["edgecolors"][mask]
×
1840
    else:
1841
        plot_kw.setdefault("edgecolors", "none")
×
1842

1843
    for key in ["vmin", "vmax"]:
×
1844
        plot_kw.pop(key)
×
1845
    # plot
1846
    plot_kw = {"x": "lon", "y": "lat", "hue": plot_data.name} | plot_kw
×
1847
    if ax:
×
1848
        plot_kw.setdefault("ax", ax)
×
1849

1850
    plot_data_masked = plot_data.where(mask).to_dataset()
×
1851
    im = plot_data_masked.plot.scatter(**plot_kw)
×
1852

1853
    # add features
1854
    if ax:
×
1855
        ax = add_features_map(
×
1856
            data,
1857
            ax,
1858
            use_attrs,
1859
            projection,
1860
            features,
1861
            geometries_kw,
1862
            frame,
1863
        )
1864

1865
        if show_time:
×
1866
            if isinstance(show_time, bool):
×
1867
                plot_coords(
×
1868
                    ax,
1869
                    plot_data,
1870
                    param="time",
1871
                    loc="lower right",
1872
                    backgroundalpha=1,
1873
                )
1874
            elif isinstance(show_time, (str, tuple, int)):
×
1875
                plot_coords(
×
1876
                    ax,
1877
                    plot_data,
1878
                    param="time",
1879
                    loc=show_time,
1880
                    backgroundalpha=1,
1881
                )
1882

1883
        if (frame is False) and (im.colorbar is not None):
×
1884
            im.colorbar.outline.set_visible(False)
×
1885

1886
    else:
1887
        for i, fax in enumerate(im.axs.flat):
×
1888
            fax = add_features_map(
×
1889
                data,
1890
                fax,
1891
                use_attrs,
1892
                projection,
1893
                features,
1894
                geometries_kw,
1895
                frame,
1896
            )
1897

1898
            if sizes:
×
1899
                # correct markersize for facetgrid
1900
                scat = fax.collections[0]
×
1901
                scat.set_sizes(pt_sizes[i])
×
1902

1903
        if (frame is False) and (im.cbar is not None):
×
1904
            im.cbar.outline.set_visible(False)
×
1905

1906
        if show_time:
×
1907
            if isinstance(show_time, bool):
×
1908
                plot_coords(
×
1909
                    None,
1910
                    plot_data,
1911
                    param="time",
1912
                    loc="lower right",
1913
                    backgroundalpha=1,
1914
                )
1915
            elif isinstance(show_time, (str, tuple, int)):
×
1916
                plot_coords(
×
1917
                    None,
1918
                    plot_data,
1919
                    param="time",
1920
                    loc=show_time,
1921
                    backgroundalpha=1,
1922
                )
1923

1924
    # size legend
1925
    if sizes:
×
1926
        legend_elements = size_legend_elements(
×
1927
            np.resize(sdata.values[mask], (sdata.values[mask].size, 1)),
1928
            np.resize(pt_sizes[mask], (pt_sizes[mask].size, 1)),
1929
            max_entries=6,
1930
            marker=plot_kw["marker"],
1931
        )
1932
        # legend spacing
1933
        if size_range[1] > 200:
×
1934
            ls = 0.5 + size_range[1] / 100 * 0.125
×
1935
        else:
1936
            ls = 0.5
×
1937

1938
        legend_kw = {
×
1939
            "loc": "lower left",
1940
            "facecolor": "w",
1941
            "framealpha": 1,
1942
            "edgecolor": "w",
1943
            "labelspacing": ls,
1944
            "handles": legend_elements,
1945
            "bbox_to_anchor": (-0.05, -0.1),
1946
        } | legend_kw
1947

1948
        if "title" not in legend_kw:
×
1949
            if hasattr(sdata, "long_name"):
×
1950
                lgd_title = wrap_text(
×
1951
                    getattr(sdata, "long_name"), min_line_len=1, max_line_len=15
1952
                )
1953
                if hasattr(sdata, "units"):
×
1954
                    lgd_title += f" ({getattr(sdata, 'units')})"
×
1955
            else:
1956
                lgd_title = sizes
×
1957
            legend_kw.setdefault("title", lgd_title)
×
1958

1959
        if ax:
×
1960
            lgd = ax.legend(**legend_kw)
×
1961
            lgd.set_zorder(11)
×
1962
        else:
1963
            im.figlegend = im.fig.legend(**legend_kw)
×
1964
        # im._adjust_fig_for_guide(im.figlegend)
1965

1966
    if ax:
×
1967
        return ax
×
1968
    else:
1969
        im.fig.suptitle(get_attributes("long_name", data))
×
1970
        im.set_titles(template="{value}")
×
1971
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
1972
            for idx, ax in enumerate(im.axs.flat):
×
1973
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
1974

1975
        return im
×
1976

1977

1978
def taylordiagram(
6✔
1979
    data: xr.DataArray | dict[str, xr.DataArray],
1980
    plot_kw: dict[str, Any] | None = None,
1981
    fig_kw: dict[str, Any] | None = None,
1982
    std_range: tuple = (0, 1.5),
1983
    contours: int | None = 4,
1984
    contours_kw: dict[str, Any] | None = None,
1985
    ref_std_line: bool = False,
1986
    legend_kw: dict[str, Any] | None = None,
1987
    std_label: str | None = None,
1988
    corr_label: str | None = None,
1989
    colors_key: str | None = None,
1990
    markers_key: str | None = None,
1991
):
1992
    """Build a Taylor diagram.
1993

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

1996
    Parameters
1997
    ----------
1998
    data : xr.DataArray or dict
1999
        DataArray or dictionary of DataArrays created by xclim.sdba.measures.taylordiagram, each corresponding
2000
        to a point on the diagram. The dictionary keys will become their labels.
2001
    plot_kw : dict, optional
2002
        Arguments to pass to the `plot()` function. Changes how the markers look.
2003
        If 'data' is a dictionary, must be a nested dictionary with the same keys as 'data'.
2004
    fig_kw : dict, optional
2005
        Arguments to pass to `plt.figure()`.
2006
    std_range : tuple
2007
        Range of the x and y axes, in units of the highest standard deviation in the data.
2008
    contours : int, optional
2009
        Number of rsme contours to plot.
2010
    contours_kw : dict, optional
2011
        Arguments to pass to `plt.contour()` for the rmse contours.
2012
    ref_std_line : bool, optional
2013
        If True, draws a circular line on radius `std = ref_std`. Default: False
2014
    legend_kw : dict, optional
2015
        Arguments to pass to `plt.legend()`.
2016
    std_label : str, optional
2017
        Label for the standard deviation (x and y) axes.
2018
    corr_label : str, optional
2019
        Label for the correlation axis.
2020
    colors_key : str, optional
2021
        Attribute or dimension of DataArrays used to separate DataArrays into groups with different colors. If present,
2022
        it overrides the "color" key in `plot_kw`.
2023
    markers_key : str, optional
2024
        Attribute or dimension of DataArrays used to separate DataArrays into groups with different markers. If present,
2025
        it overrides the "marker" key in `plot_kw`.
2026

2027
    Returns
2028
    -------
2029
    (plt.figure, mpl_toolkits.axisartist.floating_axes.FloatingSubplot, plt.legend)
2030
    """
2031
    plot_kw = empty_dict(plot_kw)
×
2032
    fig_kw = empty_dict(fig_kw)
×
2033
    contours_kw = empty_dict(contours_kw)
×
2034
    legend_kw = empty_dict(legend_kw)
×
2035

2036
    # preserve order of dimensions if used for marker/color
2037
    ordered_markers_type = None
×
2038
    ordered_colors_type = None
×
2039

2040
    # convert SSP, RCP, CMIP formats in keys
2041
    if isinstance(data, dict):
×
2042
        data = process_keys(data, convert_scen_name)
×
2043
    if isinstance(plot_kw, dict):
×
2044
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
2045

2046
    # if only one data input, insert in dict.
2047
    if not isinstance(data, dict):
×
2048
        data = {"_no_label": data}  # mpl excludes labels starting with "_" from legend
×
2049
        plot_kw = {"_no_label": empty_dict(plot_kw)}
×
2050
    elif not plot_kw:
×
2051
        plot_kw = {k: {} for k in data.keys()}
×
2052
    # check type
2053
    for key, v in data.items():
×
2054
        if not isinstance(v, xr.DataArray):
×
2055
            raise TypeError("All objects in 'data' must be xarray DataArrays.")
×
2056
        if "taylor_param" not in v.dims:
×
2057
            raise ValueError("All DataArrays must contain a 'taylor_param' dimension.")
×
2058
        if key == "reference":
×
2059
            raise ValueError("'reference' is not allowed as a key in data.")
×
2060

2061
    # If there are other dimensions than 'taylor_param', create a bigger dict with them
2062
    data_keys = list(data.keys())
×
2063
    for data_key in data_keys:
×
2064
        da = data[data_key]
×
2065
        dims = list(set(da.dims) - {"taylor_param"})
×
2066
        if dims != []:
×
2067
            if markers_key in dims:
×
2068
                ordered_markers_type = da[markers_key].values
×
2069
            if colors_key in dims:
×
2070
                ordered_colors_type = da[colors_key].values
×
2071

2072
            da = da.stack(pl_dims=dims)
×
2073
            for i, dim_key in enumerate(da.pl_dims.values):
×
2074
                if isinstance(dim_key, list) or isinstance(dim_key, tuple):
×
2075
                    dim_key = "-".join([str(k) for k in dim_key])
×
2076
                da0 = da.isel(pl_dims=i)
×
2077
                # if colors_key/markers_key is a dimension, add it as an attribute for later use
2078
                if markers_key in dims:
×
2079
                    da0.attrs[markers_key] = da0[markers_key].values.item()
×
2080
                if colors_key in dims:
×
2081
                    da0.attrs[colors_key] = da0[colors_key].values.item()
×
2082
                new_data_key = (
×
2083
                    f"{data_key}-{dim_key}" if data_key != "_no_label" else dim_key
2084
                )
2085
                data[new_data_key] = da0
×
2086
                plot_kw[new_data_key] = empty_dict(plot_kw[f"{data_key}"])
×
2087
            data.pop(data_key)
×
2088
            plot_kw.pop(data_key)
×
2089

2090
    # remove negative correlations
2091
    initial_len = len(data)
×
2092
    removed = [
×
2093
        key for key, da in data.items() if da.sel(taylor_param="corr").values < 0
2094
    ]
2095
    data = {
×
2096
        key: da for key, da in data.items() if da.sel(taylor_param="corr").values >= 0
2097
    }
2098
    if len(data) != initial_len:
×
2099
        warnings.warn(
×
2100
            f"{initial_len - len(data)} points with negative correlations will not be plotted: {', '.join(removed)}"
2101
        )
2102

2103
    # add missing keys to plot_kw
2104
    for key in data.keys():
×
2105
        if key not in plot_kw:
×
2106
            plot_kw[key] = {}
×
2107

2108
    # extract ref to be used in plot
2109
    ref_std = list(data.values())[0].sel(taylor_param="ref_std").values
×
2110
    # check if ref is the same in all DataArrays and get the highest std (for ax limits)
2111
    if len(data) > 1:
×
2112
        for key, da in data.items():
×
2113
            if da.sel(taylor_param="ref_std").values != ref_std:
×
2114
                raise ValueError(
×
2115
                    "All reference standard deviation values must be identical"
2116
                )
2117

2118
    # get highest std for axis limits
2119
    max_std = [ref_std]
×
2120
    for key, da in data.items():
×
2121
        max_std.append(
×
2122
            float(
2123
                max(
2124
                    da.sel(taylor_param="ref_std").values,
2125
                    da.sel(taylor_param="sim_std").values,
2126
                )
2127
            )
2128
        )
2129

2130
    # make labels
2131
    if not std_label:
×
2132
        try:
×
2133
            units = list(data.values())[0].units
×
2134
            std_label = get_localized_term("standard deviation")
×
2135
            std_label = std_label if units == "" else f"{std_label} ({units})"
×
2136
        except AttributeError:
×
2137
            std_label = get_localized_term("standard deviation").capitalize()
×
2138

2139
    if not corr_label:
×
2140
        try:
×
2141
            if "Pearson" in list(data.values())[0].correlation_type:
×
2142
                corr_label = get_localized_term("pearson correlation").capitalize()
×
2143
            else:
2144
                corr_label = get_localized_term("correlation").capitalize()
×
2145
        except AttributeError:
×
2146
            corr_label = get_localized_term("correlation").capitalize()
×
2147

2148
    # build diagram
2149
    transform = PolarAxes.PolarTransform()
×
2150

2151
    # Setup the axis, here we map angles in degrees to angles in radius
2152
    # Correlation labels
2153
    rlocs = np.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
×
2154
    tlocs = np.arccos(rlocs)  # Conversion to polar angles
×
2155
    gl1 = gf.FixedLocator(tlocs)  # Positions
×
2156
    tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, rlocs))))
×
2157
    # Standard deviation axis extent
2158
    radius_min = std_range[0] * max(max_std)
×
2159
    radius_max = std_range[1] * max(max_std)
×
2160

2161
    # Set up the axes range in the parameter "extremes"
2162
    ghelper = GridHelperCurveLinear(
×
2163
        transform,
2164
        extremes=(0, np.pi / 2, radius_min, radius_max),
2165
        grid_locator1=gl1,
2166
        tick_formatter1=tf1,
2167
    )
2168

2169
    fig = plt.figure(**fig_kw)
×
2170
    floating_ax = FloatingSubplot(fig, 111, grid_helper=ghelper)
×
2171
    fig.add_subplot(floating_ax)
×
2172

2173
    # Adjust axes
2174
    floating_ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
×
2175
    floating_ax.axis["top"].toggle(ticklabels=True, label=True)
×
2176
    floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
×
2177
    floating_ax.axis["top"].label.set_axis_direction("top")
×
2178
    floating_ax.axis["top"].label.set_text(corr_label)
×
2179

2180
    floating_ax.axis["left"].set_axis_direction("bottom")  # "X axis"
×
2181
    floating_ax.axis["left"].label.set_text(std_label)
×
2182

2183
    floating_ax.axis["right"].set_axis_direction("top")  # "Y axis"
×
2184
    floating_ax.axis["right"].toggle(ticklabels=True, label=True)
×
2185
    floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
×
2186
    floating_ax.axis["right"].label.set_text(std_label)
×
2187

2188
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2189

2190
    # Contours along standard deviations
2191
    floating_ax.grid(visible=True, alpha=0.4)
×
2192
    floating_ax.set_title("")
×
2193

2194
    ax = floating_ax.get_aux_axes(transform)  # return the axes that can be plotted on
×
2195

2196
    # plot reference
2197
    if "reference" in plot_kw:
×
2198
        ref_kw = plot_kw.pop("reference")
×
2199
    else:
2200
        ref_kw = {}
×
2201
    ref_kw = {
×
2202
        "color": "#154504",
2203
        "marker": "s",
2204
        "label": get_localized_term("reference"),
2205
    } | ref_kw
2206

2207
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2208

2209
    points = [ref_pt]  # set up for later
×
2210

2211
    # plot a circular line along `ref_std`
2212
    if ref_std_line:
×
2213
        angles_for_line = np.linspace(0, np.pi / 2, 100)
×
2214
        radii_for_line = np.full_like(angles_for_line, ref_std)
×
2215
        ax.plot(
×
2216
            angles_for_line,
2217
            radii_for_line,
2218
            color=ref_kw["color"],
2219
            linewidth=0.5,
2220
            linestyle="-",
2221
        )
2222

2223
    # rmse contours from reference standard deviation
2224
    if contours:
×
2225
        radii, angles = np.meshgrid(
×
2226
            np.linspace(radius_min, radius_max),
2227
            np.linspace(0, np.pi / 2),
2228
        )
2229
        # Compute centered RMS difference
2230
        rms = np.sqrt(ref_std**2 + radii**2 - 2 * ref_std * radii * np.cos(angles))
×
2231

2232
        contours_kw = {"linestyles": "--", "linewidths": 0.5} | contours_kw
×
2233
        ct = ax.contour(angles, radii, rms, levels=contours, **contours_kw)
×
2234

2235
        ax.clabel(ct, ct.levels, fontsize=8)
×
2236

2237
        # points.append(ct_line)
2238
        ct_line = ax.plot(
×
2239
            [0],
2240
            [0],
2241
            ls=contours_kw["linestyles"],
2242
            lw=1,
2243
            c="k" if "colors" not in contours_kw else contours_kw["colors"],
2244
            label="rmse",
2245
        )
2246
        points.append(ct_line[0])
×
2247

2248
    # get color options
2249
    style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
2250
    if len(data) > len(style_colors):
×
2251
        style_colors = style_colors * math.ceil(len(data) / len(style_colors))
×
2252
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
2253
    # get marker options (only used if `markers_key` is set)
2254
    style_markers = "oDv^<>p*hH+x|_"
×
2255
    if len(data) > len(style_markers):
×
2256
        style_markers = style_markers * math.ceil(len(data) / len(style_markers))
×
2257

2258
    # set colors and markers styles based on discrimnating attributes (if specified)
2259
    if colors_key or markers_key:
×
2260
        if colors_key:
×
2261
            # get_scen_color : look for SSP, RCP, CMIP model color
2262
            colors_type = (
×
2263
                ordered_colors_type
2264
                if ordered_colors_type is not None
2265
                else {da.attrs[colors_key] for da in data.values()}
2266
            )
2267
            colorsd = {
×
2268
                k: get_scen_color(k, cat_colors) or style_colors[i]
2269
                for i, k in enumerate(colors_type)
2270
            }
2271
        if markers_key:
×
2272
            markers_type = (
×
2273
                ordered_markers_type
2274
                if ordered_markers_type is not None
2275
                else {da.attrs[markers_key] for da in data.values()}
2276
            )
2277
            markersd = {k: style_markers[i] for i, k in enumerate(markers_type)}
×
2278

2279
        for key, da in data.items():
×
2280
            if colors_key:
×
2281
                plot_kw[key]["color"] = colorsd[da.attrs[colors_key]]
×
2282
            if markers_key:
×
2283
                plot_kw[key]["marker"] = markersd[da.attrs[markers_key]]
×
2284

2285
    # plot scatter
2286
    for (key, da), i in zip(data.items(), range(len(data))):
×
2287
        # look for SSP, RCP, CMIP model color
2288
        if colors_key is None:
×
2289
            plot_kw[key].setdefault(
×
2290
                "color", get_scen_color(key, cat_colors) or style_colors[i]
2291
            )
2292
        # set defaults
2293
        plot_kw[key] = {"label": key} | plot_kw[key]
×
2294

2295
        # legend will be handled later in this case
2296
        if markers_key or colors_key:
×
2297
            plot_kw[key]["label"] = ""
×
2298

2299
        # plot
2300
        pt = ax.scatter(
×
2301
            np.arccos(da.sel(taylor_param="corr").values),
2302
            da.sel(taylor_param="sim_std").values,
2303
            **plot_kw[key],
2304
        )
2305
        points.append(pt)
×
2306

2307
    # legend
2308
    legend_kw.setdefault("loc", "upper right")
×
2309
    legend = fig.legend(points, [pt.get_label() for pt in points], **legend_kw)
×
2310

2311
    # plot new legend if markers/colors represent a certain dimension
2312
    if colors_key or markers_key:
×
2313
        handles = list(floating_ax.get_legend_handles_labels()[0])
×
2314
        if markers_key:
×
2315
            for k, m in markersd.items():
×
2316
                handles.append(Line2D([0], [0], color="k", label=k, marker=m, ls=""))
×
2317
        if colors_key:
×
2318
            for k, c in colorsd.items():
×
2319
                handles.append(Line2D([0], [0], color=c, label=k, ls="-"))
×
2320
        legend.remove()
×
2321
        legend = fig.legend(handles=handles, **legend_kw)
×
2322

2323
    return fig, floating_ax, legend
×
2324

2325

2326
def hatchmap(
6✔
2327
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
2328
    ax: matplotlib.axes.Axes | None = None,
2329
    use_attrs: dict[str, Any] | None = None,
2330
    fig_kw: dict[str, Any] | None = None,
2331
    plot_kw: dict[str, Any] | None = None,
2332
    projection: ccrs.Projection = ccrs.LambertConformal(),
2333
    transform: ccrs.Projection | None = None,
2334
    features: list[str] | dict[str, dict[str, Any]] | None = None,
2335
    geometries_kw: dict[str, Any] | None = None,
2336
    levels: int | None = None,
2337
    legend_kw: dict[str, Any] | bool = True,
2338
    show_time: bool | str | int | tuple[float, float] = False,
2339
    frame: bool = False,
2340
    enumerate_subplots: bool = False,
2341
) -> matplotlib.axes.Axes:
2342
    """Create map of hatches from 2D data.
2343

2344
    Parameters
2345
    ----------
2346
    data : dict, DataArray or Dataset
2347
        Input data do plot.
2348
    ax : matplotlib axis, optional
2349
        Matplotlib axis on which to plot, with the same projection as the one specified.
2350
    use_attrs : dict, optional
2351
        Dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
2352
        Default value is {'title': 'description'}.
2353
        Only the keys found in the default dict can be used.
2354
    fig_kw : dict, optional
2355
        Arguments to pass to `plt.figure()`.
2356
    plot_kw:  dict, optional
2357
        Arguments to pass to 'xarray.plot.contourf()' function.
2358
        If 'data' is a dictionary, can be a nested dictionary with the same keys as 'data'.
2359
    projection : ccrs.Projection
2360
        The projection to use, taken from the cartopy.ccrs options. Ignored if ax is not None.
2361
    transform : ccrs.Projection, optional
2362
        Transform corresponding to the data coordinate system. If None, an attempt is made to find dimensions matching
2363
        ccrs.PlateCarree() or ccrs.RotatedPole().
2364
    features : list or dict, optional
2365
        Features to use, as a list or a nested dict containing kwargs. Options are the predefined features from
2366
        cartopy.feature: ['coastline', 'borders', 'lakes', 'land', 'ocean', 'rivers', 'states'].
2367
    geometries_kw : dict, optional
2368
        Arguments passed to cartopy ax.add_geometry() which adds given geometries (GeoDataFrame geometry) to axis.
2369
    legend_kw : dict or boolean, optional
2370
        Arguments to pass to `ax.legend()`. No legend is added if legend_kw == False.
2371
    show_time : bool, tuple, string or int.
2372
        If True, show time (as date) at the bottom right of the figure.
2373
        Can be a tuple of axis coordinates (0 to 1, as a fraction of the axis length) representing the location
2374
        of the text. If a string or an int, the same values as those of the 'loc' parameter
2375
        of matplotlib's legends are accepted.
2376

2377
        ==================   =============
2378
        Location String      Location Code
2379
        ==================   =============
2380
        'upper right'        1
2381
        'upper left'         2
2382
        'lower left'         3
2383
        'lower right'        4
2384
        'right'              5
2385
        'center left'        6
2386
        'center right'       7
2387
        'lower center'       8
2388
        'upper center'       9
2389
        'center'             10
2390
        ==================   =============
2391
    frame : bool
2392
        Show or hide frame. Default False.
2393
    enumerate_subplots: bool
2394
        If True, enumerate subplots with letters.
2395
        Only works with facetgrids (pass `col` or `row` in plot_kw).
2396

2397
    Returns
2398
    -------
2399
    matplotlib.axes.Axes
2400
    """
2401
    # default hatches
2402
    dfh = [
×
2403
        "/",
2404
        "\\",
2405
        "|",
2406
        "-",
2407
        "+",
2408
        "x",
2409
        "o",
2410
        "O",
2411
        ".",
2412
        "*",
2413
        "//",
2414
        "\\\\",
2415
        "||",
2416
        "--",
2417
        "++",
2418
        "xx",
2419
        "oo",
2420
        "OO",
2421
        "..",
2422
        "**",
2423
    ]
2424

2425
    # create empty dicts if None
2426
    use_attrs = empty_dict(use_attrs)
×
2427
    fig_kw = empty_dict(fig_kw)
×
2428
    plot_kw = empty_dict(plot_kw)
×
2429
    legend_kw = empty_dict(legend_kw)
×
2430

2431
    dattrs = None
×
2432
    plot_data = {}
×
2433

2434
    # convert data to dict (if not one)
2435
    if not isinstance(data, dict):
×
2436
        if isinstance(data, xr.DataArray):
×
2437
            plot_data = {data.name: data}
×
2438
            if data.name not in plot_kw.keys():
×
2439
                plot_kw = {data.name: plot_kw}
×
2440
        elif isinstance(data, xr.Dataset):
×
2441
            dattrs = data
×
2442
            plot_data = {var: data[var] for var in data.data_vars}
×
2443
            for v in plot_data.keys():
×
2444
                if v not in plot_kw.keys():
×
2445
                    plot_kw[v] = plot_kw
×
2446
    else:
2447
        for k, v in data.items():
×
2448
            if k not in plot_kw.keys():
×
2449
                plot_kw[k] = plot_kw
×
2450
            if isinstance(v, xr.Dataset):
×
2451
                dattrs = k
×
2452
                plot_data[k] = v[list(v.data_vars)[0]]
×
2453
                warnings.warn("Only first variable of Dataset is plotted.")
×
2454
            else:
2455
                plot_data[k] = v
×
2456

2457
    # setup transform from first data entry
2458
    trdata = list(plot_data.values())[0]
×
2459
    if transform is None:
×
2460
        if "lat" in trdata.dims and "lon" in trdata.dims:
×
2461
            transform = ccrs.PlateCarree()
×
2462
        elif "rlat" in trdata.dims and "rlon" in trdata.dims:
×
NEW
2463
            transform = get_rotpole(list(plot_data.values())[0])
×
2464

2465
    # bug xlim / ylim + transform in facetgrids
2466
    # (see https://github.com/pydata/xarray/issues/8562#issuecomment-1865189766)
2467
    if transform and (
×
2468
        "xlim" in list(plot_kw.values())[0] and "ylim" in list(plot_kw.values())[0]
2469
    ):
2470
        extent = [
×
2471
            list(plot_kw.values())[0]["xlim"][0],
2472
            list(plot_kw.values())[0]["xlim"][1],
2473
            list(plot_kw.values())[0]["ylim"][0],
2474
            list(plot_kw.values())[0]["ylim"][1],
2475
        ]
2476
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2477

2478
    elif transform and (
×
2479
        "xlim" in list(plot_kw.values())[0] or "ylim" in list(plot_kw.values())[0]
2480
    ):
2481
        extent = None
×
2482
        warnings.warn(
×
2483
            "Requires both xlim and ylim with 'transform'. Xlim or ylim was dropped"
2484
        )
2485
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2486

2487
    else:
2488
        extent = None
×
2489

2490
    # setup fig, ax
2491
    if ax is None and (
×
2492
        "row" not in list(plot_kw.values())[0].keys()
2493
        and "col" not in list(plot_kw.values())[0].keys()
2494
    ):
2495
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
2496
    elif ax is not None and (
×
2497
        "col" in list(plot_kw.values())[0].keys()
2498
        or "row" in list(plot_kw.values())[0].keys()
2499
    ):
2500
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
2501
    elif ax is None:
×
2502
        [
×
2503
            v.setdefault("subplot_kws", {}).setdefault("projection", projection)
2504
            for v in plot_kw.values()
2505
        ]
2506
        cfig_kw = copy.deepcopy(fig_kw)
×
2507
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
2508
            plot_kw[0].setdefault("figsize", fig_kw["figsize"])
×
2509
            cfig_kw.pop("figsize")
×
2510
        if cfig_kw:
×
2511
            for v in plot_kw.values():
×
2512
                {"subplots_kws": cfig_kw} | v
×
2513
            warnings.warn(
×
2514
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid."
2515
            )
2516

2517
    pat_leg = []
×
2518
    n = 0
×
2519
    for k, v in plot_data.items():
×
2520
        # if levels plot multiple hatching from one data entry
2521
        if "levels" in plot_kw[k] and len(plot_data) == 1:
×
2522
            # nans
2523
            mask = ~np.isnan(v.values)
×
2524
            if np.sum(mask) < len(mask):
×
2525
                warnings.warn(
×
2526
                    f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the pattern values"
2527
                )
2528
            if "hatches" in plot_kw[k] and plot_kw[k]["levels"] != len(
×
2529
                plot_kw[k]["hatches"]
2530
            ):
2531
                warnings.warn("Hatches number is not equivalent to number of levels")
×
2532
                hatches = dfh[0:levels]
×
2533
            if "hatches" not in plot_kw[k]:
×
2534
                hatches = dfh[0:levels]
×
2535

2536
            plot_kw[k] = {
×
2537
                "hatches": hatches,
2538
                "colors": "none",
2539
                "add_colorbar": False,
2540
            } | plot_kw[k]
2541

2542
            if "lat" in v.dims:
×
2543
                v.coords["mask"] = (("lat", "lon"), mask)
×
2544
            else:
2545
                v.coords["mask"] = (("rlat", "rlon"), mask)
×
2546

2547
            plot_kw[k].setdefault("transform", transform)
×
2548
            if ax:
×
2549
                plot_kw[k].setdefault("ax", ax)
×
2550

2551
            im = v.where(mask is not True).plot.contourf(**plot_kw[k])
×
2552
            artists, labels = im.legend_elements(str_format="{:2.1f}".format)
×
2553

2554
            if ax and legend_kw:
×
2555
                ax.legend(artists, labels, **legend_kw)
×
2556
            elif legend_kw:
×
2557
                im.figlegend = im.fig.legend(**legend_kw)
×
2558

2559
        elif len(plot_data) > 1 and "levels" in plot_kw[k]:
×
2560
            raise TypeError(
×
2561
                "To plot levels only one xr.DataArray or xr.Dataset accepted"
2562
            )
2563
        else:
2564
            # since pattern remove colors and colorbar from plotting (done by gridmap)
2565
            plot_kw[k] = {"colors": "none", "add_colorbar": False} | plot_kw[k]
×
2566

2567
            if "hatches" not in plot_kw[k].keys():
×
2568
                plot_kw[k]["hatches"] = dfh[n]
×
2569
                n += 1
×
2570
            elif isinstance(
×
2571
                plot_kw[k]["hatches"], str
2572
            ):  # make sure the hatches are in a list
2573
                warnings.warn(
×
2574
                    "Hatches argument must be of type 'list'. Wrapping string argument as list."
2575
                )
2576
                plot_kw[k]["hatches"] = [plot_kw[k]["hatches"]]
×
2577

2578
            plot_kw[k].setdefault("transform", transform)
×
2579
            if ax:
×
2580
                im = v.plot.contourf(ax=ax, **plot_kw[k])
×
2581

2582
            if not ax:
×
2583
                if k == list(plot_data.keys())[0]:
×
2584
                    im = v.plot.contourf(**plot_kw[k])
×
2585

2586
                for i, fax in enumerate(im.axs.flat):
×
2587
                    if len(plot_data) > 1 and k != list(plot_data.keys())[0]:
×
2588
                        # select data to plot from DataSet in loop to plot on facetgrids axis
2589
                        c_pkw = plot_kw[k].copy()
×
2590
                        c_pkw.pop("subplot_kws")
×
2591
                        sel = {}
×
2592
                        if "row" in c_pkw.keys():
×
2593
                            sel[c_pkw["row"]] = i
×
2594
                            c_pkw.pop("row")
×
2595
                        elif "col" in c_pkw.keys():
×
2596
                            sel[c_pkw["col"]] = i
×
2597
                            c_pkw.pop("col")
×
2598
                        v.isel(sel).plot.contourf(ax=fax, **c_pkw)
×
2599

2600
                    if k == list(plot_data.keys())[-1]:
×
2601
                        add_features_map(
×
2602
                            dattrs,
2603
                            fax,
2604
                            use_attrs,
2605
                            projection,
2606
                            features,
2607
                            geometries_kw,
2608
                            frame,
2609
                        )
2610
                        if extent:
×
2611
                            fax.set_extent(extent)
×
2612

2613
            pat_leg.append(
×
2614
                matplotlib.patches.Patch(
2615
                    hatch=plot_kw[k]["hatches"][0], fill=False, label=k
2616
                )
2617
            )
2618

2619
    if pat_leg and legend_kw:
×
2620
        legend_kw = {
×
2621
            "loc": "lower right",
2622
            "handleheight": 2,
2623
            "handlelength": 4,
2624
        } | legend_kw
2625

2626
        if ax and legend_kw:
×
2627
            ax.legend(handles=pat_leg, **legend_kw)
×
2628
        elif legend_kw:
×
2629
            im.figlegend = im.fig.legend(handles=pat_leg, **legend_kw)
×
2630

2631
    # add features
2632
    if ax:
×
2633
        if extent:
×
2634
            ax.set_extent(extent)
×
2635
        if dattrs:
×
2636
            use_attrs.setdefault("title", "description")
×
2637

2638
        ax = add_features_map(
×
2639
            dattrs,
2640
            ax,
2641
            use_attrs,
2642
            projection,
2643
            features,
2644
            geometries_kw,
2645
            frame,
2646
        )
2647

2648
        if show_time:
×
2649
            if isinstance(show_time, bool):
×
2650
                plot_coords(
×
2651
                    ax,
2652
                    plot_data,
2653
                    param="time",
2654
                    loc="lower right",
2655
                    backgroundalpha=1,
2656
                )
2657
            elif isinstance(show_time, (str, tuple, int)):
×
2658
                plot_coords(
×
2659
                    ax,
2660
                    plot_data,
2661
                    param="time",
2662
                    loc=show_time,
2663
                    backgroundalpha=1,
2664
                )
2665

2666
        # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
2667
        if (frame is False) and (
×
2668
            (getattr(im, "colorbar", None) is not None)
2669
            or (getattr(im, "cbar", None) is not None)
2670
        ):
2671
            im.colorbar.outline.set_visible(False)
×
2672

2673
            set_plot_attrs(use_attrs, dattrs, ax, wrap_kw={"max_line_len": 60})
×
2674
        return ax
×
2675

2676
    else:
2677
        # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
2678
        if (frame is False) and (
×
2679
            (getattr(im, "colorbar", None) is not None)
2680
            or (getattr(im, "cbar", None) is not None)
2681
        ):
2682
            im.cbar.outline.set_visible(False)
×
2683

2684
        if show_time:
×
2685
            if show_time is True:
×
2686
                plot_coords(
×
2687
                    None,
2688
                    dattrs,
2689
                    param="time",
2690
                    loc="lower right",
2691
                    backgroundalpha=1,
2692
                )
2693
            elif isinstance(show_time, (str, tuple, int)):
×
2694
                plot_coords(
×
2695
                    None, dattrs, param="time", loc=show_time, backgroundalpha=1
2696
                )
2697
        if dattrs:
×
2698
            use_attrs.setdefault("suptitle", "long_name")
×
2699
            set_plot_attrs(use_attrs, dattrs, facetgrid=im)
×
2700

2701
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
2702
            for idx, ax in enumerate(im.axs.flat):
×
2703
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
2704

2705
        return im
×
2706

2707

2708
def _add_lead_time_coord(da, ref):
6✔
2709
    """Add a lead time coordinate to the data. Modifies da in-place."""
2710
    lead_time = da.time.dt.year - int(ref)
×
2711
    da["Lead time"] = lead_time
×
2712
    da["Lead time"].attrs["units"] = f"years from {ref}"
×
2713
    return lead_time
×
2714

2715

2716
def partition(
6✔
2717
    data: xr.DataArray | xr.Dataset,
2718
    ax: matplotlib.axes.Axes | None = None,
2719
    start_year: str | None = None,
2720
    show_num: bool = True,
2721
    fill_kw: dict[str, Any] | None = None,
2722
    line_kw: dict[str, Any] | None = None,
2723
    fig_kw: dict[str, Any] | None = None,
2724
    legend_kw: dict[str, Any] | None = None,
2725
) -> matplotlib.axes.Axes:
2726
    """Figure of the partition of total uncertainty by components.
2727

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

2731
    Parameters
2732
    ----------
2733
    data : xr.DataArray or xr.Dataset
2734
        Variance over time of the different components of uncertainty.
2735
        Output of a `xclim.ensembles._partitioning` function.
2736
    ax : matplotlib axis, optional
2737
        Matplotlib axis on which to plot.
2738
    start_year : str
2739
        If None, the x-axis will be the time in year.
2740
        If str, the x-axis will show the number of year since start_year.
2741
    show_num : bool
2742
        If True, show the number of elements for each uncertainty components in parentheses in the legend.
2743
        `data` should have attributes named after the components with a list of its the elements.
2744
    fill_kw : dict
2745
        Keyword arguments passed to `ax.fill_between`.
2746
        It is possible to pass a dictionary of keywords for each component (uncertainty coordinates).
2747
    line_kw : dict
2748
        Keyword arguments passed to `ax.plot` for the lines in between the components.
2749
        The default is {color="k", lw=2}. We recommend always using lw>=2.
2750
    fig_kw : dict
2751
        Keyword arguments passed to `plt.subplots`.
2752
    legend_kw : dict
2753
        Keyword arguments passed to `ax.legend`.
2754

2755
    Returns
2756
    -------
2757
    mpl.axes.Axes
2758
    """
2759
    if isinstance(data, xr.Dataset):
×
2760
        if len(data.data_vars) > 1:
×
2761
            warnings.warn(
×
2762
                "data is xr.Dataset; only the first variable will be used in plot"
2763
            )
2764
        data = data[list(data.keys())[0]].squeeze()
×
2765

2766
    if data.attrs["units"] != "%":
×
2767
        raise ValueError(
×
2768
            "The units are not %. Use `fraction=True` in the xclim function call."
2769
        )
2770

2771
    fill_kw = empty_dict(fill_kw)
×
2772
    line_kw = empty_dict(line_kw)
×
2773
    fig_kw = empty_dict(fig_kw)
×
2774
    legend_kw = empty_dict(legend_kw)
×
2775

2776
    # select data to plot
2777
    if isinstance(data, xr.DataArray):
×
2778
        data = data.squeeze()
×
2779
    elif isinstance(data, xr.Dataset):  # in case, it was saved to disk before plotting.
×
2780
        if len(data.data_vars) > 1:
×
2781
            warnings.warn(
×
2782
                "data is xr.Dataset; only the first variable will be used in plot"
2783
            )
2784
        data = data[list(data.keys())[0]].squeeze()
×
2785
    else:
2786
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2787

2788
    if ax is None:
×
2789
        fig, ax = plt.subplots(**fig_kw)
×
2790

2791
    # Select data from reference year onward
2792
    if start_year:
×
2793
        data = data.sel(time=slice(start_year, None))
×
2794

2795
        # Lead time coordinate
2796
        time = _add_lead_time_coord(data, start_year)
×
2797
        ax.set_xlabel(f"Lead time (years from {start_year})")
×
2798
    else:
2799
        time = data.time.dt.year
×
2800

2801
    # fill_kw that are direct (not with uncertainty as key)
2802
    fk_direct = {k: v for k, v in fill_kw.items() if (k not in data.uncertainty.values)}
×
2803

2804
    # Draw areas
2805
    past_y = 0
×
2806
    black_lines = []
×
2807
    for u in data.uncertainty.values:
×
2808
        if u not in ["total", "variability"]:
×
2809
            present_y = past_y + data.sel(uncertainty=u)
×
2810
            num = len(data.attrs.get(u, []))  # compatible with pre PR PR #1529
×
2811
            label = f"{u} ({num})" if show_num and num else u
×
2812
            ax.fill_between(
×
2813
                time,
2814
                past_y,
2815
                present_y,
2816
                label=label,
2817
                **fill_kw.get(u, fk_direct),
2818
            )
2819
            black_lines.append(present_y)
×
2820
            past_y = present_y
×
2821
    ax.fill_between(
×
2822
        time,
2823
        past_y,
2824
        100,
2825
        label="variability",
2826
        **fill_kw.get("variability", fk_direct),
2827
    )
2828

2829
    # Draw black lines
2830
    line_kw.setdefault("color", "k")
×
2831
    line_kw.setdefault("lw", 2)
×
2832
    ax.plot(time, np.array(black_lines).T, **line_kw)
×
2833

2834
    ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(20))
×
2835
    ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=5))
×
2836

2837
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))
×
2838
    ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=2))
×
2839

2840
    ax.set_ylabel(f"{data.attrs['long_name']} ({data.attrs['units']})")  #
×
2841

2842
    ax.set_ylim(0, 100)
×
2843
    ax.legend(**legend_kw)
×
2844

2845
    return ax
×
2846

2847

2848
def triheatmap(
6✔
2849
    data: xr.DataArray | xr.Dataset,
2850
    z: str,
2851
    ax: matplotlib.axes.Axes | None = None,
2852
    use_attrs: dict[str, Any] | None = None,
2853
    fig_kw: dict[str, Any] | None = None,
2854
    plot_kw: dict[str, Any] | None | list = None,
2855
    cmap: str | matplotlib.colors.Colormap | None = None,
2856
    divergent: bool | int | float = False,
2857
    cbar: bool | str = "unique",
2858
    cbar_kw: dict[str, Any] | None | list = None,
2859
) -> matplotlib.axes.Axes:
2860
    """Create a triangle heatmap from a DataArray.
2861

2862
    Note that most of the code comes from:
2863
    https://stackoverflow.com/questions/66048529/how-to-create-a-heatmap-where-each-cell-is-divided-into-4-triangles
2864

2865
    Parameters
2866
    ----------
2867
    data : DataArray or Dataset
2868
        Input data do plot.
2869
    z: str
2870
        Dimension to plot on the triangles. Its length should be 2 or 4.
2871
    ax : matplotlib axis, optional
2872
        Matplotlib axis on which to plot, with the same projection as the one specified.
2873
    use_attrs : dict, optional
2874
        Dict linking a plot element (key, e.g. 'title') to a DataArray attribute (value, e.g. 'Description').
2875
        Default value is {'cbar_label': 'long_name',"cbar_units": "units"}.
2876
        Valid keys are: 'title', 'xlabel', 'ylabel', 'cbar_label', 'cbar_units'.
2877
    fig_kw : dict, optional
2878
        Arguments to pass to `plt.figure()`.
2879
    plot_kw :  dict, optional
2880
        Arguments to pass to the 'plt.tripcolor()' function.
2881
        It can be a list of dictionaries to pass different arguments to each type of triangles (upper/lower or north/east/south/west).
2882
    cmap : matplotlib.colors.Colormap or str, optional
2883
        Colormap to use. If str, can be a matplotlib or name of the file of an IPCC colormap (see data/ipcc_colors).
2884
        If None, look for common variables (from data/ipcc_colors/variables_groups.json) in the name of the DataArray
2885
        or its 'history' attribute and use corresponding colormap, aligned with the IPCC Visual Style Guide 2022
2886
        (https://www.ipcc.ch/site/assets/uploads/2022/09/IPCC_AR6_WGI_VisualStyleGuide_2022.pdf).
2887
    divergent : bool or int or float
2888
        If int or float, becomes center of cmap. Default center is 0.
2889
    cbar : {False, True, 'unique', 'each'}
2890
        If False, don't show the colorbar.
2891
        If True or 'unique', show a unique colorbar for all triangle types. (The cbar of the first triangle is used).
2892
        If 'each', show a colorbar for each triangle type.
2893
    cbar_kw : dict or list
2894
        Arguments to pass to 'fig.colorbar()'.
2895
        It can be a list of dictionaries to pass different arguments to each type of triangles (upper/lower or north/east/south/west).
2896

2897
    Returns
2898
    -------
2899
    matplotlib.axes.Axes
2900
    """
2901
    # create empty dicts if None
2902
    use_attrs = empty_dict(use_attrs)
×
2903
    fig_kw = empty_dict(fig_kw)
×
2904
    plot_kw = empty_dict(plot_kw)
×
2905
    cbar_kw = empty_dict(cbar_kw)
×
2906

2907
    # select data to plot
2908
    if isinstance(data, xr.DataArray):
×
2909
        da = data
×
2910
    elif isinstance(data, xr.Dataset):
×
2911
        if len(data.data_vars) > 1:
×
2912
            warnings.warn(
×
2913
                "data is xr.Dataset; only the first variable will be used in plot"
2914
            )
2915
        da = list(data.values())[0]
×
2916
    else:
2917
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2918

2919
    # setup fig, axis
2920
    if ax is None:
×
2921
        fig, ax = plt.subplots(**fig_kw)
×
2922

2923
    # colormap
2924
    if isinstance(cmap, str):
×
2925
        if cmap not in plt.colormaps():
×
2926
            try:
×
2927
                cmap = create_cmap(filename=cmap)
×
2928
            except FileNotFoundError:
×
2929
                pass
2930
                logging.log("Colormap not found. Using default.")
×
2931

2932
    elif cmap is None:
×
2933
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
2934
        cmap = create_cmap(
×
2935
            get_var_group(path_to_json=cdata, da=da),
2936
            divergent=divergent,
2937
        )
2938

2939
    # prep data
2940
    d = [da.sel(**{z: v}).values for v in da[z].values]
×
2941

2942
    other_dims = [di for di in da.dims if di != z]
×
2943
    if len(other_dims) > 2:
×
2944
        warnings.warn(
×
2945
            "More than 3 dimensions in data. The first two after dim will be used as the dimensions of the heatmap."
2946
        )
2947
    if len(other_dims) < 2:
×
2948
        raise ValueError(
×
2949
            "Data must have 3 dimensions. If you only have 2 dimensions, use fg.heatmap."
2950
        )
2951

2952
    if plot_kw == {} and cbar in ["unique", True]:
×
2953
        warnings.warn(
×
2954
            'With cbar="unique" only the colorbar of the first triangle'
2955
            " will be shown. No `plot_kw` was passed. vmin and vmax will be set the max"
2956
            " and min of data."
2957
        )
2958
        plot_kw = {"vmax": da.max().values, "vmin": da.min().values}
×
2959

2960
    if isinstance(plot_kw, dict):
×
2961
        plot_kw.setdefault("cmap", cmap)
×
2962
        plot_kw.setdefault("ec", "white")
×
2963
        plot_kw = [plot_kw for _ in range(len(d))]
×
2964

2965
    labels_x = da[other_dims[0]].values
×
2966
    labels_y = da[other_dims[1]].values
×
2967
    m, n = d[0].shape[0], d[0].shape[1]
×
2968

2969
    # plot
2970
    if len(d) == 2:
×
2971
        x = np.arange(m + 1)
×
2972
        y = np.arange(n + 1)
×
2973
        xss, ys = np.meshgrid(x, y)
×
2974
        zs = (xss * ys) % 10
×
2975
        triangles1 = [
×
2976
            (i + j * (m + 1), i + 1 + j * (m + 1), i + (j + 1) * (m + 1))
2977
            for j in range(n)
2978
            for i in range(m)
2979
        ]
2980
        triangles2 = [
×
2981
            (
2982
                i + 1 + j * (m + 1),
2983
                i + 1 + (j + 1) * (m + 1),
2984
                i + (j + 1) * (m + 1),
2985
            )
2986
            for j in range(n)
2987
            for i in range(m)
2988
        ]
2989
        triang1 = Triangulation(xss.ravel(), ys.ravel(), triangles1)
×
2990
        triang2 = Triangulation(xss.ravel(), ys.ravel(), triangles2)
×
2991
        triangul = [triang1, triang2]
×
2992

2993
        imgs = [
×
2994
            ax.tripcolor(t, np.ravel(val), **plotkw)
2995
            for t, val, plotkw in zip(triangul, d, plot_kw)
2996
        ]
2997

2998
        ax.set_xticks(np.array(range(m)) + 0.5, labels=labels_x, rotation=45)
×
2999
        ax.set_yticks(np.array(range(n)) + 0.5, labels=labels_y, rotation=90)
×
3000

3001
    elif len(d) == 4:
×
3002
        xv, yv = np.meshgrid(
×
3003
            np.arange(-0.5, m), np.arange(-0.5, n)
3004
        )  # vertices of the little squares
3005
        xc, yc = np.meshgrid(
×
3006
            np.arange(0, m), np.arange(0, n)
3007
        )  # centers of the little squares
3008
        x = np.concatenate([xv.ravel(), xc.ravel()])
×
3009
        y = np.concatenate([yv.ravel(), yc.ravel()])
×
3010
        cstart = (m + 1) * (n + 1)  # indices of the centers
×
3011

3012
        triangles_n = [
×
3013
            (i + j * (m + 1), i + 1 + j * (m + 1), cstart + i + j * m)
3014
            for j in range(n)
3015
            for i in range(m)
3016
        ]
3017
        triangles_e = [
×
3018
            (i + 1 + j * (m + 1), i + 1 + (j + 1) * (m + 1), cstart + i + j * m)
3019
            for j in range(n)
3020
            for i in range(m)
3021
        ]
3022
        triangles_s = [
×
3023
            (
3024
                i + 1 + (j + 1) * (m + 1),
3025
                i + (j + 1) * (m + 1),
3026
                cstart + i + j * m,
3027
            )
3028
            for j in range(n)
3029
            for i in range(m)
3030
        ]
3031
        triangles_w = [
×
3032
            (i + (j + 1) * (m + 1), i + j * (m + 1), cstart + i + j * m)
3033
            for j in range(n)
3034
            for i in range(m)
3035
        ]
3036
        triangul = [
×
3037
            Triangulation(x, y, triangles)
3038
            for triangles in [
3039
                triangles_n,
3040
                triangles_e,
3041
                triangles_s,
3042
                triangles_w,
3043
            ]
3044
        ]
3045

3046
        imgs = [
×
3047
            ax.tripcolor(t, np.ravel(val), **plotkw)
3048
            for t, val, plotkw in zip(triangul, d, plot_kw)
3049
        ]
3050
        ax.set_xticks(np.array(range(m)), labels=labels_x, rotation=45)
×
3051
        ax.set_yticks(np.array(range(n)), labels=labels_y, rotation=90)
×
3052

3053
    else:
3054
        raise ValueError(
×
3055
            f"The length of the dimensiondim ({z},{len(d)}) should be either 2 or 4. It represents the number of triangles."
3056
        )
3057

3058
    ax.set_title(get_attributes(use_attrs.get("title", None), data))
×
3059
    ax.set_xlabel(other_dims[0])
×
3060
    ax.set_ylabel(other_dims[1])
×
3061
    if "xlabel" in use_attrs:
×
3062
        ax.set_xlabel(get_attributes(use_attrs["xlabel"], data))
×
3063
    if "ylabel" in use_attrs:
×
3064
        ax.set_ylabel(get_attributes(use_attrs["ylabel"], data))
×
3065
    ax.set_aspect("equal", "box")
×
3066
    ax.invert_yaxis()
×
3067
    ax.tick_params(left=False, bottom=False)
×
3068
    ax.spines["bottom"].set_visible(False)
×
3069
    ax.spines["left"].set_visible(False)
×
3070

3071
    # create cbar label
3072
    # set default use_attrs values
3073
    use_attrs.setdefault("cbar_label", "long_name")
×
3074
    use_attrs.setdefault("cbar_units", "units")
×
3075
    if (
×
3076
        "cbar_units" in use_attrs
3077
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
3078
    ):  # avoids '()' as label
3079
        cbar_label = (
×
3080
            get_attributes(use_attrs["cbar_label"], data)
3081
            + " ("
3082
            + get_attributes(use_attrs["cbar_units"], data)
3083
            + ")"
3084
        )
3085
    else:
3086
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
3087

3088
    if isinstance(cbar_kw, dict):
×
3089
        cbar_kw.setdefault("label", cbar_label)
×
3090
        cbar_kw = [cbar_kw for _ in range(len(d))]
×
3091
    if cbar == "unique":
×
3092
        plt.colorbar(imgs[0], ax=ax, **cbar_kw[0])
×
3093

3094
    elif (cbar == "each") or (cbar is True):
×
3095
        for i in reversed(range(len(d))):  # switch order of colour bars
×
3096
            plt.colorbar(imgs[i], ax=ax, **cbar_kw[i])
×
3097

3098
    return ax
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc