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

Ouranosinc / figanos / 31187616480

07 Aug 2026 02:26PM UTC coverage: 9.186%. First build
31187616480

Pull #416

github

web-flow
Merge 004045e98 into e6d6afaec
Pull Request #416: fix `transpose` in heatmap

0 of 8 new or added lines in 1 file covered. (0.0%)

175 of 1905 relevant lines covered (9.19%)

0.64 hits per line

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

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

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

31
from figanos.matplotlib.utils import (  # masknan_sizes_key,
7✔
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__)
7✔
59

60

61
def _plot_realizations(
7✔
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(
7✔
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(
7✔
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(
7✔
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
690
    if cmap is None:
×
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(
7✔
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
942
        if cmap is None:
×
943
            cmap = get_ipcc_cmap_name(
×
944
                get_var_group(unique_str=df_col),
945
                divergent=divergent,
946
            )
947
        if isinstance(cmap, str):
×
948
            try:
×
949
                cmap = matplotlib.colormaps[cmap]
×
950
            except KeyError:
×
951
                warnings.warn("invalid cmap, using default", stacklevel=2)
×
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 and "outline" in plot.figure.axes[1].spines:  # 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(
7✔
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(
7✔
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
1267
    if cmap is None:
×
1268
        cmap = get_ipcc_cmap_name(
×
1269
            get_var_group(da=list(data.values())[0]),
1270
            divergent=True,
1271
        )
1272
    if isinstance(cmap, str):
×
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(
7✔
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
    # get heatmap_dims
NEW
1397
    plot_kw.setdefault("col", None)
×
NEW
1398
    plot_kw.setdefault("row", None)
×
NEW
1399
    plot_kw.setdefault("margin_titles", True)
×
NEW
1400
    heatmap_dims = [d for d in da.dims if d not in [plot_kw["col"], plot_kw["row"]]]
×
NEW
1401
    if transpose:
×
NEW
1402
        heatmap_dims = heatmap_dims[::-1]
×
1403

1404
    # setup fig, axis
1405
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
1406
        fig, ax = plt.subplots(**fig_kw)
×
1407
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
1408
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
1409
    elif ax is None:
×
1410
        if any([k != "figsize" for k in fig_kw.keys()]):
×
1411
            warnings.warn(
×
1412
                "Only figsize arguments can be passed to fig_kw when using facetgrid.", stacklevel=2
1413
            )
1414
        if da.name is None:
×
1415
            da = da.to_dataset(name="data").data
×
1416
        da_name = da.name
×
1417

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

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

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

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

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

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

1462
    # plot
1463
    def draw_heatmap(*args, **kwargs):
×
1464
        data = kwargs.pop("data")
×
NEW
1465
        d = data.pivot_table(index=args[1], columns=args[0], values=args[2], sort=False)
×
1466
        ax = sns.heatmap(d, **kwargs)
×
1467
        ax.set_xticklabels(
×
1468
            ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor"
1469
        )
1470
        ax.tick_params(axis="both", direction="out")
×
1471
        set_plot_attrs(
×
1472
            use_attrs,
1473
            da,
1474
            ax,
1475
            title_loc="center",
1476
            wrap_kw={"min_line_len": 35, "max_line_len": 44},
1477
        )
1478
        return ax
×
1479

1480
    if ax is not None:
×
NEW
1481
        ax = draw_heatmap(*heatmap_dims, da_name, data=df, ax=ax, **plot_kw)
×
1482
        return ax
×
1483
    elif "col" in plot_kw or "row" in plot_kw:
×
1484
        # When using xarray's FacetGrid, `plot_kw` can be used in the FacetGrid and in the plotting function
1485
        # With Seaborn, we need to be more careful and separate keywords.
1486
        plot_kw_hm = {
×
1487
            k: v for k, v in plot_kw.items() if k in signature(sns.heatmap).parameters
1488
        }
1489
        plot_kw_fg = {
×
1490
            k: v for k, v in plot_kw.items() if k in signature(sns.FacetGrid).parameters
1491
        }
1492
        unused_keys = (
×
1493
            set(plot_kw.keys()) - set(plot_kw_fg.keys()) - set(plot_kw_hm.keys())
1494
        )
1495
        if unused_keys != set():
×
1496
            raise ValueError(
×
1497
                f"`heatmap` got unexpected keywords in `plot_kw`: {unused_keys}. Keywords in `plot_kw` should be keywords "
1498
                "allowed in `sns.heatmap` or `sns.FacetGrid`. "
1499
            )
1500

1501
        g = sns.FacetGrid(df, **plot_kw_fg)
×
1502
        cax = g.fig.add_axes([0.95, 0.05, 0.02, 0.9])
×
1503
        g.map_dataframe(
×
1504
            draw_heatmap,
1505
            *heatmap_dims,
1506
            da_name,
1507
            **plot_kw_hm,
1508
            cbar=True,
1509
            cbar_ax=cax,
1510
        )
1511
        g.fig.subplots_adjust(right=0.9)
×
1512
        if "figsize" in fig_kw.keys():
×
1513
            g.fig.set_size_inches(*fig_kw["figsize"])
×
1514
        return g
×
1515

1516

1517
def scattermap(
7✔
1518
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1519
    ax: matplotlib.axes.Axes | None = None,
1520
    use_attrs: dict[str, Any] | None = None,
1521
    fig_kw: dict[str, Any] | None = None,
1522
    plot_kw: dict[str, Any] | None = None,
1523
    projection: ccrs.Projection = ccrs.LambertConformal(),
1524
    transform: ccrs.Projection | None = None,
1525
    features: list[str] | dict[str, dict[str, Any]] | None = None,
1526
    geometries_kw: dict[str, Any] | None = None,
1527
    sizes: str | bool | None = None,
1528
    size_range: tuple = (10, 60),
1529
    cmap: str | matplotlib.colors.Colormap | None = None,
1530
    levels: int | None = None,
1531
    divergent: bool | int | float = False,
1532
    legend_kw: dict[str, Any] | None = None,
1533
    show_time: bool | str | int | tuple[float, float] = False,
1534
    frame: bool = False,
1535
    enumerate_subplots: bool = False,
1536
) -> matplotlib.axes.Axes:
1537
    """
1538
    Make a scatter plot of georeferenced data on a map.
1539

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

1587
        ==================   =============
1588
        Location String      Location Code
1589
        ==================   =============
1590
        'upper right'        1
1591
        'upper left'         2
1592
        'lower left'         3
1593
        'lower right'        4
1594
        'right'              5
1595
        'center left'        6
1596
        'center right'       7
1597
        'lower center'       8
1598
        'upper center'       9
1599
        'center'             10
1600
        ==================   =============
1601
    frame : bool
1602
        Show or hide frame. Default False.
1603
    enumerate_subplots: bool
1604
        If True, enumerate subplots with letters.
1605
        Only works with facetgrids (pass `col` or `row` in plot_kw).
1606

1607
    Returns
1608
    -------
1609
    matplotlib.axes.Axes
1610
    """
1611
    # create empty dicts if None
1612
    use_attrs = empty_dict(use_attrs)
×
1613
    fig_kw = empty_dict(fig_kw)
×
1614
    plot_kw = empty_dict(plot_kw)
×
1615
    legend_kw = empty_dict(legend_kw)
×
1616

1617
    # set default use_attrs values
1618
    use_attrs = {"cbar_label": "long_name", "cbar_units": "units"} | use_attrs
×
1619
    if "row" not in plot_kw and "col" not in plot_kw:
×
1620
        use_attrs.setdefault("title", "description")
×
1621

1622
    # extract plot_kw from dict if needed
1623
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1624
        plot_kw = plot_kw[list(data.keys())[0]]
×
1625

1626
    # figanos does not use xr.plot.scatter default markersize
1627
    if "markersize" in plot_kw.keys():
×
1628
        if not sizes:
×
1629
            sizes = plot_kw["markersize"]
×
1630
        plot_kw.pop("markersize")
×
1631

1632
    # if data is dict, extract
1633
    if isinstance(data, dict):
×
1634
        if len(data) == 1:
×
1635
            data = list(data.values())[0].squeeze()
×
1636
            if len(data.data_vars) > 1:
×
1637
                warnings.warn(
×
1638
                    "data is xr.Dataset; only the first variable will be used in plot", stacklevel=2
1639
                )
1640
        else:
1641
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1642

1643
    # select data to plot and its xr.Dataset
1644
    if isinstance(data, xr.DataArray):
×
1645
        plot_data = data
×
1646
        data = xr.Dataset({plot_data.name: plot_data})
×
1647
    elif isinstance(data, xr.Dataset):
×
1648
        if len(data.data_vars) > 1:
×
1649
            warnings.warn(
×
1650
                "data is xr.Dataset; only the first variable will be used in plot", stacklevel=2
1651
            )
1652
        plot_data = data[list(data.keys())[0]]
×
1653
    else:
1654
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1655

1656
    # setup transform
1657
    if transform is None:
×
1658
        if "rlat" in data.dims and "rlon" in data.dims:
×
1659
            transform = get_rotpole(data)
×
1660
        elif (
×
1661
            "lat" in data.coords and "lon" in data.coords
1662
        ):  # need to work with station dims
1663
            transform = ccrs.PlateCarree()
×
1664

1665
    # setup fig, ax
1666
    if ax is None and ("row" not in plot_kw.keys() and "col" not in plot_kw.keys()):
×
1667
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
1668
    elif ax is not None and ("col" in plot_kw or "row" in plot_kw):
×
1669
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
1670
    elif ax is None:
×
1671
        plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1672
        cfig_kw = fig_kw.copy()
×
1673
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
1674
            plot_kw.setdefault("figsize", fig_kw["figsize"])
×
1675
            cfig_kw.pop("figsize")
×
1676
        if len(cfig_kw) >= 1:
×
1677
            plot_kw = {"subplot_kws": {"projection": projection}} | plot_kw
×
1678
            warnings.warn(
×
1679
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid.", stacklevel=2
1680
            )
1681

1682
    # create cbar label
1683
    if (
×
1684
        "cbar_units" in use_attrs
1685
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1686
    ):  # avoids '[]' as label
1687
        cbar_label = (
×
1688
            get_attributes(use_attrs["cbar_label"], data)
1689
            + " ("
1690
            + get_attributes(use_attrs["cbar_units"], data)
1691
            + ")"
1692
        )
1693
    else:
1694
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1695

1696
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
1697
        plot_kw.setdefault("cbar_kwargs", {})
×
1698
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
1699
        plot_kw["cbar_kwargs"].setdefault("pad", 0.015)
×
1700

1701
    # colormap
1702
    if cmap is None:
×
1703
        cmap = get_ipcc_cmap_name(
×
1704
            get_var_group(da=plot_data),
1705
            divergent=divergent,
1706
        )
1707

1708
    # nans (not required for plotting since xarray.plot handles np.nan, but needs to be found for sizes legend and to
1709
    # inform user on how many stations were dropped)
1710
    mask = ~np.isnan(plot_data.values)
×
1711
    if np.sum(mask) < len(mask):
×
1712
        warnings.warn(
×
1713
            f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the color values", stacklevel=2
1714
        )
1715

1716
    # point sizes
1717
    if sizes:
×
1718
        if sizes is True:
×
1719
            sdata = plot_data
×
1720
        elif isinstance(sizes, str):
×
1721
            if hasattr(data, "name") and data.name == sizes:
×
1722
                sdata = plot_data
×
1723
            elif sizes in list(data.coords.keys()):
×
1724
                sdata = plot_data[sizes]
×
1725
            else:
1726
                raise ValueError(f"{sizes} not found")
×
1727
        else:
1728
            raise TypeError("sizes must be a string or a bool")
×
1729

1730
        # nans sizes
1731
        smask = ~np.isnan(sdata.values) & mask
×
1732
        if np.sum(smask) < np.sum(mask):
×
1733
            warnings.warn(
×
1734
                f"{np.sum(mask) - np.sum(smask)} nan values were dropped when setting the point size", stacklevel=2
1735
            )
1736
            mask = smask
×
1737

1738
        pt_sizes = norm2range(
×
1739
            data=sdata.where(mask).values,
1740
            target_range=size_range,
1741
            data_range=None,
1742
        )
1743
        plot_kw.setdefault("add_legend", False)
×
1744
        if ax:
×
1745
            plot_kw.setdefault("s", pt_sizes)
×
1746
        else:
1747
            plot_kw.setdefault("s", pt_sizes[0])
×
1748

1749
    # norm
1750
    plot_kw.setdefault("vmin", np.nanmin(plot_data.values[mask]))
×
1751
    plot_kw.setdefault("vmax", np.nanmax(plot_data.values[mask]))
×
1752
    if levels is not None:
×
1753
        if isinstance(levels, Iterable):
×
1754
            lin = levels
×
1755
        else:
1756
            lin = custom_cmap_norm(
×
1757
                cmap,
1758
                np.nanmin(plot_data.values[mask]),
1759
                np.nanmax(plot_data.values[mask]),
1760
                levels=levels,
1761
                divergent=divergent,
1762
                linspace_out=True,
1763
            )
1764
        plot_kw.setdefault("levels", lin)
×
1765

1766
    elif (divergent is not False) and ("levels" not in plot_kw):
×
1767
        vmin = plot_kw.pop("vmin", np.nanmin(plot_data.values[mask]))
×
1768
        vmax = plot_kw.pop("vmax", np.nanmax(plot_data.values[mask]))
×
1769
        norm = custom_cmap_norm(
×
1770
            cmap,
1771
            vmin,
1772
            vmax,
1773
            levels=levels,
1774
            divergent=divergent,
1775
        )
1776
        plot_kw.setdefault("norm", norm)
×
1777

1778
    # matplotlib.pyplot.scatter treats "edgecolor" and "edgecolors" as aliases so we accept "edgecolor" and convert it
1779
    if "edgecolor" in plot_kw and "edgecolors" not in plot_kw:
×
1780
        plot_kw["edgecolors"] = plot_kw["edgecolor"]
×
1781
        plot_kw.pop("edgecolor")
×
1782

1783
    # set defaults and create copy without vmin, vmax (conflicts with norm)
1784
    plot_kw = {
×
1785
        "cmap": cmap,
1786
        "transform": transform,
1787
        "zorder": 8,
1788
        "marker": "o",
1789
    } | plot_kw
1790

1791
    # check if edgecolors in plot_kw and match len of plot_data
1792
    if "edgecolors" in plot_kw:
×
1793
        if matplotlib.colors.is_color_like(plot_kw["edgecolors"]):
×
1794
            plot_kw["edgecolors"] = np.repeat(
×
1795
                plot_kw["edgecolors"], len(plot_data.where(mask).values)
1796
            )
1797
        elif len(plot_kw["edgecolors"]) != len(plot_data.values):
×
1798
            plot_kw["edgecolors"] = np.repeat(
×
1799
                plot_kw["edgecolors"][0], len(plot_data.where(mask).values)
1800
            )
1801
            warnings.warn(
×
1802
                "Length of edgecolors does not match length of data. Only first edgecolor is used for plotting.", stacklevel=2
1803
            )
1804
        else:
1805
            if isinstance(plot_kw["edgecolors"], list):
×
1806
                plot_kw["edgecolors"] = np.array(plot_kw["edgecolors"])
×
1807
            plot_kw["edgecolors"] = plot_kw["edgecolors"][mask]
×
1808
    else:
1809
        plot_kw.setdefault("edgecolors", "none")
×
1810

1811
    for key in ["vmin", "vmax"]:
×
1812
        plot_kw.pop(key, None)
×
1813
    # plot
1814
    plot_kw = {"x": "lon", "y": "lat", "hue": plot_data.name} | plot_kw
×
1815
    if ax:
×
1816
        plot_kw.setdefault("ax", ax)
×
1817

1818
    plot_data_masked = plot_data.where(mask).to_dataset()
×
1819
    im = plot_data_masked.plot.scatter(**plot_kw)
×
1820

1821
    # add features
1822
    if ax:
×
1823
        ax = add_features_map(
×
1824
            data,
1825
            ax,
1826
            use_attrs,
1827
            projection,
1828
            features,
1829
            geometries_kw,
1830
            frame,
1831
        )
1832

1833
        if show_time:
×
1834
            if isinstance(show_time, bool):
×
1835
                plot_coords(
×
1836
                    ax,
1837
                    plot_data,
1838
                    param="time",
1839
                    loc="lower right",
1840
                    backgroundalpha=1,
1841
                )
1842
            elif isinstance(show_time, str | tuple | int):
×
1843
                plot_coords(
×
1844
                    ax,
1845
                    plot_data,
1846
                    param="time",
1847
                    loc=show_time,
1848
                    backgroundalpha=1,
1849
                )
1850

1851
        if (frame is False) and (im.colorbar is not None):
×
1852
            im.colorbar.outline.set_visible(False)
×
1853

1854
    else:
1855
        for i, fax in enumerate(im.axs.flat):
×
1856
            fax = add_features_map(
×
1857
                data,
1858
                fax,
1859
                use_attrs,
1860
                projection,
1861
                features,
1862
                geometries_kw,
1863
                frame,
1864
            )
1865

1866
            if sizes:
×
1867
                # correct markersize for facetgrid
1868
                scat = fax.collections[0]
×
1869
                scat.set_sizes(pt_sizes[i])
×
1870

1871
        if (frame is False) and (im.cbar is not None):
×
1872
            im.cbar.outline.set_visible(False)
×
1873

1874
        if show_time:
×
1875
            if isinstance(show_time, bool):
×
1876
                plot_coords(
×
1877
                    None,
1878
                    plot_data,
1879
                    param="time",
1880
                    loc="lower right",
1881
                    backgroundalpha=1,
1882
                )
1883
            elif isinstance(show_time, str | tuple | int):
×
1884
                plot_coords(
×
1885
                    None,
1886
                    plot_data,
1887
                    param="time",
1888
                    loc=show_time,
1889
                    backgroundalpha=1,
1890
                )
1891

1892
    # size legend
1893
    if sizes:
×
1894
        legend_elements = size_legend_elements(
×
1895
            np.resize(sdata.values[mask], (sdata.values[mask].size, 1)),
1896
            np.resize(pt_sizes[mask], (pt_sizes[mask].size, 1)),
1897
            max_entries=6,
1898
            marker=plot_kw["marker"],
1899
        )
1900
        # legend spacing
1901
        if size_range[1] > 200:
×
1902
            ls = 0.5 + size_range[1] / 100 * 0.125
×
1903
        else:
1904
            ls = 0.5
×
1905

1906
        legend_kw = {
×
1907
            "loc": "lower left",
1908
            "facecolor": "w",
1909
            "framealpha": 1,
1910
            "edgecolor": "w",
1911
            "labelspacing": ls,
1912
            "handles": legend_elements,
1913
            "bbox_to_anchor": (-0.05, -0.1),
1914
        } | legend_kw
1915

1916
        if "title" not in legend_kw:
×
1917
            if hasattr(sdata, "long_name"):
×
1918
                lgd_title = wrap_text(
×
1919
                    sdata.long_name, min_line_len=1, max_line_len=15
1920
                )
1921
                if hasattr(sdata, "units"):
×
1922
                    lgd_title += f" ({sdata.units})"
×
1923
            else:
1924
                lgd_title = sizes
×
1925
            legend_kw.setdefault("title", lgd_title)
×
1926

1927
        if ax:
×
1928
            lgd = ax.legend(**legend_kw)
×
1929
            lgd.set_zorder(11)
×
1930
        else:
1931
            im.figlegend = im.fig.legend(**legend_kw)
×
1932
        # im._adjust_fig_for_guide(im.figlegend)
1933

1934
    if ax:
×
1935
        return ax
×
1936
    else:
1937
        im.fig.suptitle(get_attributes("long_name", data))
×
1938
        im.set_titles(template="{value}")
×
1939
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
1940
            for idx, ax in enumerate(im.axs.flat):
×
1941
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
1942

1943
        return im
×
1944

1945

1946
def taylordiagram(
7✔
1947
    data: xr.DataArray | dict[str, xr.DataArray],
1948
    plot_kw: dict[str, Any] | None = None,
1949
    fig_kw: dict[str, Any] | None = None,
1950
    std_range: tuple = (0, 1.5),
1951
    contours: int | None = 4,
1952
    contours_kw: dict[str, Any] | None = None,
1953
    ref_std_line: bool = False,
1954
    legend_kw: dict[str, Any] | None = None,
1955
    std_label: str | None = None,
1956
    corr_label: str | None = None,
1957
    colors_key: str | None = None,
1958
    markers_key: str | None = None,
1959
):
1960
    """
1961
    Build a Taylor diagram.
1962

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

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

1996
    Returns
1997
    -------
1998
    (plt.figure, mpl_toolkits.axisartist.floating_axes.FloatingSubplot, plt.legend)
1999
    """
2000
    plot_kw = empty_dict(plot_kw)
×
2001
    fig_kw = empty_dict(fig_kw)
×
2002
    contours_kw = empty_dict(contours_kw)
×
2003
    legend_kw = empty_dict(legend_kw)
×
2004

2005
    # preserve order of dimensions if used for marker/color
2006
    ordered_markers_type = None
×
2007
    ordered_colors_type = None
×
2008

2009
    # convert SSP, RCP, CMIP formats in keys
2010
    if isinstance(data, dict):
×
2011
        data = process_keys(data, convert_scen_name)
×
2012
    if isinstance(plot_kw, dict):
×
2013
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
2014

2015
    # if only one data input, insert in dict.
2016
    if not isinstance(data, dict):
×
2017
        data = {"_no_label": data}  # mpl excludes labels starting with "_" from legend
×
2018
        plot_kw = {"_no_label": empty_dict(plot_kw)}
×
2019
    elif not plot_kw:
×
2020
        plot_kw = {k: {} for k in data.keys()}
×
2021
    # check type
2022
    for key, v in data.items():
×
2023
        if not isinstance(v, xr.DataArray):
×
2024
            raise TypeError("All objects in 'data' must be xarray DataArrays.")
×
2025
        if "taylor_param" not in v.dims:
×
2026
            raise ValueError("All DataArrays must contain a 'taylor_param' dimension.")
×
2027
        if key == "reference":
×
2028
            raise ValueError("'reference' is not allowed as a key in data.")
×
2029

2030
    # If there are other dimensions than 'taylor_param', create a bigger dict with them
2031
    data_keys = list(data.keys())
×
2032
    for data_key in data_keys:
×
2033
        da = data[data_key]
×
2034
        dims = list(set(da.dims) - {"taylor_param"})
×
2035
        if dims != []:
×
2036
            if markers_key in dims:
×
2037
                ordered_markers_type = da[markers_key].values
×
2038
            if colors_key in dims:
×
2039
                ordered_colors_type = da[colors_key].values
×
2040

2041
            da = da.stack(pl_dims=dims)
×
2042
            for i, dim_key in enumerate(da.pl_dims.values):
×
2043
                if isinstance(dim_key, list) or isinstance(dim_key, tuple):
×
2044
                    dim_key = "-".join([str(k) for k in dim_key])
×
2045
                da0 = da.isel(pl_dims=i)
×
2046
                # if colors_key/markers_key is a dimension, add it as an attribute for later use
2047
                if markers_key in dims:
×
2048
                    da0.attrs[markers_key] = da0[markers_key].values.item()
×
2049
                if colors_key in dims:
×
2050
                    da0.attrs[colors_key] = da0[colors_key].values.item()
×
2051
                new_data_key = (
×
2052
                    f"{data_key}-{dim_key}" if data_key != "_no_label" else dim_key
2053
                )
2054
                data[new_data_key] = da0
×
2055
                plot_kw[new_data_key] = empty_dict(plot_kw[f"{data_key}"])
×
2056
            data.pop(data_key)
×
2057
            plot_kw.pop(data_key)
×
2058

2059
    # remove negative correlations
2060
    initial_len = len(data)
×
2061
    removed = [
×
2062
        key for key, da in data.items() if da.sel(taylor_param="corr").values < 0
2063
    ]
2064
    data = {
×
2065
        key: da for key, da in data.items() if da.sel(taylor_param="corr").values >= 0
2066
    }
2067
    if len(data) != initial_len:
×
2068
        warnings.warn(
×
2069
            f"{initial_len - len(data)} points with negative correlations will not be plotted: {', '.join(removed)}", stacklevel=2
2070
        )
2071

2072
    # add missing keys to plot_kw
2073
    for key in data.keys():
×
2074
        if key not in plot_kw:
×
2075
            plot_kw[key] = {}
×
2076

2077
    # extract ref to be used in plot
2078
    ref_std = list(data.values())[0].sel(taylor_param="ref_std").values
×
2079
    # check if ref is the same in all DataArrays and get the highest std (for ax limits)
2080
    if len(data) > 1:
×
2081
        for da in data.values():
×
2082
            if da.sel(taylor_param="ref_std").values != ref_std:
×
2083
                raise ValueError(
×
2084
                    "All reference standard deviation values must be identical"
2085
                )
2086

2087
    # get highest std for axis limits
2088
    max_std = [ref_std]
×
2089
    for da in data.values():
×
2090
        max_std.extend(
×
2091
            [
2092
                max(
2093
                    da.sel(taylor_param="ref_std").values,
2094
                    da.sel(taylor_param="sim_std").values,
2095
                ).astype(float)
2096
            ]
2097
        )
2098

2099
    # make labels
2100
    if not std_label:
×
2101
        try:
×
2102
            units = list(data.values())[0].units
×
2103
            std_label = get_localized_term("standard deviation")
×
2104
            std_label = std_label if units == "" else f"{std_label} ({units})"
×
2105
        except AttributeError:
×
2106
            std_label = get_localized_term("standard deviation").capitalize()
×
2107

2108
    if not corr_label:
×
2109
        try:
×
2110
            if "Pearson" in list(data.values())[0].correlation_type:
×
2111
                corr_label = get_localized_term("pearson correlation").capitalize()
×
2112
            else:
2113
                corr_label = get_localized_term("correlation").capitalize()
×
2114
        except AttributeError:
×
2115
            corr_label = get_localized_term("correlation").capitalize()
×
2116

2117
    # build diagram
2118
    transform = PolarAxes.PolarTransform()
×
2119

2120
    # Setup the axis, here we map angles in degrees to angles in radius
2121
    # Correlation labels
2122
    rlocs = np.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
×
2123
    tlocs = np.arccos(rlocs)  # Conversion to polar angles
×
2124
    gl1 = gf.FixedLocator(tlocs)  # Positions
×
2125
    tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, rlocs), strict=False)))
×
2126
    # Standard deviation axis extent
2127
    radius_min = std_range[0] * max(max_std)
×
2128
    radius_max = std_range[1] * max(max_std)
×
2129

2130
    # Set up the axes range in the parameter "extremes"
2131
    ghelper = GridHelperCurveLinear(
×
2132
        transform,
2133
        extremes=(0, np.pi / 2, radius_min, radius_max),
2134
        grid_locator1=gl1,
2135
        tick_formatter1=tf1,
2136
    )
2137

2138
    fig = plt.figure(**fig_kw)
×
2139
    floating_ax = FloatingSubplot(fig, 111, grid_helper=ghelper)
×
2140
    fig.add_subplot(floating_ax)
×
2141

2142
    # Adjust axes
2143
    floating_ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
×
2144
    floating_ax.axis["top"].toggle(ticklabels=True, label=True)
×
2145
    floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
×
2146
    floating_ax.axis["top"].label.set_axis_direction("top")
×
2147
    floating_ax.axis["top"].label.set_text(corr_label)
×
2148

2149
    floating_ax.axis["left"].set_axis_direction("bottom")  # "X axis"
×
2150
    floating_ax.axis["left"].label.set_text(std_label)
×
2151

2152
    floating_ax.axis["right"].set_axis_direction("top")  # "Y axis"
×
2153
    floating_ax.axis["right"].toggle(ticklabels=True, label=True)
×
2154
    floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
×
2155
    floating_ax.axis["right"].label.set_text(std_label)
×
2156

2157
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2158

2159
    # Contours along standard deviations
2160
    floating_ax.grid(visible=True, alpha=0.4)
×
2161
    floating_ax.set_title("")
×
2162

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

2165
    # plot reference
2166
    if "reference" in plot_kw:
×
2167
        ref_kw = plot_kw.pop("reference")
×
2168
    else:
2169
        ref_kw = {}
×
2170
    ref_kw = {
×
2171
        "color": "#154504",
2172
        "marker": "s",
2173
        "label": get_localized_term("reference"),
2174
    } | ref_kw
2175

2176
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2177

2178
    points = [ref_pt]  # set up for later
×
2179

2180
    # plot a circular line along `ref_std`
2181
    if ref_std_line:
×
2182
        angles_for_line = np.linspace(0, np.pi / 2, 100)
×
2183
        radii_for_line = np.full_like(angles_for_line, ref_std)
×
2184
        ax.plot(
×
2185
            angles_for_line,
2186
            radii_for_line,
2187
            color=ref_kw["color"],
2188
            linewidth=0.5,
2189
            linestyle="-",
2190
        )
2191

2192
    # rmse contours from reference standard deviation
2193
    if contours:
×
2194
        radii, angles = np.meshgrid(
×
2195
            np.linspace(radius_min, radius_max),
2196
            np.linspace(0, np.pi / 2),
2197
        )
2198
        # Compute centered RMS difference
2199
        rms = np.sqrt(ref_std**2 + radii**2 - 2 * ref_std * radii * np.cos(angles))
×
2200

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

2204
        ax.clabel(ct, ct.levels, fontsize=8)
×
2205

2206
        # points.append(ct_line)
2207
        ct_line = ax.plot(
×
2208
            [0],
2209
            [0],
2210
            ls=contours_kw["linestyles"],
2211
            lw=1,
2212
            c="k" if "colors" not in contours_kw else contours_kw["colors"],
2213
            label="rmse",
2214
        )
2215
        points.append(ct_line[0])
×
2216

2217
    # get color options
2218
    style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
2219
    if len(data) > len(style_colors):
×
2220
        style_colors = style_colors * math.ceil(len(data) / len(style_colors))
×
2221
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
2222
    # get marker options (only used if `markers_key` is set)
2223
    style_markers = "oDv^<>p*hH+x|_"
×
2224
    if len(data) > len(style_markers):
×
2225
        style_markers = style_markers * math.ceil(len(data) / len(style_markers))
×
2226

2227
    # set colors and markers styles based on discrimnating attributes (if specified)
2228
    if colors_key or markers_key:
×
2229
        if colors_key:
×
2230
            # get_scen_color : look for SSP, RCP, CMIP model color
2231
            colors_type = (
×
2232
                ordered_colors_type
2233
                if ordered_colors_type is not None
2234
                else {da.attrs[colors_key] for da in data.values()}
2235
            )
2236
            colorsd = {
×
2237
                k: get_scen_color(k, cat_colors) or style_colors[i]
2238
                for i, k in enumerate(colors_type)
2239
            }
2240
        if markers_key:
×
2241
            markers_type = (
×
2242
                ordered_markers_type
2243
                if ordered_markers_type is not None
2244
                else {da.attrs[markers_key] for da in data.values()}
2245
            )
2246
            markersd = {k: style_markers[i] for i, k in enumerate(markers_type)}
×
2247

2248
        for key, da in data.items():
×
2249
            if colors_key:
×
2250
                plot_kw[key]["color"] = colorsd[da.attrs[colors_key]]
×
2251
            if markers_key:
×
2252
                plot_kw[key]["marker"] = markersd[da.attrs[markers_key]]
×
2253

2254
    # plot scatter
2255
    for (key, da), i in zip(data.items(), range(len(data)), strict=False):
×
2256
        # look for SSP, RCP, CMIP model color
2257
        if colors_key is None:
×
2258
            plot_kw[key].setdefault(
×
2259
                "color", get_scen_color(key, cat_colors) or style_colors[i]
2260
            )
2261
        # set defaults
2262
        plot_kw[key] = {"label": key} | plot_kw[key]
×
2263

2264
        # legend will be handled later in this case
2265
        if markers_key or colors_key:
×
2266
            plot_kw[key]["label"] = ""
×
2267

2268
        # plot
2269
        pt = ax.scatter(
×
2270
            np.arccos(da.sel(taylor_param="corr").values),
2271
            da.sel(taylor_param="sim_std").values,
2272
            **plot_kw[key],
2273
        )
2274
        points.append(pt)
×
2275

2276
    # legend
2277
    legend_kw.setdefault("loc", "upper right")
×
2278
    legend = fig.legend(points, [pt.get_label() for pt in points], **legend_kw)
×
2279

2280
    # plot new legend if markers/colors represent a certain dimension
2281
    if colors_key or markers_key:
×
2282
        handles = list(floating_ax.get_legend_handles_labels()[0])
×
2283
        if markers_key:
×
2284
            for k, m in markersd.items():
×
2285
                handles.append(Line2D([0], [0], color="k", label=k, marker=m, ls=""))
×
2286
        if colors_key:
×
2287
            for k, c in colorsd.items():
×
2288
                handles.append(Line2D([0], [0], color=c, label=k, ls="-"))
×
2289
        legend.remove()
×
2290
        legend = fig.legend(handles=handles, **legend_kw)
×
2291

2292
    return fig, floating_ax, legend
×
2293

2294

2295
def hatchmap(
7✔
2296
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
2297
    ax: matplotlib.axes.Axes | None = None,
2298
    use_attrs: dict[str, Any] | None = None,
2299
    fig_kw: dict[str, Any] | None = None,
2300
    plot_kw: dict[str, Any] | None = None,
2301
    projection: ccrs.Projection = ccrs.LambertConformal(),
2302
    transform: ccrs.Projection | None = None,
2303
    features: list[str] | dict[str, dict[str, Any]] | None = None,
2304
    geometries_kw: dict[str, Any] | None = None,
2305
    levels: int | None = None,
2306
    legend_kw: dict[str, Any] | bool = True,
2307
    show_time: bool | str | int | tuple[float, float] = False,
2308
    frame: bool = False,
2309
    enumerate_subplots: bool = False,
2310
) -> matplotlib.axes.Axes:
2311
    """
2312
    Create map of hatches from 2D data.
2313

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

2347
        ==================   =============
2348
        Location String      Location Code
2349
        ==================   =============
2350
        'upper right'        1
2351
        'upper left'         2
2352
        'lower left'         3
2353
        'lower right'        4
2354
        'right'              5
2355
        'center left'        6
2356
        'center right'       7
2357
        'lower center'       8
2358
        'upper center'       9
2359
        'center'             10
2360
        ==================   =============
2361
    frame : bool
2362
        Show or hide frame. Default False.
2363
    enumerate_subplots: bool
2364
        If True, enumerate subplots with letters.
2365
        Only works with facetgrids (pass `col` or `row` in plot_kw).
2366

2367
    Returns
2368
    -------
2369
    matplotlib.axes.Axes
2370
    """
2371
    # default hatches
2372
    dfh = [
×
2373
        "/",
2374
        "\\",
2375
        "|",
2376
        "-",
2377
        "+",
2378
        "x",
2379
        "o",
2380
        "O",
2381
        ".",
2382
        "*",
2383
        "//",
2384
        "\\\\",
2385
        "||",
2386
        "--",
2387
        "++",
2388
        "xx",
2389
        "oo",
2390
        "OO",
2391
        "..",
2392
        "**",
2393
    ]
2394

2395
    # create empty dicts if None
2396
    use_attrs = empty_dict(use_attrs)
×
2397
    fig_kw = empty_dict(fig_kw)
×
2398
    plot_kw = empty_dict(plot_kw)
×
2399
    legend_kw = empty_dict(legend_kw)
×
2400

2401
    dattrs = None
×
2402
    plot_data = {}
×
2403

2404
    # convert data to dict (if not one)
2405
    if not isinstance(data, dict):
×
2406
        if isinstance(data, xr.DataArray):
×
2407
            plot_data = {data.name: data}
×
2408
            if data.name not in plot_kw.keys():
×
2409
                plot_kw = {data.name: plot_kw}
×
2410
        elif isinstance(data, xr.Dataset):
×
2411
            dattrs = data
×
2412
            plot_data = {var: data[var] for var in data.data_vars}
×
2413
            for v in plot_data.keys():
×
2414
                if v not in plot_kw.keys():
×
2415
                    plot_kw[v] = plot_kw
×
2416
    else:
2417
        for k, v in data.items():
×
2418
            if isinstance(v, xr.Dataset):
×
2419
                dattrs = k
×
2420
                plot_data[k] = v[list(v.data_vars)[0]]
×
2421
                warnings.warn("Only first variable of Dataset is plotted.", stacklevel=2)
×
2422
            else:
2423
                plot_data[k] = v
×
2424

2425
    # if plot_kw doesn't have any of the same key as data,
2426
    # put plot_kw as a nested dict with the same keys as data
2427
    if not any(k in plot_kw for k in plot_data.keys()):
×
2428
        plot_kw = {k: plot_kw for k in plot_data.keys()}
×
2429
    # if plot_kw is only missing some keys, fill them with empty dicts
2430
    for k in plot_data.keys():
×
2431
        if k not in plot_kw:
×
2432
            plot_kw[k] = {}
×
2433

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

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

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

2464
    else:
2465
        extent = None
×
2466

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

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

2513
            plot_kw[k] = {
×
2514
                "hatches": hatches,
2515
                "colors": "none",
2516
                "add_colorbar": False,
2517
            } | plot_kw[k]
2518

2519
            if "lat" in v.dims:
×
2520
                v.coords["mask"] = (("lat", "lon"), mask)
×
2521
            else:
2522
                v.coords["mask"] = (("rlat", "rlon"), mask)
×
2523

2524
            plot_kw[k].setdefault("transform", transform)
×
2525
            if ax:
×
2526
                plot_kw[k].setdefault("ax", ax)
×
2527

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

2531
            if ax and legend_kw:
×
2532
                ax.legend(artists, labels, **legend_kw)
×
2533
            elif legend_kw:
×
2534
                im.figlegend = im.fig.legend(**legend_kw)
×
2535

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

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

2555
            plot_kw[k].setdefault("transform", transform)
×
2556
            if ax:
×
2557
                im = v.plot.contourf(ax=ax, **plot_kw[k])
×
2558

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

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

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

2599
            pat_leg.append(
×
2600
                matplotlib.patches.Patch(
2601
                    hatch=plot_kw[k]["hatches"][0], fill=False, label=k
2602
                )
2603
            )
2604

2605
    if pat_leg and legend_kw:
×
2606
        legend_kw = {
×
2607
            "loc": "lower right",
2608
            "handleheight": 2,
2609
            "handlelength": 4,
2610
        } | legend_kw
2611

2612
        if ax and legend_kw:
×
2613
            ax.legend(handles=pat_leg, **legend_kw)
×
2614
        elif legend_kw:
×
2615
            im.figlegend = im.fig.legend(handles=pat_leg, **legend_kw)
×
2616

2617
    # add features
2618
    if ax:
×
2619
        if extent:
×
2620
            ax.set_extent(extent)
×
2621
        if dattrs:
×
2622
            use_attrs.setdefault("title", "description")
×
2623

2624
        ax = add_features_map(
×
2625
            dattrs,
2626
            ax,
2627
            use_attrs,
2628
            projection,
2629
            features,
2630
            geometries_kw,
2631
            frame,
2632
        )
2633

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

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

2659
            set_plot_attrs(use_attrs, dattrs, ax, wrap_kw={"max_line_len": 60})
×
2660
        return ax
×
2661

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

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

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

2691
        return im
×
2692

2693

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

2701

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

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

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

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

2753
    if data.attrs["units"] != "%":
×
2754
        raise ValueError(
×
2755
            "The units are not %. Use `fraction=True` in the xclim function call."
2756
        )
2757

2758
    fill_kw = empty_dict(fill_kw)
×
2759
    line_kw = empty_dict(line_kw)
×
2760
    fig_kw = empty_dict(fig_kw)
×
2761
    legend_kw = empty_dict(legend_kw)
×
2762

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

2775
    if ax is None:
×
2776
        fig, ax = plt.subplots(**fig_kw)
×
2777

2778
    # Select data from reference year onward
2779
    if start_year:
×
2780
        data = data.sel(time=slice(start_year, None))
×
2781

2782
        # Lead time coordinate
2783
        time = _add_lead_time_coord(data, start_year)
×
2784
        ax.set_xlabel(f"Lead time (years from {start_year})")
×
2785
    else:
2786
        time = data.time.dt.year
×
2787

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

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

2816
    # Draw black lines
2817
    line_kw.setdefault("color", "k")
×
2818
    line_kw.setdefault("lw", 2)
×
2819
    ax.plot(time, np.array(black_lines).T, **line_kw)
×
2820

2821
    ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(20))
×
2822
    ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=5))
×
2823

2824
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))
×
2825
    ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=2))
×
2826

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

2829
    ax.set_ylim(0, 100)
×
2830
    ax.legend(**legend_kw)
×
2831

2832
    return ax
×
2833

2834

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

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

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

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

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

2907
    # setup fig, axis
2908
    if ax is None:
×
2909
        fig, ax = plt.subplots(**fig_kw)
×
2910

2911
    # colormap
2912
    if cmap is None:
×
2913
        cmap = get_ipcc_cmap_name(
×
2914
            get_var_group(da=da),
2915
            divergent=divergent,
2916
        )
2917

2918
    # prep data
2919
    d = [da.sel(**{z: v}).values for v in da[z].values]
×
2920

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

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

2939
    if isinstance(plot_kw, dict):
×
2940
        plot_kw.setdefault("cmap", cmap)
×
2941
        plot_kw.setdefault("ec", "white")
×
2942
        plot_kw = [plot_kw for _ in range(len(d))]
×
2943

2944
    labels_x = da[other_dims[0]].values
×
2945
    labels_y = da[other_dims[1]].values
×
2946
    m, n = d[0].shape[0], d[0].shape[1]
×
2947

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

2972
        imgs = [
×
2973
            ax.tripcolor(t, np.ravel(val), **plotkw)
2974
            for t, val, plotkw in zip(triangul, d, plot_kw, strict=False)
2975
        ]
2976

2977
        ax.set_xticks(np.array(range(m)) + 0.5, labels=labels_x, rotation=45)
×
2978
        ax.set_yticks(np.array(range(n)) + 0.5, labels=labels_y, rotation=90)
×
2979

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc