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

Ouranosinc / figanos / 30944767640

04 Aug 2026 07:45PM UTC coverage: 9.186%. First build
30944767640

Pull #416

github

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

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

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

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

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

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

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

1458
    plot_kw.setdefault("cmap", cmap)
×
1459

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

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

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

1514

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1941
        return im
×
1942

1943

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2115
    # build diagram
2116
    transform = PolarAxes.PolarTransform()
×
2117

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

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

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

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

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

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

2155
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2156

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

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

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

2174
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2175

2176
    points = [ref_pt]  # set up for later
×
2177

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

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

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

2202
        ax.clabel(ct, ct.levels, fontsize=8)
×
2203

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

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

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

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

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

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

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

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

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

2290
    return fig, floating_ax, legend
×
2291

2292

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

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

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

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

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

2399
    dattrs = None
×
2400
    plot_data = {}
×
2401

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

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

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

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

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

2462
    else:
2463
        extent = None
×
2464

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2689
        return im
×
2690

2691

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

2699

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

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

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

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

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

2756
    fill_kw = empty_dict(fill_kw)
×
2757
    line_kw = empty_dict(line_kw)
×
2758
    fig_kw = empty_dict(fig_kw)
×
2759
    legend_kw = empty_dict(legend_kw)
×
2760

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

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

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

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

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

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

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

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

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

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

2827
    ax.set_ylim(0, 100)
×
2828
    ax.legend(**legend_kw)
×
2829

2830
    return ax
×
2831

2832

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3075
    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