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

Ouranosinc / figanos / 20276532443

16 Dec 2025 05:13PM UTC coverage: 9.11% (+0.9%) from 8.187%
20276532443

Pull #368

github

web-flow
Merge 9c88f65b3 into 07bbe06e5
Pull Request #368: Enregistrement des cmaps de l'IPCC dans matplotlib

12 of 35 new or added lines in 2 files covered. (34.29%)

1 existing line in 1 file now uncovered.

173 of 1899 relevant lines covered (9.11%)

0.55 hits per line

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

3.66
/src/figanos/matplotlib/plot.py
1
# noqa: D100
2
from __future__ import annotations
6✔
3
import copy
6✔
4
import logging
6✔
5
import math
6✔
6
import string
6✔
7
import warnings
6✔
8
from collections.abc import Iterable
6✔
9
from inspect import signature
6✔
10
from pathlib import Path
6✔
11
from typing import Any
6✔
12

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

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

57

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

60

61
def _plot_realizations(
6✔
62
    ax: matplotlib.axes.Axes,
63
    da: xr.DataArray,
64
    name: str,
65
    plot_kw: dict[str, Any],
66
    non_dict_data: dict[str, Any],
67
) -> matplotlib.axes.Axes:
68
    """
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
    """
121
    Plot figanos timeseries.
122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

529
        return im
×
530

531

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

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

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

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

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

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

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

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

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

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

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

689
    # colormap
NEW
690
    if cmap is None:
×
NEW
691
        cmap = get_ipcc_cmap_name(
×
692
            get_var_group(da=plot_data),
693
            divergent=divergent,
694
        )
695
    plot_kw.setdefault("cmap", cmap)
×
696

697
    if levels is not None:
×
698
        if isinstance(levels, Iterable):
×
699
            lin = levels
×
700
        else:
701
            lin = custom_cmap_norm(
×
702
                cmap,
703
                np.nanmin(plot_data.values),
704
                np.nanmax(plot_data.values),
705
                levels=levels,
706
                divergent=divergent,
707
                linspace_out=True,
708
            )
709
        plot_kw.setdefault("levels", lin)
×
710

711
    elif (divergent is not False) and ("levels" not in plot_kw):
×
712
        vmin = plot_kw.pop("vmin", np.nanmin(plot_data.values))
×
713
        vmax = plot_kw.pop("vmax", np.nanmax(plot_data.values))
×
714
        norm = custom_cmap_norm(
×
715
            cmap,
716
            vmin,
717
            vmax,
718
            levels=levels,
719
            divergent=divergent,
720
        )
721
        plot_kw.setdefault("norm", norm)
×
722

723
    # set defaults
724
    if divergent is not False:
×
725
        if isinstance(divergent, int | float):
×
726
            plot_kw.setdefault("center", divergent)
×
727
        else:
728
            plot_kw.setdefault("center", 0)
×
729

730
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
731
        plot_kw.setdefault("cbar_kwargs", {})
×
732
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
733

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

757
    # plot
758
    if ax:
×
759
        plot_kw.setdefault("ax", ax)
×
760
    if transform:
×
761
        plot_kw.setdefault("transform", transform)
×
762

763
    if contourf is False:
×
764
        im = plot_data.plot.pcolormesh(**plot_kw)
×
765
    else:
766
        im = plot_data.plot.contourf(**plot_kw)
×
767

768
    if ax:
×
769
        if extent:
×
770
            ax.set_extent(extent)
×
771

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

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

807
    else:
808
        for _i, fax in enumerate(im.axs.flat):
×
809
            add_features_map(
×
810
                data,
811
                fax,
812
                use_attrs,
813
                projection,
814
                features,
815
                geometries_kw,
816
                frame,
817
            )
818
            if extent:
×
819
                fax.set_extent(extent)
×
820

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

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

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

852
        return im
×
853

854

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

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

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

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

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

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

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

931
    # add features
932
    if features:
×
933
        add_cartopy_features(ax, features)
×
934

935
    if df_col == "boundary":
×
936
        plot = df.boundary.plot(ax=ax, **plot_kw)
×
937
        if cmap is not None or levels is not None or divergent is not False:
×
938
            warnings.warn("Colomap arguments are ignored when plotting 'boundary'.", stacklevel=2)
×
939
    else:
940

941
        # colormap
NEW
942
        if cmap is None:
×
NEW
943
            cmap = get_ipcc_cmap_name(
×
944
                get_var_group(unique_str=df_col),
945
                divergent=divergent,
946
            )
NEW
947
        if isinstance(cmap, str):
×
NEW
948
            try:
×
NEW
949
                cmap = matplotlib.colormaps[cmap]
×
NEW
950
            except KeyError:
×
NEW
951
                warnings.warn("invalid cmap, using default", stacklevel=2)
×
NEW
952
                cmap = matplotlib.colormaps["slev_seq"]
×
953

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

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

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

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

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

987
    return ax
×
988

989

990
def violin(
6✔
991
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
992
    ax: matplotlib.axes.Axes | None = None,
993
    use_attrs: dict[str, Any] | None = None,
994
    fig_kw: dict[str, Any] | None = None,
995
    plot_kw: dict[str, Any] | None = None,
996
    color: str | int | list[str | int] | None = None,
997
) -> matplotlib.axes.Axes:
998
    """
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 as err:
×
1101
                raise IndexError("Index out of range of stylesheet colors") from err
×
1102
        elif isinstance(color, list):
×
1103
            for c, i in zip(color, np.arange(len(color)), strict=False):
×
1104
                if isinstance(c, int):
×
1105
                    try:
×
1106
                        color[i] = style_colors[c]
×
1107
                    except IndexError as err:
×
1108
                        raise IndexError("Index out of range of stylesheet colors") from err
×
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
    """
1132
    Create stripes plot with or without multiple scenarios.
1133

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

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

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

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

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

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

1183
    n = len(data)
×
1184

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

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

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

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

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

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

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

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

1266
    # colormap
NEW
1267
    if cmap is None:
×
NEW
1268
        cmap = get_ipcc_cmap_name(
×
1269
            get_var_group(da=list(data.values())[0]),
1270
            divergent=True,
1271
        )
NEW
1272
    if isinstance(cmap, str):
×
NEW
1273
        cmap = matplotlib.colormaps[cmap]
×
1274

1275
    # create cmap norm
1276
    if cmap_center is not None:
×
1277
        norm = matplotlib.colors.TwoSlopeNorm(cmap_center, vmin=data_min, vmax=data_max)
×
1278
    else:
1279
        norm = matplotlib.colors.Normalize(data_min, data_max)
×
1280

1281
    # plot
1282
    for (_name, subax), (key, da) in zip(subaxes.items(), data.items(), strict=False):
×
1283
        subax.bar(da.time.dt.year, height=1, width=dtime, color=cmap(norm(da.values)))
×
1284
        if divide:
×
1285
            if key != "_no_label":
×
1286
                subax.text(
×
1287
                    0.99,
1288
                    0.5,
1289
                    key,
1290
                    transform=subax.transAxes,
1291
                    fontsize=14,
1292
                    ha="right",
1293
                    va="center",
1294
                    c="w",
1295
                    weight="bold",
1296
                )
1297

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

1312
        cbar_kw = {
×
1313
            "cax": cax,
1314
            "orientation": "horizontal",
1315
            "ticks": cbar_tcks,
1316
            "label": label,
1317
        } | cbar_kw
1318
        plt.colorbar(sm, **cbar_kw)
×
1319
        cax.spines["outline"].set_visible(False)
×
1320
        cax.set_xscale("linear")
×
1321

1322
    return ax
×
1323

1324

1325
def heatmap(
6✔
1326
    data: xr.DataArray | xr.Dataset | dict[str, Any],
1327
    ax: matplotlib.axes.Axes | None = None,
1328
    use_attrs: dict[str, Any] | None = None,
1329
    fig_kw: dict[str, Any] | None = None,
1330
    plot_kw: dict[str, Any] | None = None,
1331
    transpose: bool = False,
1332
    cmap: str | matplotlib.colors.Colormap | None = "RdBu",
1333
    divergent: bool | int | float = False,
1334
) -> matplotlib.axes.Axes:
1335
    """
1336
    Create heatmap from a DataArray.
1337

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

1363
    Returns
1364
    -------
1365
    matplotlib.axes.Axes
1366
    """
1367
    # create empty dicts if None
1368
    use_attrs = empty_dict(use_attrs)
×
1369
    fig_kw = empty_dict(fig_kw)
×
1370
    plot_kw = empty_dict(plot_kw)
×
1371

1372
    # set default use_attrs values
1373
    use_attrs.setdefault("cbar_label", "long_name")
×
1374

1375
    # if data is dict, extract
1376
    if isinstance(data, dict):
×
1377
        if plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1378
            plot_kw = plot_kw[list(data.keys())[0]]
×
1379
        if len(data) == 1:
×
1380
            data = list(data.values())[0]
×
1381
        else:
1382
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1383

1384
    # select data to plot
1385
    if isinstance(data, xr.DataArray):
×
1386
        da = data
×
1387
    elif isinstance(data, xr.Dataset):
×
1388
        if len(data.data_vars) > 1:
×
1389
            warnings.warn(
×
1390
                "data is xr.Dataset; only the first variable will be used in plot", stacklevel=2
1391
            )
1392
        da = list(data.values())[0]
×
1393
    else:
1394
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1395

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

1417
    # create cbar label
1418
    if (
×
1419
        "cbar_units" in use_attrs
1420
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1421
    ):  # avoids '()' as label
1422
        cbar_label = (
×
1423
            get_attributes(use_attrs["cbar_label"], data)
1424
            + " ("
1425
            + get_attributes(use_attrs["cbar_units"], data)
1426
            + ")"
1427
        )
1428
    else:
1429
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1430

1431
    # colormap
NEW
1432
    if cmap is None:
×
NEW
1433
        cmap = get_ipcc_cmap_name(
×
1434
            get_var_group(da=da),
1435
            divergent=divergent,
1436
        )
1437

1438
    # convert data to DataFrame
1439
    if transpose:
×
1440
        da = da.transpose()
×
1441
    if "col" not in plot_kw and "row" not in plot_kw:
×
1442
        if len(da.dims) != 2:
×
1443
            raise ValueError("DataArray must have exactly two dimensions")
×
1444
        df = da.to_pandas()
×
1445
    else:
1446
        if len(heatmap_dims) != 2:
×
1447
            raise ValueError("DataArray must have exactly two dimensions")
×
1448
        df = da.to_dataframe().reset_index()
×
1449

1450
    # set defaults
1451
    if divergent is not False:
×
1452
        if isinstance(divergent, int | float):
×
1453
            plot_kw.setdefault("center", divergent)
×
1454
        else:
1455
            plot_kw.setdefault("center", 0)
×
1456

1457
    if "cbar" not in plot_kw or plot_kw["cbar"] is not False:
×
1458
        plot_kw.setdefault("cbar_kws", {})
×
1459
        plot_kw["cbar_kws"].setdefault("label", wrap_text(cbar_label))
×
1460

1461
    plot_kw.setdefault("cmap", cmap)
×
1462

1463
    # plot
1464
    def draw_heatmap(*args, **kwargs):
×
1465
        data = kwargs.pop("data")
×
1466
        d = (
×
1467
            data
1468
            if len(args) == 0
1469
            # Any sorting should be performed before sending a DataArray in `fg.heatmap`
1470
            else data.pivot_table(
1471
                index=args[1], columns=args[0], values=args[2], sort=False
1472
            )
1473
        )
1474
        ax = sns.heatmap(d, **kwargs)
×
1475
        ax.set_xticklabels(
×
1476
            ax.get_xticklabels(),
1477
            rotation=45,
1478
            ha="right",
1479
            rotation_mode="anchor",
1480
        )
1481
        ax.tick_params(axis="both", direction="out")
×
1482
        set_plot_attrs(
×
1483
            use_attrs,
1484
            da,
1485
            ax,
1486
            title_loc="center",
1487
            wrap_kw={"min_line_len": 35, "max_line_len": 44},
1488
        )
1489
        return ax
×
1490

1491
    if ax is not None:
×
1492
        ax = draw_heatmap(data=df, ax=ax, **plot_kw)
×
1493
        return ax
×
1494
    elif "col" in plot_kw or "row" in plot_kw:
×
1495
        # When using xarray's FacetGrid, `plot_kw` can be used in the FacetGrid and in the plotting function
1496
        # With Seaborn, we need to be more careful and separate keywords.
1497
        plot_kw_hm = {
×
1498
            k: v for k, v in plot_kw.items() if k in signature(sns.heatmap).parameters
1499
        }
1500
        plot_kw_fg = {
×
1501
            k: v for k, v in plot_kw.items() if k in signature(sns.FacetGrid).parameters
1502
        }
1503
        unused_keys = (
×
1504
            set(plot_kw.keys()) - set(plot_kw_fg.keys()) - set(plot_kw_hm.keys())
1505
        )
1506
        if unused_keys != set():
×
1507
            raise ValueError(
×
1508
                f"`heatmap` got unexpected keywords in `plot_kw`: {unused_keys}. Keywords in `plot_kw` should be keywords "
1509
                "allowed in `sns.heatmap` or `sns.FacetGrid`. "
1510
            )
1511

1512
        g = sns.FacetGrid(df, **plot_kw_fg)
×
1513
        cax = g.fig.add_axes([0.95, 0.05, 0.02, 0.9])
×
1514
        g.map_dataframe(
×
1515
            draw_heatmap,
1516
            *heatmap_dims,
1517
            da_name,
1518
            **plot_kw_hm,
1519
            cbar=True,
1520
            cbar_ax=cax,
1521
        )
1522
        g.fig.subplots_adjust(right=0.9)
×
1523
        if "figsize" in fig_kw.keys():
×
1524
            g.fig.set_size_inches(*fig_kw["figsize"])
×
1525
        return g
×
1526

1527

1528
def scattermap(
6✔
1529
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1530
    ax: matplotlib.axes.Axes | None = None,
1531
    use_attrs: dict[str, Any] | None = None,
1532
    fig_kw: dict[str, Any] | None = None,
1533
    plot_kw: dict[str, Any] | None = None,
1534
    projection: ccrs.Projection = ccrs.LambertConformal(),
1535
    transform: ccrs.Projection | None = None,
1536
    features: list[str] | dict[str, dict[str, Any]] | None = None,
1537
    geometries_kw: dict[str, Any] | None = None,
1538
    sizes: str | bool | None = None,
1539
    size_range: tuple = (10, 60),
1540
    cmap: str | matplotlib.colors.Colormap | None = None,
1541
    levels: int | None = None,
1542
    divergent: bool | int | float = False,
1543
    legend_kw: dict[str, Any] | None = None,
1544
    show_time: bool | str | int | tuple[float, float] = False,
1545
    frame: bool = False,
1546
    enumerate_subplots: bool = False,
1547
) -> matplotlib.axes.Axes:
1548
    """
1549
    Make a scatter plot of georeferenced data on a map.
1550

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

1598
        ==================   =============
1599
        Location String      Location Code
1600
        ==================   =============
1601
        'upper right'        1
1602
        'upper left'         2
1603
        'lower left'         3
1604
        'lower right'        4
1605
        'right'              5
1606
        'center left'        6
1607
        'center right'       7
1608
        'lower center'       8
1609
        'upper center'       9
1610
        'center'             10
1611
        ==================   =============
1612
    frame : bool
1613
        Show or hide frame. Default False.
1614
    enumerate_subplots: bool
1615
        If True, enumerate subplots with letters.
1616
        Only works with facetgrids (pass `col` or `row` in plot_kw).
1617

1618
    Returns
1619
    -------
1620
    matplotlib.axes.Axes
1621
    """
1622
    # create empty dicts if None
1623
    use_attrs = empty_dict(use_attrs)
×
1624
    fig_kw = empty_dict(fig_kw)
×
1625
    plot_kw = empty_dict(plot_kw)
×
1626
    legend_kw = empty_dict(legend_kw)
×
1627

1628
    # set default use_attrs values
1629
    use_attrs = {"cbar_label": "long_name", "cbar_units": "units"} | use_attrs
×
1630
    if "row" not in plot_kw and "col" not in plot_kw:
×
1631
        use_attrs.setdefault("title", "description")
×
1632

1633
    # extract plot_kw from dict if needed
1634
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1635
        plot_kw = plot_kw[list(data.keys())[0]]
×
1636

1637
    # figanos does not use xr.plot.scatter default markersize
1638
    if "markersize" in plot_kw.keys():
×
1639
        if not sizes:
×
1640
            sizes = plot_kw["markersize"]
×
1641
        plot_kw.pop("markersize")
×
1642

1643
    # if data is dict, extract
1644
    if isinstance(data, dict):
×
1645
        if len(data) == 1:
×
1646
            data = list(data.values())[0].squeeze()
×
1647
            if len(data.data_vars) > 1:
×
1648
                warnings.warn(
×
1649
                    "data is xr.Dataset; only the first variable will be used in plot", stacklevel=2
1650
                )
1651
        else:
1652
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1653

1654
    # select data to plot and its xr.Dataset
1655
    if isinstance(data, xr.DataArray):
×
1656
        plot_data = data
×
1657
        data = xr.Dataset({plot_data.name: plot_data})
×
1658
    elif isinstance(data, xr.Dataset):
×
1659
        if len(data.data_vars) > 1:
×
1660
            warnings.warn(
×
1661
                "data is xr.Dataset; only the first variable will be used in plot", stacklevel=2
1662
            )
1663
        plot_data = data[list(data.keys())[0]]
×
1664
    else:
1665
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1666

1667
    # setup transform
1668
    if transform is None:
×
1669
        if "rlat" in data.dims and "rlon" in data.dims:
×
1670
            transform = get_rotpole(data)
×
1671
        elif (
×
1672
            "lat" in data.coords and "lon" in data.coords
1673
        ):  # need to work with station dims
1674
            transform = ccrs.PlateCarree()
×
1675

1676
    # setup fig, ax
1677
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
1678
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
1679
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
1680
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
1681
    elif ax is None:
×
1682
        plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1683
        cfig_kw = fig_kw.copy()
×
1684
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
1685
            plot_kw.setdefault("figsize", fig_kw["figsize"])
×
1686
            cfig_kw.pop("figsize")
×
1687
        if len(cfig_kw) >= 1:
×
1688
            plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1689
            warnings.warn(
×
1690
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid.", stacklevel=2
1691
            )
1692

1693
    # create cbar label
1694
    if (
×
1695
        "cbar_units" in use_attrs
1696
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1697
    ):  # avoids '[]' as label
1698
        cbar_label = (
×
1699
            get_attributes(use_attrs["cbar_label"], data)
1700
            + " ("
1701
            + get_attributes(use_attrs["cbar_units"], data)
1702
            + ")"
1703
        )
1704
    else:
1705
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1706

1707
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
1708
        plot_kw.setdefault("cbar_kwargs", {})
×
1709
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
1710
        plot_kw["cbar_kwargs"].setdefault("pad", 0.015)
×
1711

1712
    # colormap
NEW
1713
    if cmap is None:
×
NEW
1714
        cmap = get_ipcc_cmap_name(
×
1715
            get_var_group(da=plot_data),
1716
            divergent=divergent,
1717
        )
1718

1719
    # nans (not required for plotting since xarray.plot handles np.nan, but needs to be found for sizes legend and to
1720
    # inform user on how many stations were dropped)
1721
    mask = ~np.isnan(plot_data.values)
×
1722
    if np.sum(mask) < len(mask):
×
1723
        warnings.warn(
×
1724
            f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the color values", stacklevel=2
1725
        )
1726

1727
    # point sizes
1728
    if sizes:
×
1729
        if sizes is True:
×
1730
            sdata = plot_data
×
1731
        elif isinstance(sizes, str):
×
1732
            if hasattr(data, "name") and data.name == sizes:
×
1733
                sdata = plot_data
×
1734
            elif sizes in list(data.coords.keys()):
×
1735
                sdata = plot_data[sizes]
×
1736
            else:
1737
                raise ValueError(f"{sizes} not found")
×
1738
        else:
1739
            raise TypeError("sizes must be a string or a bool")
×
1740

1741
        # nans sizes
1742
        smask = ~np.isnan(sdata.values) & mask
×
1743
        if np.sum(smask) < np.sum(mask):
×
1744
            warnings.warn(
×
1745
                f"{np.sum(mask) - np.sum(smask)} nan values were dropped when setting the point size", stacklevel=2
1746
            )
1747
            mask = smask
×
1748

1749
        pt_sizes = norm2range(
×
1750
            data=sdata.where(mask).values,
1751
            target_range=size_range,
1752
            data_range=None,
1753
        )
1754
        plot_kw.setdefault("add_legend", False)
×
1755
        if ax:
×
1756
            plot_kw.setdefault("s", pt_sizes)
×
1757
        else:
1758
            plot_kw.setdefault("s", pt_sizes[0])
×
1759

1760
    # norm
1761
    plot_kw.setdefault("vmin", np.nanmin(plot_data.values[mask]))
×
1762
    plot_kw.setdefault("vmax", np.nanmax(plot_data.values[mask]))
×
1763
    if levels is not None:
×
1764
        if isinstance(levels, Iterable):
×
1765
            lin = levels
×
1766
        else:
1767
            lin = custom_cmap_norm(
×
1768
                cmap,
1769
                np.nanmin(plot_data.values[mask]),
1770
                np.nanmax(plot_data.values[mask]),
1771
                levels=levels,
1772
                divergent=divergent,
1773
                linspace_out=True,
1774
            )
1775
        plot_kw.setdefault("levels", lin)
×
1776

1777
    elif (divergent is not False) and ("levels" not in plot_kw):
×
1778
        vmin = plot_kw.pop("vmin", np.nanmin(plot_data.values[mask]))
×
1779
        vmax = plot_kw.pop("vmax", np.nanmax(plot_data.values[mask]))
×
1780
        norm = custom_cmap_norm(
×
1781
            cmap,
1782
            vmin,
1783
            vmax,
1784
            levels=levels,
1785
            divergent=divergent,
1786
        )
1787
        plot_kw.setdefault("norm", norm)
×
1788

1789
    # matplotlib.pyplot.scatter treats "edgecolor" and "edgecolors" as aliases so we accept "edgecolor" and convert it
1790
    if "edgecolor" in plot_kw and "edgecolors" not in plot_kw:
×
1791
        plot_kw["edgecolors"] = plot_kw["edgecolor"]
×
1792
        plot_kw.pop("edgecolor")
×
1793

1794
    # set defaults and create copy without vmin, vmax (conflicts with norm)
1795
    plot_kw = {
×
1796
        "cmap": cmap,
1797
        "transform": transform,
1798
        "zorder": 8,
1799
        "marker": "o",
1800
    } | plot_kw
1801

1802
    # check if edgecolors in plot_kw and match len of plot_data
1803
    if "edgecolors" in plot_kw:
×
1804
        if matplotlib.colors.is_color_like(plot_kw["edgecolors"]):
×
1805
            plot_kw["edgecolors"] = np.repeat(
×
1806
                plot_kw["edgecolors"], len(plot_data.where(mask).values)
1807
            )
1808
        elif len(plot_kw["edgecolors"]) != len(plot_data.values):
×
1809
            plot_kw["edgecolors"] = np.repeat(
×
1810
                plot_kw["edgecolors"][0], len(plot_data.where(mask).values)
1811
            )
1812
            warnings.warn(
×
1813
                "Length of edgecolors does not match length of data. Only first edgecolor is used for plotting.", stacklevel=2
1814
            )
1815
        else:
1816
            if isinstance(plot_kw["edgecolors"], list):
×
1817
                plot_kw["edgecolors"] = np.array(plot_kw["edgecolors"])
×
1818
            plot_kw["edgecolors"] = plot_kw["edgecolors"][mask]
×
1819
    else:
1820
        plot_kw.setdefault("edgecolors", "none")
×
1821

1822
    for key in ["vmin", "vmax"]:
×
1823
        plot_kw.pop(key, None)
×
1824
    # plot
1825
    plot_kw = {"x": "lon", "y": "lat", "hue": plot_data.name} | plot_kw
×
1826
    if ax:
×
1827
        plot_kw.setdefault("ax", ax)
×
1828

1829
    plot_data_masked = plot_data.where(mask).to_dataset()
×
1830
    im = plot_data_masked.plot.scatter(**plot_kw)
×
1831

1832
    # add features
1833
    if ax:
×
1834
        ax = add_features_map(
×
1835
            data,
1836
            ax,
1837
            use_attrs,
1838
            projection,
1839
            features,
1840
            geometries_kw,
1841
            frame,
1842
        )
1843

1844
        if show_time:
×
1845
            if isinstance(show_time, bool):
×
1846
                plot_coords(
×
1847
                    ax,
1848
                    plot_data,
1849
                    param="time",
1850
                    loc="lower right",
1851
                    backgroundalpha=1,
1852
                )
1853
            elif isinstance(show_time, str | tuple | int):
×
1854
                plot_coords(
×
1855
                    ax,
1856
                    plot_data,
1857
                    param="time",
1858
                    loc=show_time,
1859
                    backgroundalpha=1,
1860
                )
1861

1862
        if (frame is False) and (im.colorbar is not None):
×
1863
            im.colorbar.outline.set_visible(False)
×
1864

1865
    else:
1866
        for i, fax in enumerate(im.axs.flat):
×
1867
            fax = add_features_map(
×
1868
                data,
1869
                fax,
1870
                use_attrs,
1871
                projection,
1872
                features,
1873
                geometries_kw,
1874
                frame,
1875
            )
1876

1877
            if sizes:
×
1878
                # correct markersize for facetgrid
1879
                scat = fax.collections[0]
×
1880
                scat.set_sizes(pt_sizes[i])
×
1881

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

1885
        if show_time:
×
1886
            if isinstance(show_time, bool):
×
1887
                plot_coords(
×
1888
                    None,
1889
                    plot_data,
1890
                    param="time",
1891
                    loc="lower right",
1892
                    backgroundalpha=1,
1893
                )
1894
            elif isinstance(show_time, str | tuple | int):
×
1895
                plot_coords(
×
1896
                    None,
1897
                    plot_data,
1898
                    param="time",
1899
                    loc=show_time,
1900
                    backgroundalpha=1,
1901
                )
1902

1903
    # size legend
1904
    if sizes:
×
1905
        legend_elements = size_legend_elements(
×
1906
            np.resize(sdata.values[mask], (sdata.values[mask].size, 1)),
1907
            np.resize(pt_sizes[mask], (pt_sizes[mask].size, 1)),
1908
            max_entries=6,
1909
            marker=plot_kw["marker"],
1910
        )
1911
        # legend spacing
1912
        if size_range[1] > 200:
×
1913
            ls = 0.5 + size_range[1] / 100 * 0.125
×
1914
        else:
1915
            ls = 0.5
×
1916

1917
        legend_kw = {
×
1918
            "loc": "lower left",
1919
            "facecolor": "w",
1920
            "framealpha": 1,
1921
            "edgecolor": "w",
1922
            "labelspacing": ls,
1923
            "handles": legend_elements,
1924
            "bbox_to_anchor": (-0.05, -0.1),
1925
        } | legend_kw
1926

1927
        if "title" not in legend_kw:
×
1928
            if hasattr(sdata, "long_name"):
×
1929
                lgd_title = wrap_text(
×
1930
                    sdata.long_name, min_line_len=1, max_line_len=15
1931
                )
1932
                if hasattr(sdata, "units"):
×
1933
                    lgd_title += f" ({sdata.units})"
×
1934
            else:
1935
                lgd_title = sizes
×
1936
            legend_kw.setdefault("title", lgd_title)
×
1937

1938
        if ax:
×
1939
            lgd = ax.legend(**legend_kw)
×
1940
            lgd.set_zorder(11)
×
1941
        else:
1942
            im.figlegend = im.fig.legend(**legend_kw)
×
1943
        # im._adjust_fig_for_guide(im.figlegend)
1944

1945
    if ax:
×
1946
        return ax
×
1947
    else:
1948
        im.fig.suptitle(get_attributes("long_name", data))
×
1949
        im.set_titles(template="{value}")
×
1950
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
1951
            for idx, ax in enumerate(im.axs.flat):
×
1952
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
1953

1954
        return im
×
1955

1956

1957
def taylordiagram(
6✔
1958
    data: xr.DataArray | dict[str, xr.DataArray],
1959
    plot_kw: dict[str, Any] | None = None,
1960
    fig_kw: dict[str, Any] | None = None,
1961
    std_range: tuple = (0, 1.5),
1962
    contours: int | None = 4,
1963
    contours_kw: dict[str, Any] | None = None,
1964
    ref_std_line: bool = False,
1965
    legend_kw: dict[str, Any] | None = None,
1966
    std_label: str | None = None,
1967
    corr_label: str | None = None,
1968
    colors_key: str | None = None,
1969
    markers_key: str | None = None,
1970
):
1971
    """
1972
    Build a Taylor diagram.
1973

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

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

2007
    Returns
2008
    -------
2009
    (plt.figure, mpl_toolkits.axisartist.floating_axes.FloatingSubplot, plt.legend)
2010
    """
2011
    plot_kw = empty_dict(plot_kw)
×
2012
    fig_kw = empty_dict(fig_kw)
×
2013
    contours_kw = empty_dict(contours_kw)
×
2014
    legend_kw = empty_dict(legend_kw)
×
2015

2016
    # preserve order of dimensions if used for marker/color
2017
    ordered_markers_type = None
×
2018
    ordered_colors_type = None
×
2019

2020
    # convert SSP, RCP, CMIP formats in keys
2021
    if isinstance(data, dict):
×
2022
        data = process_keys(data, convert_scen_name)
×
2023
    if isinstance(plot_kw, dict):
×
2024
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
2025

2026
    # if only one data input, insert in dict.
2027
    if not isinstance(data, dict):
×
2028
        data = {"_no_label": data}  # mpl excludes labels starting with "_" from legend
×
2029
        plot_kw = {"_no_label": empty_dict(plot_kw)}
×
2030
    elif not plot_kw:
×
2031
        plot_kw = {k: {} for k in data.keys()}
×
2032
    # check type
2033
    for key, v in data.items():
×
2034
        if not isinstance(v, xr.DataArray):
×
2035
            raise TypeError("All objects in 'data' must be xarray DataArrays.")
×
2036
        if "taylor_param" not in v.dims:
×
2037
            raise ValueError("All DataArrays must contain a 'taylor_param' dimension.")
×
2038
        if key == "reference":
×
2039
            raise ValueError("'reference' is not allowed as a key in data.")
×
2040

2041
    # If there are other dimensions than 'taylor_param', create a bigger dict with them
2042
    data_keys = list(data.keys())
×
2043
    for data_key in data_keys:
×
2044
        da = data[data_key]
×
2045
        dims = list(set(da.dims) - {"taylor_param"})
×
2046
        if dims != []:
×
2047
            if markers_key in dims:
×
2048
                ordered_markers_type = da[markers_key].values
×
2049
            if colors_key in dims:
×
2050
                ordered_colors_type = da[colors_key].values
×
2051

2052
            da = da.stack(pl_dims=dims)
×
2053
            for i, dim_key in enumerate(da.pl_dims.values):
×
2054
                if isinstance(dim_key, list) or isinstance(dim_key, tuple):
×
2055
                    dim_key = "-".join([str(k) for k in dim_key])
×
2056
                da0 = da.isel(pl_dims=i)
×
2057
                # if colors_key/markers_key is a dimension, add it as an attribute for later use
2058
                if markers_key in dims:
×
2059
                    da0.attrs[markers_key] = da0[markers_key].values.item()
×
2060
                if colors_key in dims:
×
2061
                    da0.attrs[colors_key] = da0[colors_key].values.item()
×
2062
                new_data_key = (
×
2063
                    f"{data_key}-{dim_key}" if data_key != "_no_label" else dim_key
2064
                )
2065
                data[new_data_key] = da0
×
2066
                plot_kw[new_data_key] = empty_dict(plot_kw[f"{data_key}"])
×
2067
            data.pop(data_key)
×
2068
            plot_kw.pop(data_key)
×
2069

2070
    # remove negative correlations
2071
    initial_len = len(data)
×
2072
    removed = [
×
2073
        key for key, da in data.items() if da.sel(taylor_param="corr").values < 0
2074
    ]
2075
    data = {
×
2076
        key: da for key, da in data.items() if da.sel(taylor_param="corr").values >= 0
2077
    }
2078
    if len(data) != initial_len:
×
2079
        warnings.warn(
×
2080
            f"{initial_len - len(data)} points with negative correlations will not be plotted: {', '.join(removed)}", stacklevel=2
2081
        )
2082

2083
    # add missing keys to plot_kw
2084
    for key in data.keys():
×
2085
        if key not in plot_kw:
×
2086
            plot_kw[key] = {}
×
2087

2088
    # extract ref to be used in plot
2089
    ref_std = list(data.values())[0].sel(taylor_param="ref_std").values
×
2090
    # check if ref is the same in all DataArrays and get the highest std (for ax limits)
2091
    if len(data) > 1:
×
2092
        for da in data.values():
×
2093
            if da.sel(taylor_param="ref_std").values != ref_std:
×
2094
                raise ValueError(
×
2095
                    "All reference standard deviation values must be identical"
2096
                )
2097

2098
    # get highest std for axis limits
2099
    max_std = [ref_std]
×
2100
    for da in data.values():
×
2101
        max_std.extend(
×
2102
            [
2103
                max(
2104
                    da.sel(taylor_param="ref_std").values,
2105
                    da.sel(taylor_param="sim_std").values,
2106
                ).astype(float)
2107
            ]
2108
        )
2109

2110
    # make labels
2111
    if not std_label:
×
2112
        try:
×
2113
            units = list(data.values())[0].units
×
2114
            std_label = get_localized_term("standard deviation")
×
2115
            std_label = std_label if units == "" else f"{std_label} ({units})"
×
2116
        except AttributeError:
×
2117
            std_label = get_localized_term("standard deviation").capitalize()
×
2118

2119
    if not corr_label:
×
2120
        try:
×
2121
            if "Pearson" in list(data.values())[0].correlation_type:
×
2122
                corr_label = get_localized_term("pearson correlation").capitalize()
×
2123
            else:
2124
                corr_label = get_localized_term("correlation").capitalize()
×
2125
        except AttributeError:
×
2126
            corr_label = get_localized_term("correlation").capitalize()
×
2127

2128
    # build diagram
2129
    transform = PolarAxes.PolarTransform()
×
2130

2131
    # Setup the axis, here we map angles in degrees to angles in radius
2132
    # Correlation labels
2133
    rlocs = np.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
×
2134
    tlocs = np.arccos(rlocs)  # Conversion to polar angles
×
2135
    gl1 = gf.FixedLocator(tlocs)  # Positions
×
2136
    tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, rlocs), strict=False)))
×
2137
    # Standard deviation axis extent
2138
    radius_min = std_range[0] * max(max_std)
×
2139
    radius_max = std_range[1] * max(max_std)
×
2140

2141
    # Set up the axes range in the parameter "extremes"
2142
    ghelper = GridHelperCurveLinear(
×
2143
        transform,
2144
        extremes=(0, np.pi / 2, radius_min, radius_max),
2145
        grid_locator1=gl1,
2146
        tick_formatter1=tf1,
2147
    )
2148

2149
    fig = plt.figure(**fig_kw)
×
2150
    floating_ax = FloatingSubplot(fig, 111, grid_helper=ghelper)
×
2151
    fig.add_subplot(floating_ax)
×
2152

2153
    # Adjust axes
2154
    floating_ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
×
2155
    floating_ax.axis["top"].toggle(ticklabels=True, label=True)
×
2156
    floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
×
2157
    floating_ax.axis["top"].label.set_axis_direction("top")
×
2158
    floating_ax.axis["top"].label.set_text(corr_label)
×
2159

2160
    floating_ax.axis["left"].set_axis_direction("bottom")  # "X axis"
×
2161
    floating_ax.axis["left"].label.set_text(std_label)
×
2162

2163
    floating_ax.axis["right"].set_axis_direction("top")  # "Y axis"
×
2164
    floating_ax.axis["right"].toggle(ticklabels=True, label=True)
×
2165
    floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
×
2166
    floating_ax.axis["right"].label.set_text(std_label)
×
2167

2168
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2169

2170
    # Contours along standard deviations
2171
    floating_ax.grid(visible=True, alpha=0.4)
×
2172
    floating_ax.set_title("")
×
2173

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

2176
    # plot reference
2177
    if "reference" in plot_kw:
×
2178
        ref_kw = plot_kw.pop("reference")
×
2179
    else:
2180
        ref_kw = {}
×
2181
    ref_kw = {
×
2182
        "color": "#154504",
2183
        "marker": "s",
2184
        "label": get_localized_term("reference"),
2185
    } | ref_kw
2186

2187
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2188

2189
    points = [ref_pt]  # set up for later
×
2190

2191
    # plot a circular line along `ref_std`
2192
    if ref_std_line:
×
2193
        angles_for_line = np.linspace(0, np.pi / 2, 100)
×
2194
        radii_for_line = np.full_like(angles_for_line, ref_std)
×
2195
        ax.plot(
×
2196
            angles_for_line,
2197
            radii_for_line,
2198
            color=ref_kw["color"],
2199
            linewidth=0.5,
2200
            linestyle="-",
2201
        )
2202

2203
    # rmse contours from reference standard deviation
2204
    if contours:
×
2205
        radii, angles = np.meshgrid(
×
2206
            np.linspace(radius_min, radius_max),
2207
            np.linspace(0, np.pi / 2),
2208
        )
2209
        # Compute centered RMS difference
2210
        rms = np.sqrt(ref_std**2 + radii**2 - 2 * ref_std * radii * np.cos(angles))
×
2211

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

2215
        ax.clabel(ct, ct.levels, fontsize=8)
×
2216

2217
        # points.append(ct_line)
2218
        ct_line = ax.plot(
×
2219
            [0],
2220
            [0],
2221
            ls=contours_kw["linestyles"],
2222
            lw=1,
2223
            c="k" if "colors" not in contours_kw else contours_kw["colors"],
2224
            label="rmse",
2225
        )
2226
        points.append(ct_line[0])
×
2227

2228
    # get color options
2229
    style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
2230
    if len(data) > len(style_colors):
×
2231
        style_colors = style_colors * math.ceil(len(data) / len(style_colors))
×
2232
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
2233
    # get marker options (only used if `markers_key` is set)
2234
    style_markers = "oDv^<>p*hH+x|_"
×
2235
    if len(data) > len(style_markers):
×
2236
        style_markers = style_markers * math.ceil(len(data) / len(style_markers))
×
2237

2238
    # set colors and markers styles based on discrimnating attributes (if specified)
2239
    if colors_key or markers_key:
×
2240
        if colors_key:
×
2241
            # get_scen_color : look for SSP, RCP, CMIP model color
2242
            colors_type = (
×
2243
                ordered_colors_type
2244
                if ordered_colors_type is not None
2245
                else {da.attrs[colors_key] for da in data.values()}
2246
            )
2247
            colorsd = {
×
2248
                k: get_scen_color(k, cat_colors) or style_colors[i]
2249
                for i, k in enumerate(colors_type)
2250
            }
2251
        if markers_key:
×
2252
            markers_type = (
×
2253
                ordered_markers_type
2254
                if ordered_markers_type is not None
2255
                else {da.attrs[markers_key] for da in data.values()}
2256
            )
2257
            markersd = {k: style_markers[i] for i, k in enumerate(markers_type)}
×
2258

2259
        for key, da in data.items():
×
2260
            if colors_key:
×
2261
                plot_kw[key]["color"] = colorsd[da.attrs[colors_key]]
×
2262
            if markers_key:
×
2263
                plot_kw[key]["marker"] = markersd[da.attrs[markers_key]]
×
2264

2265
    # plot scatter
2266
    for (key, da), i in zip(data.items(), range(len(data)), strict=False):
×
2267
        # look for SSP, RCP, CMIP model color
2268
        if colors_key is None:
×
2269
            plot_kw[key].setdefault(
×
2270
                "color", get_scen_color(key, cat_colors) or style_colors[i]
2271
            )
2272
        # set defaults
2273
        plot_kw[key] = {"label": key} | plot_kw[key]
×
2274

2275
        # legend will be handled later in this case
2276
        if markers_key or colors_key:
×
2277
            plot_kw[key]["label"] = ""
×
2278

2279
        # plot
2280
        pt = ax.scatter(
×
2281
            np.arccos(da.sel(taylor_param="corr").values),
2282
            da.sel(taylor_param="sim_std").values,
2283
            **plot_kw[key],
2284
        )
2285
        points.append(pt)
×
2286

2287
    # legend
2288
    legend_kw.setdefault("loc", "upper right")
×
2289
    legend = fig.legend(points, [pt.get_label() for pt in points], **legend_kw)
×
2290

2291
    # plot new legend if markers/colors represent a certain dimension
2292
    if colors_key or markers_key:
×
2293
        handles = list(floating_ax.get_legend_handles_labels()[0])
×
2294
        if markers_key:
×
2295
            for k, m in markersd.items():
×
2296
                handles.append(Line2D([0], [0], color="k", label=k, marker=m, ls=""))
×
2297
        if colors_key:
×
2298
            for k, c in colorsd.items():
×
2299
                handles.append(Line2D([0], [0], color=c, label=k, ls="-"))
×
2300
        legend.remove()
×
2301
        legend = fig.legend(handles=handles, **legend_kw)
×
2302

2303
    return fig, floating_ax, legend
×
2304

2305

2306
def hatchmap(
6✔
2307
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
2308
    ax: matplotlib.axes.Axes | None = None,
2309
    use_attrs: dict[str, Any] | None = None,
2310
    fig_kw: dict[str, Any] | None = None,
2311
    plot_kw: dict[str, Any] | None = None,
2312
    projection: ccrs.Projection = ccrs.LambertConformal(),
2313
    transform: ccrs.Projection | None = None,
2314
    features: list[str] | dict[str, dict[str, Any]] | None = None,
2315
    geometries_kw: dict[str, Any] | None = None,
2316
    levels: int | None = None,
2317
    legend_kw: dict[str, Any] | bool = True,
2318
    show_time: bool | str | int | tuple[float, float] = False,
2319
    frame: bool = False,
2320
    enumerate_subplots: bool = False,
2321
) -> matplotlib.axes.Axes:
2322
    """
2323
    Create map of hatches from 2D data.
2324

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

2358
        ==================   =============
2359
        Location String      Location Code
2360
        ==================   =============
2361
        'upper right'        1
2362
        'upper left'         2
2363
        'lower left'         3
2364
        'lower right'        4
2365
        'right'              5
2366
        'center left'        6
2367
        'center right'       7
2368
        'lower center'       8
2369
        'upper center'       9
2370
        'center'             10
2371
        ==================   =============
2372
    frame : bool
2373
        Show or hide frame. Default False.
2374
    enumerate_subplots: bool
2375
        If True, enumerate subplots with letters.
2376
        Only works with facetgrids (pass `col` or `row` in plot_kw).
2377

2378
    Returns
2379
    -------
2380
    matplotlib.axes.Axes
2381
    """
2382
    # default hatches
2383
    dfh = [
×
2384
        "/",
2385
        "\\",
2386
        "|",
2387
        "-",
2388
        "+",
2389
        "x",
2390
        "o",
2391
        "O",
2392
        ".",
2393
        "*",
2394
        "//",
2395
        "\\\\",
2396
        "||",
2397
        "--",
2398
        "++",
2399
        "xx",
2400
        "oo",
2401
        "OO",
2402
        "..",
2403
        "**",
2404
    ]
2405

2406
    # create empty dicts if None
2407
    use_attrs = empty_dict(use_attrs)
×
2408
    fig_kw = empty_dict(fig_kw)
×
2409
    plot_kw = empty_dict(plot_kw)
×
2410
    legend_kw = empty_dict(legend_kw)
×
2411

2412
    dattrs = None
×
2413
    plot_data = {}
×
2414

2415
    # convert data to dict (if not one)
2416
    if not isinstance(data, dict):
×
2417
        if isinstance(data, xr.DataArray):
×
2418
            plot_data = {data.name: data}
×
2419
            if data.name not in plot_kw.keys():
×
2420
                plot_kw = {data.name: plot_kw}
×
2421
        elif isinstance(data, xr.Dataset):
×
2422
            dattrs = data
×
2423
            plot_data = {var: data[var] for var in data.data_vars}
×
2424
            for v in plot_data.keys():
×
2425
                if v not in plot_kw.keys():
×
2426
                    plot_kw[v] = plot_kw
×
2427
    else:
2428
        for k, v in data.items():
×
2429
            if k not in plot_kw.keys():
×
2430
                plot_kw[k] = plot_kw
×
2431
            if isinstance(v, xr.Dataset):
×
2432
                dattrs = k
×
2433
                plot_data[k] = v[list(v.data_vars)[0]]
×
2434
                warnings.warn("Only first variable of Dataset is plotted.", stacklevel=2)
×
2435
            else:
2436
                plot_data[k] = v
×
2437

2438
    # setup transform from first data entry
2439
    trdata = list(plot_data.values())[0]
×
2440
    if transform is None:
×
2441
        if "lat" in trdata.dims and "lon" in trdata.dims:
×
2442
            transform = ccrs.PlateCarree()
×
2443
        elif "rlat" in trdata.dims and "rlon" in trdata.dims:
×
2444
            transform = get_rotpole(list(plot_data.values())[0])
×
2445

2446
    # bug xlim / ylim + transform in facetgrids
2447
    # (see https://github.com/pydata/xarray/issues/8562#issuecomment-1865189766)
2448
    if transform and (
×
2449
        "xlim" in list(plot_kw.values())[0] and "ylim" in list(plot_kw.values())[0]
2450
    ):
2451
        extent = [
×
2452
            list(plot_kw.values())[0]["xlim"][0],
2453
            list(plot_kw.values())[0]["xlim"][1],
2454
            list(plot_kw.values())[0]["ylim"][0],
2455
            list(plot_kw.values())[0]["ylim"][1],
2456
        ]
2457
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2458

2459
    elif transform and (
×
2460
        "xlim" in list(plot_kw.values())[0] or "ylim" in list(plot_kw.values())[0]
2461
    ):
2462
        extent = None
×
2463
        warnings.warn(
×
2464
            "Requires both xlim and ylim with 'transform'. Xlim or ylim was dropped", stacklevel=2
2465
        )
2466
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2467

2468
    else:
2469
        extent = None
×
2470

2471
    # setup fig, ax
2472
    if ax is None and (
×
2473
        "row" not in list(plot_kw.values())[0].keys()
2474
        and "col" not in list(plot_kw.values())[0].keys()
2475
    ):
2476
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
2477
    elif ax is not None and (
×
2478
        "col" in list(plot_kw.values())[0].keys()
2479
        or "row" in list(plot_kw.values())[0].keys()
2480
    ):
2481
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
2482
    elif ax is None:
×
2483
        [
×
2484
            v.setdefault("subplot_kws", {}).setdefault("projection", projection)
2485
            for v in plot_kw.values()
2486
        ]
2487
        cfig_kw = copy.deepcopy(fig_kw)
×
2488
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
2489
            plot_kw[0].setdefault("figsize", fig_kw["figsize"])
×
2490
            cfig_kw.pop("figsize")
×
2491
        if cfig_kw:
×
2492
            for v in plot_kw.values():
×
2493
                {"subplots_kws": cfig_kw} | v
×
2494
            warnings.warn(
×
2495
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid.", stacklevel=2
2496
            )
2497

2498
    pat_leg = []
×
2499
    n = 0
×
2500
    for k, v in plot_data.items():
×
2501
        # if levels plot multiple hatching from one data entry
2502
        if "levels" in plot_kw[k] and len(plot_data) == 1:
×
2503
            # nans
2504
            mask = ~np.isnan(v.values)
×
2505
            if np.sum(mask) < len(mask):
×
2506
                warnings.warn(
×
2507
                    f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the pattern values", stacklevel=2
2508
                )
2509
            if "hatches" in plot_kw[k] and plot_kw[k]["levels"] != len(
×
2510
                plot_kw[k]["hatches"]
2511
            ):
2512
                warnings.warn("Hatches number is not equivalent to number of levels", stacklevel=2)
×
2513
                hatches = dfh[0:levels]
×
2514
            if "hatches" not in plot_kw[k]:
×
2515
                hatches = dfh[0:levels]
×
2516

2517
            plot_kw[k] = {
×
2518
                "hatches": hatches,
2519
                "colors": "none",
2520
                "add_colorbar": False,
2521
            } | plot_kw[k]
2522

2523
            if "lat" in v.dims:
×
2524
                v.coords["mask"] = (("lat", "lon"), mask)
×
2525
            else:
2526
                v.coords["mask"] = (("rlat", "rlon"), mask)
×
2527

2528
            plot_kw[k].setdefault("transform", transform)
×
2529
            if ax:
×
2530
                plot_kw[k].setdefault("ax", ax)
×
2531

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

2535
            if ax and legend_kw:
×
2536
                ax.legend(artists, labels, **legend_kw)
×
2537
            elif legend_kw:
×
2538
                im.figlegend = im.fig.legend(**legend_kw)
×
2539

2540
        elif len(plot_data) > 1 and "levels" in plot_kw[k]:
×
2541
            raise TypeError(
×
2542
                "To plot levels only one xr.DataArray or xr.Dataset accepted"
2543
            )
2544
        else:
2545
            # since pattern remove colors and colorbar from plotting (done by gridmap)
2546
            plot_kw[k] = {"colors": "none", "add_colorbar": False} | plot_kw[k]
×
2547

2548
            if "hatches" not in plot_kw[k].keys():
×
2549
                plot_kw[k]["hatches"] = dfh[n]
×
2550
                n += 1
×
2551
            elif isinstance(
×
2552
                plot_kw[k]["hatches"], str
2553
            ):  # make sure the hatches are in a list
2554
                warnings.warn(
×
2555
                    "Hatches argument must be of type 'list'. Wrapping string argument as list.", stacklevel=2
2556
                )
2557
                plot_kw[k]["hatches"] = [plot_kw[k]["hatches"]]
×
2558

2559
            plot_kw[k].setdefault("transform", transform)
×
2560
            if ax:
×
2561
                im = v.plot.contourf(ax=ax, **plot_kw[k])
×
2562

2563
            if not ax:
×
2564
                if k == list(plot_data.keys())[0]:
×
2565
                    c_pkw = plot_kw[k].copy()
×
2566
                    if "col" in plot_kw[k].keys() or "row" in plot_kw[k].keys():
×
2567
                        if c_pkw["colors"] == "none":
×
2568
                            c_pkw.pop("colors")
×
2569
                        im = v.plot.contourf(**c_pkw)
×
2570

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

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

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

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

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

2621
    # add features
2622
    if ax:
×
2623
        if extent:
×
2624
            ax.set_extent(extent)
×
2625
        if dattrs:
×
2626
            use_attrs.setdefault("title", "description")
×
2627

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

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

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

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

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

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

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

2695
        return im
×
2696

2697

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

2705

2706
def partition(
6✔
2707
    data: xr.DataArray | xr.Dataset,
2708
    ax: matplotlib.axes.Axes | None = None,
2709
    start_year: str | None = None,
2710
    show_num: bool = True,
2711
    fill_kw: dict[str, Any] | None = None,
2712
    line_kw: dict[str, Any] | None = None,
2713
    fig_kw: dict[str, Any] | None = None,
2714
    legend_kw: dict[str, Any] | None = None,
2715
) -> matplotlib.axes.Axes:
2716
    """
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", stacklevel=2
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", stacklevel=2
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
    """
2852
    Create a triangle heatmap from a DataArray.
2853

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

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

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

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

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

2915
    # colormap
NEW
2916
    if cmap is None:
×
NEW
2917
        cmap = get_ipcc_cmap_name(
×
2918
            get_var_group(da=da),
2919
            divergent=divergent,
2920
        )
2921

2922
    # prep data
2923
    d = [da.sel(**{z: v}).values for v in da[z].values]
×
2924

2925
    other_dims = [di for di in da.dims if di != z]
×
2926
    if len(other_dims) > 2:
×
2927
        warnings.warn(
×
2928
            "More than 3 dimensions in data. The first two after dim will be used as the dimensions of the heatmap.", stacklevel=2
2929
        )
2930
    if len(other_dims) < 2:
×
2931
        raise ValueError(
×
2932
            "Data must have 3 dimensions. If you only have 2 dimensions, use fg.heatmap."
2933
        )
2934

2935
    if plot_kw == {} and cbar in ["unique", True]:
×
2936
        warnings.warn(
×
2937
            'With cbar="unique" only the colorbar of the first triangle'
2938
            " will be shown. No `plot_kw` was passed. vmin and vmax will be set the max"
2939
            " and min of data.", stacklevel=2
2940
        )
2941
        plot_kw = {"vmax": da.max().values, "vmin": da.min().values}
×
2942

2943
    if isinstance(plot_kw, dict):
×
2944
        plot_kw.setdefault("cmap", cmap)
×
2945
        plot_kw.setdefault("ec", "white")
×
2946
        plot_kw = [plot_kw for _ in range(len(d))]
×
2947

2948
    labels_x = da[other_dims[0]].values
×
2949
    labels_y = da[other_dims[1]].values
×
2950
    m, n = d[0].shape[0], d[0].shape[1]
×
2951

2952
    # plot
2953
    if len(d) == 2:
×
2954
        x = np.arange(m + 1)
×
2955
        y = np.arange(n + 1)
×
2956
        xss, ys = np.meshgrid(x, y)
×
2957
        (xss * ys) % 10
×
2958
        triangles1 = [
×
2959
            (i + j * (m + 1), i + 1 + j * (m + 1), i + (j + 1) * (m + 1))
2960
            for j in range(n)
2961
            for i in range(m)
2962
        ]
2963
        triangles2 = [
×
2964
            (
2965
                i + 1 + j * (m + 1),
2966
                i + 1 + (j + 1) * (m + 1),
2967
                i + (j + 1) * (m + 1),
2968
            )
2969
            for j in range(n)
2970
            for i in range(m)
2971
        ]
2972
        triang1 = Triangulation(xss.ravel(), ys.ravel(), triangles1)
×
2973
        triang2 = Triangulation(xss.ravel(), ys.ravel(), triangles2)
×
2974
        triangul = [triang1, triang2]
×
2975

2976
        imgs = [
×
2977
            ax.tripcolor(t, np.ravel(val), **plotkw)
2978
            for t, val, plotkw in zip(triangul, d, plot_kw, strict=False)
2979
        ]
2980

2981
        ax.set_xticks(np.array(range(m)) + 0.5, labels=labels_x, rotation=45)
×
2982
        ax.set_yticks(np.array(range(n)) + 0.5, labels=labels_y, rotation=90)
×
2983

2984
    elif len(d) == 4:
×
2985
        xv, yv = np.meshgrid(
×
2986
            np.arange(-0.5, m), np.arange(-0.5, n)
2987
        )  # vertices of the little squares
2988
        xc, yc = np.meshgrid(
×
2989
            np.arange(0, m), np.arange(0, n)
2990
        )  # centers of the little squares
2991
        x = np.concatenate([xv.ravel(), xc.ravel()])
×
2992
        y = np.concatenate([yv.ravel(), yc.ravel()])
×
2993
        cstart = (m + 1) * (n + 1)  # indices of the centers
×
2994

2995
        triangles_n = [
×
2996
            (i + j * (m + 1), i + 1 + j * (m + 1), cstart + i + j * m)
2997
            for j in range(n)
2998
            for i in range(m)
2999
        ]
3000
        triangles_e = [
×
3001
            (i + 1 + j * (m + 1), i + 1 + (j + 1) * (m + 1), cstart + i + j * m)
3002
            for j in range(n)
3003
            for i in range(m)
3004
        ]
3005
        triangles_s = [
×
3006
            (
3007
                i + 1 + (j + 1) * (m + 1),
3008
                i + (j + 1) * (m + 1),
3009
                cstart + i + j * m,
3010
            )
3011
            for j in range(n)
3012
            for i in range(m)
3013
        ]
3014
        triangles_w = [
×
3015
            (i + (j + 1) * (m + 1), i + j * (m + 1), cstart + i + j * m)
3016
            for j in range(n)
3017
            for i in range(m)
3018
        ]
3019
        triangul = [
×
3020
            Triangulation(x, y, triangles)
3021
            for triangles in [
3022
                triangles_n,
3023
                triangles_e,
3024
                triangles_s,
3025
                triangles_w,
3026
            ]
3027
        ]
3028

3029
        imgs = [
×
3030
            ax.tripcolor(t, np.ravel(val), **plotkw)
3031
            for t, val, plotkw in zip(triangul, d, plot_kw, strict=False)
3032
        ]
3033
        ax.set_xticks(np.array(range(m)), labels=labels_x, rotation=45)
×
3034
        ax.set_yticks(np.array(range(n)), labels=labels_y, rotation=90)
×
3035

3036
    else:
3037
        raise ValueError(
×
3038
            f"The length of the dimensiondim ({z},{len(d)}) should be either 2 or 4. It represents the number of triangles."
3039
        )
3040

3041
    ax.set_title(get_attributes(use_attrs.get("title", None), data))
×
3042
    ax.set_xlabel(other_dims[0])
×
3043
    ax.set_ylabel(other_dims[1])
×
3044
    if "xlabel" in use_attrs:
×
3045
        ax.set_xlabel(get_attributes(use_attrs["xlabel"], data))
×
3046
    if "ylabel" in use_attrs:
×
3047
        ax.set_ylabel(get_attributes(use_attrs["ylabel"], data))
×
3048
    ax.set_aspect("equal", "box")
×
3049
    ax.invert_yaxis()
×
3050
    ax.tick_params(left=False, bottom=False)
×
3051
    ax.spines["bottom"].set_visible(False)
×
3052
    ax.spines["left"].set_visible(False)
×
3053

3054
    # create cbar label
3055
    # set default use_attrs values
3056
    use_attrs.setdefault("cbar_label", "long_name")
×
3057
    use_attrs.setdefault("cbar_units", "units")
×
3058
    if (
×
3059
        "cbar_units" in use_attrs
3060
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
3061
    ):  # avoids '()' as label
3062
        cbar_label = (
×
3063
            get_attributes(use_attrs["cbar_label"], data)
3064
            + " ("
3065
            + get_attributes(use_attrs["cbar_units"], data)
3066
            + ")"
3067
        )
3068
    else:
3069
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
3070

3071
    if isinstance(cbar_kw, dict):
×
3072
        cbar_kw.setdefault("label", cbar_label)
×
3073
        cbar_kw = [cbar_kw for _ in range(len(d))]
×
3074
    if cbar == "unique":
×
3075
        plt.colorbar(imgs[0], ax=ax, **cbar_kw[0])
×
3076

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

3081
    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

© 2025 Coveralls, Inc