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

Ouranosinc / figanos / 12073120497

28 Nov 2024 05:08PM UTC coverage: 8.149% (+0.2%) from 7.974%
12073120497

push

github

web-flow
Split doc (#279)

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

* Creates directory datasets with the data for plot hatch map that was
too long to calculate on the fly
* Splits Getting started and Colours of Figanos in 3 new notebooks to
increase speed of RtD.
* Change default projection to LambertConformal
* Fix bug in projection for scattermap
* Create gallery wall

### Does this PR introduce a breaking change?

New default projection

5 of 28 new or added lines in 4 files covered. (17.86%)

4 existing lines in 2 files now uncovered.

155 of 1902 relevant lines covered (8.15%)

0.49 hits per line

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

3.67
/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
        Dictionnary 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:
UNCOV
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:
×
653
            if hasattr(data, "rotated_pole"):
×
654
                transform = get_rotpole(data)
×
655

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

857
        return im
×
858

859

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

988
    return ax
×
989

990

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1118
    return ax
×
1119

1120

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

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

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

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

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

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

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

1182
    n = len(data)
×
1183

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1330
    return ax
×
1331

1332

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1543

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

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

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

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

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

1648
    plot_kw_pop = copy.deepcopy(plot_kw)  # copy plot_kw to modify and pop info in it
×
1649

1650
    # extract plot_kw from dict if needed
1651
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1652
        plot_kw_pop = plot_kw_pop[list(data.keys())[0]]
×
1653

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

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

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

1684
    # setup transform
1685
    if transform is None:
×
NEW
1686
        if "rlat" in data.dims and "rlon" in data.dims:
×
1687
            if hasattr(data, "rotated_pole"):
×
1688
                transform = get_rotpole(data)
×
NEW
1689
        elif (
×
1690
            "lat" in data.coords and "lon" in data.coords
1691
        ):  # need to work with station dims
NEW
1692
            transform = ccrs.PlateCarree()
×
1693

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

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

1725
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
1726
        plot_kw_pop.setdefault("cbar_kwargs", {})
×
1727
        plot_kw_pop["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
1728
        plot_kw_pop["cbar_kwargs"].setdefault("pad", 0.015)
×
1729

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

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

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

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

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

1776
        pt_sizes = norm2range(
×
1777
            data=sdata.where(mask).values,
1778
            target_range=size_range,
1779
            data_range=None,
1780
        )
1781
        plot_kw_pop.setdefault("add_legend", False)
×
1782
        if ax:
×
1783
            plot_kw_pop.setdefault("s", pt_sizes)
×
1784
        else:
1785
            plot_kw_pop.setdefault("s", pt_sizes[0])
×
1786

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

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

1811
    # set defaults and
1812
    plot_kw_pop = {
×
1813
        "cmap": cmap,
1814
        "transform": transform,
1815
        "zorder": 8,
1816
        "marker": "o",
1817
    } | plot_kw_pop
1818

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

1839
    # plot
1840
    plot_kw_pop = {"x": "lon", "y": "lat", "hue": plot_data.name} | plot_kw_pop
×
1841
    if ax:
×
1842
        plot_kw_pop.setdefault("ax", ax)
×
1843
    v = plot_data.where(mask).to_dataset()
×
1844
    im = v.plot.scatter(**plot_kw_pop)
×
1845

1846
    # add features
1847
    if ax:
×
1848
        ax = add_features_map(
×
1849
            data,
1850
            ax,
1851
            use_attrs,
1852
            projection,
1853
            features,
1854
            geometries_kw,
1855
            frame,
1856
        )
1857

1858
        if show_time:
×
1859
            if isinstance(show_time, bool):
×
1860
                plot_coords(
×
1861
                    ax,
1862
                    plot_data,
1863
                    param="time",
1864
                    loc="lower right",
1865
                    backgroundalpha=1,
1866
                )
1867
            elif isinstance(show_time, (str, tuple, int)):
×
1868
                plot_coords(
×
1869
                    ax,
1870
                    plot_data,
1871
                    param="time",
1872
                    loc=show_time,
1873
                    backgroundalpha=1,
1874
                )
1875

1876
        if (frame is False) and (im.colorbar is not None):
×
1877
            im.colorbar.outline.set_visible(False)
×
1878

1879
    else:
1880
        for i, fax in enumerate(im.axs.flat):
×
1881
            fax = add_features_map(
×
1882
                data,
1883
                fax,
1884
                use_attrs,
1885
                projection,
1886
                features,
1887
                geometries_kw,
1888
                frame,
1889
            )
1890

1891
            if sizes:
×
1892
                # correct markersize for facetgrid
1893
                scat = fax.collections[0]
×
1894
                scat.set_sizes(pt_sizes[i])
×
1895

1896
        if (frame is False) and (im.cbar is not None):
×
1897
            im.cbar.outline.set_visible(False)
×
1898

1899
        if show_time:
×
1900
            if isinstance(show_time, bool):
×
1901
                plot_coords(
×
1902
                    None,
1903
                    plot_data,
1904
                    param="time",
1905
                    loc="lower right",
1906
                    backgroundalpha=1,
1907
                )
1908
            elif isinstance(show_time, (str, tuple, int)):
×
1909
                plot_coords(
×
1910
                    None,
1911
                    plot_data,
1912
                    param="time",
1913
                    loc=show_time,
1914
                    backgroundalpha=1,
1915
                )
1916

1917
    # size legend
1918
    if sizes:
×
1919
        legend_elements = size_legend_elements(
×
1920
            np.resize(sdata.values[mask], (sdata.values[mask].size, 1)),
1921
            np.resize(pt_sizes[mask], (pt_sizes[mask].size, 1)),
1922
            max_entries=6,
1923
            marker=plot_kw_pop["marker"],
1924
        )
1925
        # legend spacing
1926
        if size_range[1] > 200:
×
1927
            ls = 0.5 + size_range[1] / 100 * 0.125
×
1928
        else:
1929
            ls = 0.5
×
1930

1931
        legend_kw = {
×
1932
            "loc": "lower left",
1933
            "facecolor": "w",
1934
            "framealpha": 1,
1935
            "edgecolor": "w",
1936
            "labelspacing": ls,
1937
            "handles": legend_elements,
1938
            "bbox_to_anchor": (-0.05, -0.1),
1939
        } | legend_kw
1940

1941
        if "title" not in legend_kw:
×
1942
            if hasattr(sdata, "long_name"):
×
1943
                lgd_title = wrap_text(
×
1944
                    getattr(sdata, "long_name"), min_line_len=1, max_line_len=15
1945
                )
1946
                if hasattr(sdata, "units"):
×
1947
                    lgd_title += f" ({getattr(sdata, 'units')})"
×
1948
            else:
1949
                lgd_title = sizes
×
1950
            legend_kw.setdefault("title", lgd_title)
×
1951

1952
        if ax:
×
1953
            lgd = ax.legend(**legend_kw)
×
1954
            lgd.set_zorder(11)
×
1955
        else:
1956
            im.figlegend = im.fig.legend(**legend_kw)
×
1957
        # im._adjust_fig_for_guide(im.figlegend)
1958

1959
    if ax:
×
1960
        return ax
×
1961
    else:
1962
        im.fig.suptitle(get_attributes("long_name", data))
×
1963
        im.set_titles(template="{value}")
×
1964
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
1965
            for idx, ax in enumerate(im.axs.flat):
×
1966
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
1967

1968
        return im
×
1969

1970

1971
def taylordiagram(
6✔
1972
    data: xr.DataArray | dict[str, xr.DataArray],
1973
    plot_kw: dict[str, Any] | None = None,
1974
    fig_kw: dict[str, Any] | None = None,
1975
    std_range: tuple = (0, 1.5),
1976
    contours: int | None = 4,
1977
    contours_kw: dict[str, Any] | None = None,
1978
    ref_std_line: bool = False,
1979
    legend_kw: dict[str, Any] | None = None,
1980
    std_label: str | None = None,
1981
    corr_label: str | None = None,
1982
    colors_key: str | None = None,
1983
    markers_key: str | None = None,
1984
):
1985
    """Build a Taylor diagram.
1986

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

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

2020
    Returns
2021
    -------
2022
    (plt.figure, mpl_toolkits.axisartist.floating_axes.FloatingSubplot, plt.legend)
2023
    """
2024
    plot_kw = empty_dict(plot_kw)
×
2025
    fig_kw = empty_dict(fig_kw)
×
2026
    contours_kw = empty_dict(contours_kw)
×
2027
    legend_kw = empty_dict(legend_kw)
×
2028

2029
    # preserve order of dimensions if used for marker/color
2030
    ordered_markers_type = None
×
2031
    ordered_colors_type = None
×
2032

2033
    # convert SSP, RCP, CMIP formats in keys
2034
    if isinstance(data, dict):
×
2035
        data = process_keys(data, convert_scen_name)
×
2036
    if isinstance(plot_kw, dict):
×
2037
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
2038

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

2054
    # If there are other dimensions than 'taylor_param', create a bigger dict with them
2055
    data_keys = list(data.keys())
×
2056
    for data_key in data_keys:
×
2057
        da = data[data_key]
×
2058
        dims = list(set(da.dims) - {"taylor_param"})
×
2059
        if dims != []:
×
2060
            if markers_key in dims:
×
2061
                ordered_markers_type = da[markers_key].values
×
2062
            if colors_key in dims:
×
2063
                ordered_colors_type = da[colors_key].values
×
2064

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

2083
    # remove negative correlations
2084
    initial_len = len(data)
×
2085
    removed = [
×
2086
        key for key, da in data.items() if da.sel(taylor_param="corr").values < 0
2087
    ]
2088
    data = {
×
2089
        key: da for key, da in data.items() if da.sel(taylor_param="corr").values >= 0
2090
    }
2091
    if len(data) != initial_len:
×
2092
        warnings.warn(
×
2093
            f"{initial_len - len(data)} points with negative correlations will not be plotted: {', '.join(removed)}"
2094
        )
2095

2096
    # add missing keys to plot_kw
2097
    for key in data.keys():
×
2098
        if key not in plot_kw:
×
2099
            plot_kw[key] = {}
×
2100

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

2111
    # get highest std for axis limits
2112
    max_std = [ref_std]
×
2113
    for key, da in data.items():
×
2114
        max_std.append(
×
2115
            float(
2116
                max(
2117
                    da.sel(taylor_param="ref_std").values,
2118
                    da.sel(taylor_param="sim_std").values,
2119
                )
2120
            )
2121
        )
2122

2123
    # make labels
2124
    if not std_label:
×
2125
        try:
×
2126
            units = list(data.values())[0].units
×
2127
            std_label = get_localized_term("standard deviation")
×
2128
            std_label = std_label if units == "" else f"{std_label} ({units})"
×
2129
        except AttributeError:
×
2130
            std_label = get_localized_term("standard deviation").capitalize()
×
2131

2132
    if not corr_label:
×
2133
        try:
×
2134
            if "Pearson" in list(data.values())[0].correlation_type:
×
2135
                corr_label = get_localized_term("pearson correlation").capitalize()
×
2136
            else:
2137
                corr_label = get_localized_term("correlation").capitalize()
×
2138
        except AttributeError:
×
2139
            corr_label = get_localized_term("correlation").capitalize()
×
2140

2141
    # build diagram
2142
    transform = PolarAxes.PolarTransform()
×
2143

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

2154
    # Set up the axes range in the parameter "extremes"
2155
    ghelper = GridHelperCurveLinear(
×
2156
        transform,
2157
        extremes=(0, np.pi / 2, radius_min, radius_max),
2158
        grid_locator1=gl1,
2159
        tick_formatter1=tf1,
2160
    )
2161

2162
    fig = plt.figure(**fig_kw)
×
2163
    floating_ax = FloatingSubplot(fig, 111, grid_helper=ghelper)
×
2164
    fig.add_subplot(floating_ax)
×
2165

2166
    # Adjust axes
2167
    floating_ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
×
2168
    floating_ax.axis["top"].toggle(ticklabels=True, label=True)
×
2169
    floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
×
2170
    floating_ax.axis["top"].label.set_axis_direction("top")
×
2171
    floating_ax.axis["top"].label.set_text(corr_label)
×
2172

2173
    floating_ax.axis["left"].set_axis_direction("bottom")  # "X axis"
×
2174
    floating_ax.axis["left"].label.set_text(std_label)
×
2175

2176
    floating_ax.axis["right"].set_axis_direction("top")  # "Y axis"
×
2177
    floating_ax.axis["right"].toggle(ticklabels=True, label=True)
×
2178
    floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
×
2179
    floating_ax.axis["right"].label.set_text(std_label)
×
2180

2181
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2182

2183
    # Contours along standard deviations
2184
    floating_ax.grid(visible=True, alpha=0.4)
×
2185
    floating_ax.set_title("")
×
2186

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

2189
    # plot reference
2190
    if "reference" in plot_kw:
×
2191
        ref_kw = plot_kw.pop("reference")
×
2192
    else:
2193
        ref_kw = {}
×
2194
    ref_kw = {
×
2195
        "color": "#154504",
2196
        "marker": "s",
2197
        "label": get_localized_term("reference"),
2198
    } | ref_kw
2199

2200
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2201

2202
    points = [ref_pt]  # set up for later
×
2203

2204
    # plot a circular line along `ref_std`
2205
    if ref_std_line:
×
2206
        angles_for_line = np.linspace(0, np.pi / 2, 100)
×
2207
        radii_for_line = np.full_like(angles_for_line, ref_std)
×
2208
        ax.plot(
×
2209
            angles_for_line,
2210
            radii_for_line,
2211
            color=ref_kw["color"],
2212
            linewidth=0.5,
2213
            linestyle="-",
2214
        )
2215

2216
    # rmse contours from reference standard deviation
2217
    if contours:
×
2218
        radii, angles = np.meshgrid(
×
2219
            np.linspace(radius_min, radius_max),
2220
            np.linspace(0, np.pi / 2),
2221
        )
2222
        # Compute centered RMS difference
2223
        rms = np.sqrt(ref_std**2 + radii**2 - 2 * ref_std * radii * np.cos(angles))
×
2224

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

2228
        ax.clabel(ct, ct.levels, fontsize=8)
×
2229

2230
        # points.append(ct_line)
2231
        ct_line = ax.plot(
×
2232
            [0],
2233
            [0],
2234
            ls=contours_kw["linestyles"],
2235
            lw=1,
2236
            c="k" if "colors" not in contours_kw else contours_kw["colors"],
2237
            label="rmse",
2238
        )
2239
        points.append(ct_line[0])
×
2240

2241
    # get color options
2242
    style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
2243
    if len(data) > len(style_colors):
×
2244
        style_colors = style_colors * math.ceil(len(data) / len(style_colors))
×
2245
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
2246
    # get marker options (only used if `markers_key` is set)
2247
    style_markers = "oDv^<>p*hH+x|_"
×
2248
    if len(data) > len(style_markers):
×
2249
        style_markers = style_markers * math.ceil(len(data) / len(style_markers))
×
2250

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

2272
        for key, da in data.items():
×
2273
            if colors_key:
×
2274
                plot_kw[key]["color"] = colorsd[da.attrs[colors_key]]
×
2275
            if markers_key:
×
2276
                plot_kw[key]["marker"] = markersd[da.attrs[markers_key]]
×
2277

2278
    # plot scatter
2279
    for (key, da), i in zip(data.items(), range(len(data))):
×
2280
        # look for SSP, RCP, CMIP model color
2281
        if colors_key is None:
×
2282
            plot_kw[key].setdefault(
×
2283
                "color", get_scen_color(key, cat_colors) or style_colors[i]
2284
            )
2285
        # set defaults
2286
        plot_kw[key] = {"label": key} | plot_kw[key]
×
2287

2288
        # legend will be handled later in this case
2289
        if markers_key or colors_key:
×
2290
            plot_kw[key]["label"] = ""
×
2291

2292
        # plot
2293
        pt = ax.scatter(
×
2294
            np.arccos(da.sel(taylor_param="corr").values),
2295
            da.sel(taylor_param="sim_std").values,
2296
            **plot_kw[key],
2297
        )
2298
        points.append(pt)
×
2299

2300
    # legend
2301
    legend_kw.setdefault("loc", "upper right")
×
2302
    legend = fig.legend(points, [pt.get_label() for pt in points], **legend_kw)
×
2303

2304
    # plot new legend if markers/colors represent a certain dimension
2305
    if colors_key or markers_key:
×
2306
        handles = list(floating_ax.get_legend_handles_labels()[0])
×
2307
        if markers_key:
×
2308
            for k, m in markersd.items():
×
2309
                handles.append(Line2D([0], [0], color="k", label=k, marker=m, ls=""))
×
2310
        if colors_key:
×
2311
            for k, c in colorsd.items():
×
2312
                handles.append(Line2D([0], [0], color=c, label=k, ls="-"))
×
2313
        legend.remove()
×
2314
        legend = fig.legend(handles=handles, **legend_kw)
×
2315

2316
    return fig, floating_ax, legend
×
2317

2318

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

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

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

2390
    Returns
2391
    -------
2392
    matplotlib.axes.Axes
2393
    """
2394
    # default hatches
2395
    dfh = [
×
2396
        "/",
2397
        "\\",
2398
        "|",
2399
        "-",
2400
        "+",
2401
        "x",
2402
        "o",
2403
        "O",
2404
        ".",
2405
        "*",
2406
        "//",
2407
        "\\\\",
2408
        "||",
2409
        "--",
2410
        "++",
2411
        "xx",
2412
        "oo",
2413
        "OO",
2414
        "..",
2415
        "**",
2416
    ]
2417

2418
    # create empty dicts if None
2419
    use_attrs = empty_dict(use_attrs)
×
2420
    fig_kw = empty_dict(fig_kw)
×
2421
    plot_kw = empty_dict(plot_kw)
×
2422
    legend_kw = empty_dict(legend_kw)
×
2423

2424
    dattrs = None
×
2425
    plot_data = {}
×
2426
    dc = plot_kw.copy()
×
2427

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

2451
    # setup transform from first data entry
2452
    trdata = list(plot_data.values())[0]
×
2453
    if transform is None:
×
2454
        if "lat" in trdata.dims and "lon" in trdata.dims:
×
2455
            transform = ccrs.PlateCarree()
×
2456
        elif "rlat" in trdata.dims and "rlon" in trdata.dims:
×
2457
            if hasattr(list(plot_data.values())[0], "rotated_pole"):
×
2458
                transform = get_rotpole(list(plot_data.values())[0])
×
2459

2460
    # bug xlim / ylim + transfrom in facetgrids
2461
    # (see https://github.com/pydata/xarray/issues/8562#issuecomment-1865189766)
2462
    if transform and (
×
2463
        "xlim" in list(plot_kw.values())[0] and "ylim" in list(plot_kw.values())[0]
2464
    ):
2465
        extend = [
×
2466
            list(plot_kw.values())[0]["xlim"][0],
2467
            list(plot_kw.values())[0]["xlim"][1],
2468
            list(plot_kw.values())[0]["ylim"][0],
2469
            list(plot_kw.values())[0]["ylim"][1],
2470
        ]
2471
        {v.pop("xlim") for v in plot_kw.values()}
×
2472
        {v.pop("ylim") for v in plot_kw.values()}
×
2473

2474
    elif transform and (
×
2475
        "xlim" in list(plot_kw.values())[0] or "ylim" in list(plot_kw.values())[0]
2476
    ):
2477
        extend = None
×
2478
        warnings.warn(
×
2479
            "Requires both xlim and ylim with 'transform'. Xlim or ylim was dropped"
2480
        )
2481
        if "xlim" in list(plot_kw.values())[0].keys():
×
2482
            {v.pop("xlim") for v in plot_kw.values()}
×
2483
        if "ylim" in list(plot_kw.values())[0].keys():
×
2484
            {v.pop("ylim") for v in plot_kw.values()}
×
2485
    else:
2486
        extend = None
×
2487

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

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

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

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

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

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

2552
            if ax:
×
2553
                ax.legend(artists, labels, **legend_kw)
×
2554
            else:
2555
                im.figlegend = im.fig.legend(**legend_kw)
×
2556

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

2565
            if "hatches" not in plot_kw[k].keys():
×
2566
                plot_kw[k]["hatches"] = dfh[n]
×
2567
                n += 1
×
2568

2569
            plot_kw[k].setdefault("transform", transform)
×
2570
            if ax:
×
2571
                im = v.plot.contourf(ax=ax, **plot_kw[k])
×
2572

2573
            if not ax:
×
2574
                if k == list(plot_data.keys())[0]:
×
2575
                    im = v.plot.contourf(**plot_kw[k])
×
2576

2577
                for i, fax in enumerate(im.axs.flat):
×
2578
                    if len(plot_data) > 1 and k != list(plot_data.keys())[0]:
×
2579
                        # select data to plot from DataSet in loop to plot on facetgrids axis
2580
                        c_pkw = plot_kw[k].copy()
×
2581
                        c_pkw.pop("subplot_kws")
×
2582
                        sel = {}
×
2583
                        if "row" in c_pkw.keys():
×
2584
                            sel[c_pkw["row"]] = i
×
2585
                            c_pkw.pop("row")
×
2586
                        elif "col" in c_pkw.keys():
×
2587
                            sel[c_pkw["col"]] = i
×
2588
                            c_pkw.pop("col")
×
2589
                        v.isel(sel).plot.contourf(ax=fax, **c_pkw)
×
2590

2591
                    if k == list(plot_data.keys())[-1]:
×
2592
                        add_features_map(
×
2593
                            dattrs,
2594
                            fax,
2595
                            use_attrs,
2596
                            projection,
2597
                            features,
2598
                            geometries_kw,
2599
                            frame,
2600
                        )
2601
                        if extend:
×
2602
                            fax.set_extent(extend)
×
2603

2604
            pat_leg.append(
×
2605
                matplotlib.patches.Patch(
2606
                    hatch=plot_kw[k]["hatches"], fill=False, label=k
2607
                )
2608
            )
2609

2610
    if pat_leg:
×
2611
        legend_kw = {
×
2612
            "loc": "lower right",
2613
            "handleheight": 2,
2614
            "handlelength": 4,
2615
        } | legend_kw
2616

2617
        if ax:
×
2618
            ax.legend(handles=pat_leg, **legend_kw)
×
2619
        else:
2620
            im.figlegend = im.fig.legend(handles=pat_leg, **legend_kw)
×
2621

2622
    # add features
2623
    if ax:
×
2624
        if extend:
×
2625
            ax.set_extend(extend)
×
2626
        if dattrs:
×
2627
            use_attrs.setdefault("title", "description")
×
2628

2629
        ax = add_features_map(
×
2630
            dattrs,
2631
            ax,
2632
            use_attrs,
2633
            projection,
2634
            features,
2635
            geometries_kw,
2636
            frame,
2637
        )
2638

2639
        if show_time:
×
2640
            if isinstance(show_time, bool):
×
2641
                plot_coords(
×
2642
                    ax,
2643
                    plot_data,
2644
                    param="time",
2645
                    loc="lower right",
2646
                    backgroundalpha=1,
2647
                )
2648
            elif isinstance(show_time, (str, tuple, int)):
×
2649
                plot_coords(
×
2650
                    ax,
2651
                    plot_data,
2652
                    param="time",
2653
                    loc=show_time,
2654
                    backgroundalpha=1,
2655
                )
2656

2657
        # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
2658
        if (frame is False) and (
×
2659
            (getattr(im, "colorbar", None) is not None)
2660
            or (getattr(im, "cbar", None) is not None)
2661
        ):
2662
            im.colorbar.outline.set_visible(False)
×
2663

2664
            set_plot_attrs(use_attrs, dattrs, ax, wrap_kw={"max_line_len": 60})
×
2665
        return ax
×
2666

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

2675
        if show_time:
×
2676
            if show_time is True:
×
2677
                plot_coords(
×
2678
                    None,
2679
                    dattrs,
2680
                    param="time",
2681
                    loc="lower right",
2682
                    backgroundalpha=1,
2683
                )
2684
            elif isinstance(show_time, (str, tuple, int)):
×
2685
                plot_coords(
×
2686
                    None, dattrs, param="time", loc=show_time, backgroundalpha=1
2687
                )
2688
        if dattrs:
×
2689
            use_attrs.setdefault("suptitle", "long_name")
×
2690
            set_plot_attrs(use_attrs, dattrs, facetgrid=im)
×
2691

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

2696
        return im
×
2697

2698

2699
def _add_lead_time_coord(da, ref):
6✔
2700
    """Add a lead time coordinate to the data. Modifies da in-place."""
2701
    lead_time = da.time.dt.year - int(ref)
×
2702
    da["Lead time"] = lead_time
×
2703
    da["Lead time"].attrs["units"] = f"years from {ref}"
×
2704
    return lead_time
×
2705

2706

2707
def partition(
6✔
2708
    data: xr.DataArray | xr.Dataset,
2709
    ax: matplotlib.axes.Axes | None = None,
2710
    start_year: str | None = None,
2711
    show_num: bool = True,
2712
    fill_kw: dict[str, Any] | None = None,
2713
    line_kw: dict[str, Any] | None = None,
2714
    fig_kw: dict[str, Any] | None = None,
2715
    legend_kw: dict[str, Any] | None = None,
2716
) -> matplotlib.axes.Axes:
2717
    """Figure of the partition of total uncertainty by components.
2718

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

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

2746
    Returns
2747
    -------
2748
    mpl.axes.Axes
2749
    """
2750
    if isinstance(data, xr.Dataset):
×
2751
        if len(data.data_vars) > 1:
×
2752
            warnings.warn(
×
2753
                "data is xr.Dataset; only the first variable will be used in plot"
2754
            )
2755
        data = data[list(data.keys())[0]].squeeze()
×
2756

2757
    if data.attrs["units"] != "%":
×
2758
        raise ValueError(
×
2759
            "The units are not %. Use `fraction=True` in the xclim function call."
2760
        )
2761

2762
    fill_kw = empty_dict(fill_kw)
×
2763
    line_kw = empty_dict(line_kw)
×
2764
    fig_kw = empty_dict(fig_kw)
×
2765
    legend_kw = empty_dict(legend_kw)
×
2766

2767
    # select data to plot
2768
    if isinstance(data, xr.DataArray):
×
2769
        data = data.squeeze()
×
2770
    elif isinstance(data, xr.Dataset):  # in case, it was saved to disk before plotting.
×
2771
        if len(data.data_vars) > 1:
×
2772
            warnings.warn(
×
2773
                "data is xr.Dataset; only the first variable will be used in plot"
2774
            )
2775
        data = data[list(data.keys())[0]].squeeze()
×
2776
    else:
2777
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2778

2779
    if ax is None:
×
2780
        fig, ax = plt.subplots(**fig_kw)
×
2781

2782
    # Select data from reference year onward
2783
    if start_year:
×
2784
        data = data.sel(time=slice(start_year, None))
×
2785

2786
        # Lead time coordinate
2787
        time = _add_lead_time_coord(data, start_year)
×
2788
        ax.set_xlabel(f"Lead time (years from {start_year})")
×
2789
    else:
2790
        time = data.time.dt.year
×
2791

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

2795
    # Draw areas
2796
    past_y = 0
×
2797
    black_lines = []
×
2798
    for u in data.uncertainty.values:
×
2799
        if u not in ["total", "variability"]:
×
2800
            present_y = past_y + data.sel(uncertainty=u)
×
2801
            num = len(data.attrs.get(u, []))  # compatible with pre PR PR #1529
×
2802
            label = f"{u} ({num})" if show_num and num else u
×
2803
            ax.fill_between(
×
2804
                time,
2805
                past_y,
2806
                present_y,
2807
                label=label,
2808
                **fill_kw.get(u, fk_direct),
2809
            )
2810
            black_lines.append(present_y)
×
2811
            past_y = present_y
×
2812
    ax.fill_between(
×
2813
        time,
2814
        past_y,
2815
        100,
2816
        label="variability",
2817
        **fill_kw.get("variability", fk_direct),
2818
    )
2819

2820
    # Draw black lines
2821
    line_kw.setdefault("color", "k")
×
2822
    line_kw.setdefault("lw", 2)
×
2823
    ax.plot(time, np.array(black_lines).T, **line_kw)
×
2824

2825
    ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(20))
×
2826
    ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=5))
×
2827

2828
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))
×
2829
    ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=2))
×
2830

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

2833
    ax.set_ylim(0, 100)
×
2834
    ax.legend(**legend_kw)
×
2835

2836
    return ax
×
2837

2838

2839
def triheatmap(
6✔
2840
    data: xr.DataArray | xr.Dataset,
2841
    z: str,
2842
    ax: matplotlib.axes.Axes | None = None,
2843
    use_attrs: dict[str, Any] | None = None,
2844
    fig_kw: dict[str, Any] | None = None,
2845
    plot_kw: dict[str, Any] | None | list = None,
2846
    cmap: str | matplotlib.colors.Colormap | None = None,
2847
    divergent: bool | int | float = False,
2848
    cbar: bool | str = "unique",
2849
    cbar_kw: dict[str, Any] | None | list = None,
2850
) -> matplotlib.axes.Axes:
2851
    """Create a triangle heatmap from a DataArray.
2852

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

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

2888
    Returns
2889
    -------
2890
    matplotlib.axes.Axes
2891
    """
2892
    # create empty dicts if None
2893
    use_attrs = empty_dict(use_attrs)
×
2894
    fig_kw = empty_dict(fig_kw)
×
2895
    plot_kw = empty_dict(plot_kw)
×
2896
    cbar_kw = empty_dict(cbar_kw)
×
2897

2898
    # select data to plot
2899
    if isinstance(data, xr.DataArray):
×
2900
        da = data
×
2901
    elif isinstance(data, xr.Dataset):
×
2902
        if len(data.data_vars) > 1:
×
2903
            warnings.warn(
×
2904
                "data is xr.Dataset; only the first variable will be used in plot"
2905
            )
2906
        da = list(data.values())[0]
×
2907
    else:
2908
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2909

2910
    # setup fig, axis
2911
    if ax is None:
×
2912
        fig, ax = plt.subplots(**fig_kw)
×
2913

2914
    # colormap
2915
    if isinstance(cmap, str):
×
2916
        if cmap not in plt.colormaps():
×
2917
            try:
×
2918
                cmap = create_cmap(filename=cmap)
×
2919
            except FileNotFoundError:
×
2920
                pass
2921
                logging.log("Colormap not found. Using default.")
×
2922

2923
    elif cmap is None:
×
2924
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
2925
        cmap = create_cmap(
×
2926
            get_var_group(path_to_json=cdata, da=da),
2927
            divergent=divergent,
2928
        )
2929

2930
    # prep data
2931
    d = [da.sel(**{z: v}).values for v in da[z].values]
×
2932

2933
    other_dims = [di for di in da.dims if di != z]
×
2934
    if len(other_dims) > 2:
×
2935
        warnings.warn(
×
2936
            "More than 3 dimensions in data. The first two after dim will be used as the dimensions of the heatmap."
2937
        )
2938
    if len(other_dims) < 2:
×
2939
        raise ValueError(
×
2940
            "Data must have 3 dimensions. If you only have 2 dimensions, use fg.heatmap."
2941
        )
2942

2943
    if plot_kw == {} and cbar in ["unique", True]:
×
2944
        warnings.warn(
×
2945
            'With cbar="unique" only the colorbar of the first triangle'
2946
            " will be shown. No `plot_kw` was passed. vmin and vmax will be set the max"
2947
            " and min of data."
2948
        )
2949
        plot_kw = {"vmax": da.max().values, "vmin": da.min().values}
×
2950

2951
    if isinstance(plot_kw, dict):
×
2952
        plot_kw.setdefault("cmap", cmap)
×
2953
        plot_kw.setdefault("ec", "white")
×
2954
        plot_kw = [plot_kw for _ in range(len(d))]
×
2955

2956
    labels_x = da[other_dims[0]].values
×
2957
    labels_y = da[other_dims[1]].values
×
2958
    m, n = d[0].shape[0], d[0].shape[1]
×
2959

2960
    # plot
2961
    if len(d) == 2:
×
UNCOV
2962
        x = np.arange(m + 1)
×
2963
        y = np.arange(n + 1)
×
2964
        xss, ys = np.meshgrid(x, y)
×
2965
        zs = (xss * ys) % 10
×
2966
        triangles1 = [
×
2967
            (i + j * (m + 1), i + 1 + j * (m + 1), i + (j + 1) * (m + 1))
2968
            for j in range(n)
2969
            for i in range(m)
2970
        ]
2971
        triangles2 = [
×
2972
            (
2973
                i + 1 + j * (m + 1),
2974
                i + 1 + (j + 1) * (m + 1),
2975
                i + (j + 1) * (m + 1),
2976
            )
2977
            for j in range(n)
2978
            for i in range(m)
2979
        ]
2980
        triang1 = Triangulation(xss.ravel(), ys.ravel(), triangles1)
×
2981
        triang2 = Triangulation(xss.ravel(), ys.ravel(), triangles2)
×
2982
        triangul = [triang1, triang2]
×
2983

2984
        imgs = [
×
2985
            ax.tripcolor(t, np.ravel(val), **plotkw)
2986
            for t, val, plotkw in zip(triangul, d, plot_kw)
2987
        ]
2988

2989
        ax.set_xticks(np.array(range(m)) + 0.5, labels=labels_x, rotation=45)
×
2990
        ax.set_yticks(np.array(range(n)) + 0.5, labels=labels_y, rotation=90)
×
2991

2992
    elif len(d) == 4:
×
UNCOV
2993
        xv, yv = np.meshgrid(
×
2994
            np.arange(-0.5, m), np.arange(-0.5, n)
2995
        )  # vertices of the little squares
2996
        xc, yc = np.meshgrid(
×
2997
            np.arange(0, m), np.arange(0, n)
2998
        )  # centers of the little squares
2999
        x = np.concatenate([xv.ravel(), xc.ravel()])
×
3000
        y = np.concatenate([yv.ravel(), yc.ravel()])
×
3001
        cstart = (m + 1) * (n + 1)  # indices of the centers
×
3002

3003
        triangles_n = [
×
3004
            (i + j * (m + 1), i + 1 + j * (m + 1), cstart + i + j * m)
3005
            for j in range(n)
3006
            for i in range(m)
3007
        ]
3008
        triangles_e = [
×
3009
            (i + 1 + j * (m + 1), i + 1 + (j + 1) * (m + 1), cstart + i + j * m)
3010
            for j in range(n)
3011
            for i in range(m)
3012
        ]
3013
        triangles_s = [
×
3014
            (
3015
                i + 1 + (j + 1) * (m + 1),
3016
                i + (j + 1) * (m + 1),
3017
                cstart + i + j * m,
3018
            )
3019
            for j in range(n)
3020
            for i in range(m)
3021
        ]
3022
        triangles_w = [
×
3023
            (i + (j + 1) * (m + 1), i + j * (m + 1), cstart + i + j * m)
3024
            for j in range(n)
3025
            for i in range(m)
3026
        ]
3027
        triangul = [
×
3028
            Triangulation(x, y, triangles)
3029
            for triangles in [
3030
                triangles_n,
3031
                triangles_e,
3032
                triangles_s,
3033
                triangles_w,
3034
            ]
3035
        ]
3036

3037
        imgs = [
×
3038
            ax.tripcolor(t, np.ravel(val), **plotkw)
3039
            for t, val, plotkw in zip(triangul, d, plot_kw)
3040
        ]
3041
        ax.set_xticks(np.array(range(m)), labels=labels_x, rotation=45)
×
3042
        ax.set_yticks(np.array(range(n)), labels=labels_y, rotation=90)
×
3043

3044
    else:
3045
        raise ValueError(
×
3046
            f"The length of the dimensiondim ({z},{len(d)}) should be either 2 or 4. It represents the number of triangles."
3047
        )
3048

3049
    ax.set_title(get_attributes(use_attrs.get("title", None), data))
×
3050
    ax.set_xlabel(other_dims[0])
×
3051
    ax.set_ylabel(other_dims[1])
×
3052
    if "xlabel" in use_attrs:
×
3053
        ax.set_xlabel(get_attributes(use_attrs["xlabel"], data))
×
3054
    if "ylabel" in use_attrs:
×
3055
        ax.set_ylabel(get_attributes(use_attrs["ylabel"], data))
×
3056
    ax.set_aspect("equal", "box")
×
3057
    ax.invert_yaxis()
×
3058
    ax.tick_params(left=False, bottom=False)
×
3059
    ax.spines["bottom"].set_visible(False)
×
3060
    ax.spines["left"].set_visible(False)
×
3061

3062
    # create cbar label
3063
    # set default use_attrs values
3064
    use_attrs.setdefault("cbar_label", "long_name")
×
3065
    use_attrs.setdefault("cbar_units", "units")
×
3066
    if (
×
3067
        "cbar_units" in use_attrs
3068
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
3069
    ):  # avoids '()' as label
3070
        cbar_label = (
×
3071
            get_attributes(use_attrs["cbar_label"], data)
3072
            + " ("
3073
            + get_attributes(use_attrs["cbar_units"], data)
3074
            + ")"
3075
        )
3076
    else:
3077
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
3078

3079
    if isinstance(cbar_kw, dict):
×
3080
        cbar_kw.setdefault("label", cbar_label)
×
3081
        cbar_kw = [cbar_kw for _ in range(len(d))]
×
3082
    if cbar == "unique":
×
3083
        plt.colorbar(imgs[0], ax=ax, **cbar_kw[0])
×
3084

3085
    elif (cbar == "each") or (cbar is True):
×
3086
        for i in reversed(range(len(d))):  # swithc order of colorbars
×
3087
            plt.colorbar(imgs[i], ax=ax, **cbar_kw[i])
×
3088

3089
    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