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

Ouranosinc / figanos / 16052439588

03 Jul 2025 01:57PM UTC coverage: 8.147% (-0.02%) from 8.164%
16052439588

push

github

web-flow
use vmin and vmax with divergent (#342)

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

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

* If vmax and vmin are given, use them in creating the colormap (with
divergent) instead of using the max and min of the data.

### Does this PR introduce a breaking change?
yes. This used to fail.

### Other information:

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

2 existing lines in 1 file now uncovered.

157 of 1927 relevant lines covered (8.15%)

0.41 hits per line

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

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

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

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

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

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

61

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

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

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

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

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

108
    return ax
×
109

110

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

263

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

527
        return im
×
528

529

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

858
        return im
×
859

860

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

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

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

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

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

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

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

936
    # add features
937
    if features:
×
938
        add_cartopy_features(ax, features)
×
939

940
    if df_col == "boundary":
×
941
        plot = df.boundary.plot(ax=ax, **plot_kw)
×
942
        if cmap is not None or levels is not None or divergent is not False:
×
943
            warnings.warn("Colomap arguments are ignored when plotting 'boundary'.")
×
944
    else:
945

946
        # colormap
947
        if isinstance(cmap, str):
×
948
            if cmap in plt.colormaps():
×
949
                cmap = matplotlib.colormaps[cmap]
×
950
            else:
951
                try:
×
952
                    cmap = create_cmap(filename=cmap)
×
953
                except FileNotFoundError:
×
954
                    warnings.warn("invalid cmap, using default")
×
955
                    cmap = create_cmap(filename="slev_seq")
×
956

957
        elif cmap is None:
×
958
            cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
959
            cmap = create_cmap(
×
960
                get_var_group(unique_str=df_col, path_to_json=cdata),
961
                divergent=divergent,
962
            )
963

964
        # create normalization for colormap
965
        plot_kw.setdefault("vmin", df[df_col].min())
×
966
        plot_kw.setdefault("vmax", df[df_col].max())
×
967

968
        if (levels is not None) or (divergent is not False):
×
969
            norm = custom_cmap_norm(
×
970
                cmap,
971
                plot_kw["vmin"],
972
                plot_kw["vmax"],
973
                levels=levels,
974
                divergent=divergent,
975
            )
976
            plot_kw.setdefault("norm", norm)
×
977

978
        # colorbar
979
        if cbar:
×
980
            plot_kw.setdefault("legend", True)
×
981
            plot_kw.setdefault("legend_kwds", {})
×
982
            plot_kw["legend_kwds"].setdefault("label", df_col)
×
983
            plot_kw["legend_kwds"].setdefault("orientation", "horizontal")
×
984
            plot_kw["legend_kwds"].setdefault("pad", 0.02)
×
985

986
        # plot
987
        plot = df.plot(column=df_col, ax=ax, cmap=cmap, **plot_kw)
×
988

989
    if frame is False:
×
990
        # cbar
991
        if len(plot.figure.axes) > 1:  # only if it exists
×
992
            plot.figure.axes[1].spines["outline"].set_visible(False)
×
993
            plot.figure.axes[1].tick_params(size=0)
×
994
        # main axes
995
        ax.spines["geo"].set_visible(False)
×
996

997
    return ax
×
998

999

1000
def violin(
5✔
1001
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1002
    ax: matplotlib.axes.Axes | None = None,
1003
    use_attrs: dict[str, Any] | None = None,
1004
    fig_kw: dict[str, Any] | None = None,
1005
    plot_kw: dict[str, Any] | None = None,
1006
    color: str | int | list[str | int] | None = None,
1007
) -> matplotlib.axes.Axes:
1008
    """Make violin plot using seaborn.
1009

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

1028
    Returns
1029
    -------
1030
    matplotlib.axes.Axes
1031
    """
1032
    # create empty dicts if None
1033
    use_attrs = empty_dict(use_attrs)
×
1034
    fig_kw = empty_dict(fig_kw)
×
1035
    plot_kw = empty_dict(plot_kw)
×
1036

1037
    # if data is dict, assemble into one DataFrame
1038
    non_dict_data = True
×
1039
    if isinstance(data, dict):
×
1040
        non_dict_data = False
×
1041
        df = pd.DataFrame()
×
1042
        for key, xr_obj in data.items():
×
1043
            if isinstance(xr_obj, xr.Dataset):
×
1044
                # if one data var, use key
1045
                if len(list(xr_obj.data_vars)) == 1:
×
1046
                    df[key] = xr_obj[list(xr_obj.data_vars)[0]].values
×
1047
                # if more than one data var, use key + name of var
1048
                else:
1049
                    for data_var in list(xr_obj.data_vars):
×
1050
                        df[key + "_" + data_var] = xr_obj[data_var].values
×
1051

1052
            elif isinstance(xr_obj, xr.DataArray):
×
1053
                df[key] = xr_obj.values
×
1054

1055
            else:
1056
                raise TypeError(
×
1057
                    '"data" must be a xr.Dataset, a xr.DataArray or a dictionary of such objects.'
1058
                )
1059

1060
    elif isinstance(data, xr.Dataset):
×
1061
        # create dataframe
1062
        df = data.to_dataframe()
×
1063
        df = df[data.data_vars]
×
1064

1065
    elif isinstance(data, xr.DataArray):
×
1066
        # create dataframe
1067
        df = data.to_dataframe()
×
1068
        for coord in list(data.coords):
×
1069
            if coord in df.columns:
×
1070
                df = df.drop(columns=coord)
×
1071

1072
    else:
1073
        raise TypeError(
×
1074
            '"data" must be a xr.Dataset, a xr.DataArray or a dictionary of such objects.'
1075
        )
1076

1077
    # set fig, ax if not provided
1078
    if ax is None:
×
1079
        fig, ax = plt.subplots(**fig_kw)
×
1080

1081
    # set default use_attrs values
1082
    if "orient" in plot_kw and plot_kw["orient"] == "h":
×
1083
        use_attrs = {"xlabel": "long_name", "xunits": "units"} | use_attrs
×
1084
    else:
1085
        use_attrs = {"ylabel": "long_name", "yunits": "units"} | use_attrs
×
1086

1087
    #  add/modify plot elements according to the first entry.
1088
    if non_dict_data:
×
1089
        set_plot_obj = data
×
1090
    else:
1091
        set_plot_obj = list(data.values())[0]
×
1092

1093
    set_plot_attrs(
×
1094
        use_attrs,
1095
        xr_obj=set_plot_obj,
1096
        ax=ax,
1097
        title_loc="left",
1098
        wrap_kw={"min_line_len": 35, "max_line_len": 48},
1099
    )
1100

1101
    # color
1102
    if color:
×
1103
        style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
1104
        if isinstance(color, str):
×
1105
            plot_kw.setdefault("color", color)
×
1106
        elif isinstance(color, int):
×
1107
            try:
×
1108
                plot_kw.setdefault("color", style_colors[color])
×
1109
            except IndexError:
×
1110
                raise IndexError("Index out of range of stylesheet colors")
×
1111
        elif isinstance(color, list):
×
1112
            for c, i in zip(color, np.arange(len(color))):
×
1113
                if isinstance(c, int):
×
1114
                    try:
×
1115
                        color[i] = style_colors[c]
×
1116
                    except IndexError:
×
1117
                        raise IndexError("Index out of range of stylesheet colors")
×
1118
            plot_kw.setdefault("palette", color)
×
1119

1120
    # plot
1121
    sns.violinplot(df, ax=ax, **plot_kw)
×
1122

1123
    # grid
1124
    if "orient" in plot_kw and plot_kw["orient"] == "h":
×
1125
        ax.grid(visible=True, axis="x")
×
1126

1127
    return ax
×
1128

1129

1130
def stripes(
5✔
1131
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1132
    ax: matplotlib.axes.Axes | None = None,
1133
    fig_kw: dict[str, Any] | None = None,
1134
    divide: int | None = None,
1135
    cmap: str | matplotlib.colors.Colormap | None = None,
1136
    cmap_center: int | float = 0,
1137
    cbar: bool = True,
1138
    cbar_kw: dict[str, Any] | None = None,
1139
) -> matplotlib.axes.Axes:
1140
    """Create stripes plot with or without multiple scenarios.
1141

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

1165
    Returns
1166
    -------
1167
    matplotlib.axes.Axes
1168
    """
1169
    # create empty dicts if None
1170
    fig_kw = empty_dict(fig_kw)
×
1171
    cbar_kw = empty_dict(cbar_kw)
×
1172

1173
    # init main (figure) axis
1174
    if ax is None:
×
1175
        fig_kw.setdefault("figsize", (10, 5))
×
1176
        fig, ax = plt.subplots(**fig_kw)
×
1177
    ax.set_yticks([])
×
1178
    ax.set_xticks([])
×
1179
    ax.spines[["top", "bottom", "left", "right"]].set_visible(False)
×
1180

1181
    # init plot axis
1182
    ax_0 = ax.inset_axes([0, 0.15, 1, 0.75])
×
1183

1184
    # handle non-dict data
1185
    if not isinstance(data, dict):
×
1186
        data = {"_no_label": data}
×
1187

1188
    # convert SSP, RCP, CMIP formats in keys
1189
    data = process_keys(data, convert_scen_name)
×
1190

1191
    n = len(data)
×
1192

1193
    # extract DataArrays from datasets
1194
    for key, obj in data.items():
×
1195
        if isinstance(obj, xr.DataArray):
×
1196
            pass
×
1197
        elif isinstance(obj, xr.Dataset):
×
1198
            data[key] = obj[list(obj.data_vars)[0]]
×
1199
        else:
1200
            raise TypeError("data must contain xarray DataArrays or Datasets")
×
1201

1202
    # get time interval
1203
    time_index = list(data.values())[0].time.dt.year.values
×
1204
    delta_time = [
×
1205
        time_index[i] - time_index[i - 1] for i in np.arange(1, len(time_index), 1)
1206
    ]
1207

1208
    if all(i == delta_time[0] for i in delta_time):
×
1209
        dtime = delta_time[0]
×
1210
    else:
1211
        raise ValueError("Time delta between each array element must be constant")
×
1212

1213
    # modify axes
1214
    ax.set_xlim(min(time_index) - 0.5 * dtime, max(time_index) + 0.5 * dtime)
×
1215
    ax_0.set_xlim(min(time_index) - 0.5 * dtime, max(time_index) + 0.5 * dtime)
×
1216
    ax_0.set_ylim(0, 1)
×
1217
    ax_0.set_yticks([])
×
1218
    ax_0.xaxis.set_ticks_position("top")
×
1219
    ax_0.tick_params(axis="x", direction="out", zorder=10)
×
1220
    ax_0.spines[["top", "left", "right", "bottom"]].set_visible(False)
×
1221

1222
    # width of bars, to fill x axis limits
1223
    width = (max(time_index) + 0.5 - min(time_index) - 0.5) / len(time_index)
×
1224

1225
    # create historical/projection divide
1226
    if divide is not None:
×
1227
        # convert divide year to transAxes
1228
        divide_disp = ax_0.transData.transform(
×
1229
            (divide - width * 0.5, 1)
1230
        )  # left limit of stripe, 1 is placeholder
1231
        divide_ax = ax_0.transAxes.inverted().transform(divide_disp)
×
1232
        divide_ax = divide_ax[0]
×
1233
    else:
1234
        divide_ax = 0
×
1235

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

1265
    # get max and min of all data
1266
    data_min = 1e6
×
1267
    data_max = -1e6
×
1268
    for da in data.values():
×
1269
        if min(da.values) < data_min:
×
1270
            data_min = min(da.values)
×
1271
        if max(da.values) > data_max:
×
1272
            data_max = max(da.values)
×
1273

1274
    # colormap
1275
    if isinstance(cmap, str):
×
1276
        if cmap in plt.colormaps():
×
1277
            cmap = matplotlib.colormaps[cmap]
×
1278
        else:
1279
            try:
×
1280
                cmap = create_cmap(filename=cmap)
×
1281
            except FileNotFoundError as e:
×
1282
                logger.error(e)
×
1283
                pass
×
1284

1285
    elif cmap is None:
×
1286
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1287
        cmap = create_cmap(
×
1288
            get_var_group(path_to_json=cdata, da=list(data.values())[0]),
1289
            divergent=True,
1290
        )
1291

1292
    # create cmap norm
1293
    if cmap_center is not None:
×
1294
        norm = matplotlib.colors.TwoSlopeNorm(cmap_center, vmin=data_min, vmax=data_max)
×
1295
    else:
1296
        norm = matplotlib.colors.Normalize(data_min, data_max)
×
1297

1298
    # plot
1299
    for (name, subax), (key, da) in zip(subaxes.items(), data.items()):
×
1300
        subax.bar(da.time.dt.year, height=1, width=dtime, color=cmap(norm(da.values)))
×
1301
        if divide:
×
1302
            if key != "_no_label":
×
1303
                subax.text(
×
1304
                    0.99,
1305
                    0.5,
1306
                    key,
1307
                    transform=subax.transAxes,
1308
                    fontsize=14,
1309
                    ha="right",
1310
                    va="center",
1311
                    c="w",
1312
                    weight="bold",
1313
                )
1314

1315
    # colorbar
1316
    if cbar is True:
×
1317
        sm = ScalarMappable(cmap=cmap, norm=norm)
×
1318
        cax = ax.inset_axes([0.01, 0.05, 0.35, 0.06])
×
1319
        cbar_tcks = np.arange(math.floor(data_min), math.ceil(data_max), 2)
×
1320
        # label
1321
        da = list(data.values())[0]
×
1322
        label = get_attributes("long_name", da)
×
1323
        if label != "":
×
1324
            if "units" in da.attrs:
×
1325
                u = da.units
×
1326
                label += f" ({u})"
×
1327
            label = wrap_text(label, max_line_len=40)
×
1328

1329
        cbar_kw = {
×
1330
            "cax": cax,
1331
            "orientation": "horizontal",
1332
            "ticks": cbar_tcks,
1333
            "label": label,
1334
        } | cbar_kw
1335
        plt.colorbar(sm, **cbar_kw)
×
1336
        cax.spines["outline"].set_visible(False)
×
1337
        cax.set_xscale("linear")
×
1338

1339
    return ax
×
1340

1341

1342
def heatmap(
5✔
1343
    data: xr.DataArray | xr.Dataset | dict[str, Any],
1344
    ax: matplotlib.axes.Axes | None = None,
1345
    use_attrs: dict[str, Any] | None = None,
1346
    fig_kw: dict[str, Any] | None = None,
1347
    plot_kw: dict[str, Any] | None = None,
1348
    transpose: bool = False,
1349
    cmap: str | matplotlib.colors.Colormap | None = "RdBu",
1350
    divergent: bool | int | float = False,
1351
) -> matplotlib.axes.Axes:
1352
    """Create heatmap from a DataArray.
1353

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

1379
    Returns
1380
    -------
1381
    matplotlib.axes.Axes
1382
    """
1383
    # create empty dicts if None
1384
    use_attrs = empty_dict(use_attrs)
×
1385
    fig_kw = empty_dict(fig_kw)
×
1386
    plot_kw = empty_dict(plot_kw)
×
1387

1388
    # set default use_attrs values
1389
    use_attrs.setdefault("cbar_label", "long_name")
×
1390

1391
    # if data is dict, extract
1392
    if isinstance(data, dict):
×
1393
        if plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1394
            plot_kw = plot_kw[list(data.keys())[0]]
×
1395
        if len(data) == 1:
×
1396
            data = list(data.values())[0]
×
1397
        else:
1398
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1399

1400
    # select data to plot
1401
    if isinstance(data, xr.DataArray):
×
1402
        da = data
×
1403
    elif isinstance(data, xr.Dataset):
×
1404
        if len(data.data_vars) > 1:
×
1405
            warnings.warn(
×
1406
                "data is xr.Dataset; only the first variable will be used in plot"
1407
            )
1408
        da = list(data.values())[0]
×
1409
    else:
1410
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
1411

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

1433
    # create cbar label
1434
    if (
×
1435
        "cbar_units" in use_attrs
1436
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1437
    ):  # avoids '()' as label
1438
        cbar_label = (
×
1439
            get_attributes(use_attrs["cbar_label"], data)
1440
            + " ("
1441
            + get_attributes(use_attrs["cbar_units"], data)
1442
            + ")"
1443
        )
1444
    else:
1445
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1446

1447
    # colormap
1448
    if isinstance(cmap, str):
×
1449
        if cmap not in plt.colormaps():
×
1450
            try:
×
1451
                cmap = create_cmap(filename=cmap)
×
1452
            except FileNotFoundError as e:
×
1453
                logger.error(e)
×
1454
                pass
×
1455

1456
    elif cmap is None:
×
1457
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1458
        cmap = create_cmap(
×
1459
            get_var_group(path_to_json=cdata, da=da),
1460
            divergent=divergent,
1461
        )
1462

1463
    # convert data to DataFrame
1464
    if transpose:
×
1465
        da = da.transpose()
×
1466
    if "col" not in plot_kw and "row" not in plot_kw:
×
1467
        if len(da.dims) != 2:
×
1468
            raise ValueError("DataArray must have exactly two dimensions")
×
1469
        df = da.to_pandas()
×
1470
    else:
1471
        if len(heatmap_dims) != 2:
×
1472
            raise ValueError("DataArray must have exactly two dimensions")
×
1473
        df = da.to_dataframe().reset_index()
×
1474

1475
    # set defaults
1476
    if divergent is not False:
×
1477
        if isinstance(divergent, (int, float)):
×
1478
            plot_kw.setdefault("center", divergent)
×
1479
        else:
1480
            plot_kw.setdefault("center", 0)
×
1481

1482
    if "cbar" not in plot_kw or plot_kw["cbar"] is not False:
×
1483
        plot_kw.setdefault("cbar_kws", {})
×
1484
        plot_kw["cbar_kws"].setdefault("label", wrap_text(cbar_label))
×
1485

1486
    plot_kw.setdefault("cmap", cmap)
×
1487

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

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

1537
        g = sns.FacetGrid(df, **plot_kw_fg)
×
1538
        cax = g.fig.add_axes([0.95, 0.05, 0.02, 0.9])
×
1539
        g.map_dataframe(
×
1540
            draw_heatmap,
1541
            *heatmap_dims,
1542
            da_name,
1543
            **plot_kw_hm,
1544
            cbar=True,
1545
            cbar_ax=cax,
1546
        )
1547
        g.fig.subplots_adjust(right=0.9)
×
1548
        if "figsize" in fig_kw.keys():
×
1549
            g.fig.set_size_inches(*fig_kw["figsize"])
×
1550
        return g
×
1551

1552

1553
def scattermap(
5✔
1554
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
1555
    ax: matplotlib.axes.Axes | None = None,
1556
    use_attrs: dict[str, Any] | None = None,
1557
    fig_kw: dict[str, Any] | None = None,
1558
    plot_kw: dict[str, Any] | None = None,
1559
    projection: ccrs.Projection = ccrs.LambertConformal(),
1560
    transform: ccrs.Projection | None = None,
1561
    features: list[str] | dict[str, dict[str, Any]] | None = None,
1562
    geometries_kw: dict[str, Any] | None = None,
1563
    sizes: str | bool | None = None,
1564
    size_range: tuple = (10, 60),
1565
    cmap: str | matplotlib.colors.Colormap | None = None,
1566
    levels: int | None = None,
1567
    divergent: bool | int | float = False,
1568
    legend_kw: dict[str, Any] | None = None,
1569
    show_time: bool | str | int | tuple[float, float] = False,
1570
    frame: bool = False,
1571
    enumerate_subplots: bool = False,
1572
) -> matplotlib.axes.Axes:
1573
    """Make a scatter plot of georeferenced data on a map.
1574

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

1622
        ==================   =============
1623
        Location String      Location Code
1624
        ==================   =============
1625
        'upper right'        1
1626
        'upper left'         2
1627
        'lower left'         3
1628
        'lower right'        4
1629
        'right'              5
1630
        'center left'        6
1631
        'center right'       7
1632
        'lower center'       8
1633
        'upper center'       9
1634
        'center'             10
1635
        ==================   =============
1636
    frame : bool
1637
        Show or hide frame. Default False.
1638
    enumerate_subplots: bool
1639
        If True, enumerate subplots with letters.
1640
        Only works with facetgrids (pass `col` or `row` in plot_kw).
1641

1642
    Returns
1643
    -------
1644
    matplotlib.axes.Axes
1645
    """
1646
    # create empty dicts if None
1647
    use_attrs = empty_dict(use_attrs)
×
1648
    fig_kw = empty_dict(fig_kw)
×
1649
    plot_kw = empty_dict(plot_kw)
×
1650
    legend_kw = empty_dict(legend_kw)
×
1651

1652
    # set default use_attrs values
1653
    use_attrs = {"cbar_label": "long_name", "cbar_units": "units"} | use_attrs
×
1654
    if "row" not in plot_kw and "col" not in plot_kw:
×
1655
        use_attrs.setdefault("title", "description")
×
1656

1657
    # extract plot_kw from dict if needed
1658
    if isinstance(data, dict) and plot_kw and list(data.keys())[0] in plot_kw.keys():
×
1659
        plot_kw = plot_kw[list(data.keys())[0]]
×
1660

1661
    # figanos does not use xr.plot.scatter default markersize
1662
    if "markersize" in plot_kw.keys():
×
1663
        if not sizes:
×
1664
            sizes = plot_kw["markersize"]
×
1665
        plot_kw.pop("markersize")
×
1666

1667
    # if data is dict, extract
1668
    if isinstance(data, dict):
×
1669
        if len(data) == 1:
×
1670
            data = list(data.values())[0].squeeze()
×
1671
            if len(data.data_vars) > 1:
×
1672
                warnings.warn(
×
1673
                    "data is xr.Dataset; only the first variable will be used in plot"
1674
                )
1675
        else:
1676
            raise ValueError("If `data` is a dict, it must be of length 1.")
×
1677

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

1691
    # setup transform
1692
    if transform is None:
×
1693
        if "rlat" in data.dims and "rlon" in data.dims:
×
1694
            transform = get_rotpole(data)
×
1695
        elif (
×
1696
            "lat" in data.coords and "lon" in data.coords
1697
        ):  # need to work with station dims
1698
            transform = ccrs.PlateCarree()
×
1699

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

1717
    # create cbar label
1718
    if (
×
1719
        "cbar_units" in use_attrs
1720
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
1721
    ):  # avoids '[]' as label
1722
        cbar_label = (
×
1723
            get_attributes(use_attrs["cbar_label"], data)
1724
            + " ("
1725
            + get_attributes(use_attrs["cbar_units"], data)
1726
            + ")"
1727
        )
1728
    else:
1729
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
1730

1731
    if "add_colorbar" not in plot_kw or plot_kw["add_colorbar"] is not False:
×
1732
        plot_kw.setdefault("cbar_kwargs", {})
×
1733
        plot_kw["cbar_kwargs"].setdefault("label", wrap_text(cbar_label))
×
1734
        plot_kw["cbar_kwargs"].setdefault("pad", 0.015)
×
1735

1736
    # colormap
1737
    if isinstance(cmap, str):
×
1738
        if cmap not in plt.colormaps():
×
1739
            try:
×
1740
                cmap = create_cmap(filename=cmap)
×
1741
            except FileNotFoundError as e:
×
1742
                logger.error(e)
×
1743
                pass
×
1744

1745
    elif cmap is None:
×
1746
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
1747
        cmap = create_cmap(
×
1748
            get_var_group(path_to_json=cdata, da=plot_data),
1749
            divergent=divergent,
1750
        )
1751

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

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

1774
        # nans sizes
1775
        smask = ~np.isnan(sdata.values) & mask
×
1776
        if np.sum(smask) < np.sum(mask):
×
1777
            warnings.warn(
×
1778
                f"{np.sum(mask) - np.sum(smask)} nan values were dropped when setting the point size"
1779
            )
1780
            mask = smask
×
1781

1782
        pt_sizes = norm2range(
×
1783
            data=sdata.where(mask).values,
1784
            target_range=size_range,
1785
            data_range=None,
1786
        )
1787
        plot_kw.setdefault("add_legend", False)
×
1788
        if ax:
×
1789
            plot_kw.setdefault("s", pt_sizes)
×
1790
        else:
1791
            plot_kw.setdefault("s", pt_sizes[0])
×
1792

1793
    # norm
1794
    plot_kw.setdefault("vmin", np.nanmin(plot_data.values[mask]))
×
1795
    plot_kw.setdefault("vmax", np.nanmax(plot_data.values[mask]))
×
1796
    if levels is not None:
×
1797
        if isinstance(levels, Iterable):
×
1798
            lin = levels
×
1799
        else:
1800
            lin = custom_cmap_norm(
×
1801
                cmap,
1802
                np.nanmin(plot_data.values[mask]),
1803
                np.nanmax(plot_data.values[mask]),
1804
                levels=levels,
1805
                divergent=divergent,
1806
                linspace_out=True,
1807
            )
1808
        plot_kw.setdefault("levels", lin)
×
1809

1810
    elif (divergent is not False) and ("levels" not in plot_kw):
×
NEW
1811
        vmin = plot_kw.pop("vmin", np.nanmin(plot_data.values[mask]))
×
NEW
1812
        vmax = plot_kw.pop("vmax", np.nanmax(plot_data.values[mask]))
×
UNCOV
1813
        norm = custom_cmap_norm(
×
1814
            cmap,
1815
            vmin,
1816
            vmax,
1817
            levels=levels,
1818
            divergent=divergent,
1819
        )
1820
        plot_kw.setdefault("norm", norm)
×
1821

1822
    # matplotlib.pyplot.scatter treats "edgecolor" and "edgecolors" as aliases so we accept "edgecolor" and convert it
1823
    if "edgecolor" in plot_kw and "edgecolors" not in plot_kw:
×
1824
        plot_kw["edgecolors"] = plot_kw["edgecolor"]
×
1825
        plot_kw.pop("edgecolor")
×
1826

1827
    # set defaults and create copy without vmin, vmax (conflicts with norm)
1828
    plot_kw = {
×
1829
        "cmap": cmap,
1830
        "transform": transform,
1831
        "zorder": 8,
1832
        "marker": "o",
1833
    } | plot_kw
1834

1835
    # check if edgecolors in plot_kw and match len of plot_data
1836
    if "edgecolors" in plot_kw:
×
1837
        if matplotlib.colors.is_color_like(plot_kw["edgecolors"]):
×
1838
            plot_kw["edgecolors"] = np.repeat(
×
1839
                plot_kw["edgecolors"], len(plot_data.where(mask).values)
1840
            )
1841
        elif len(plot_kw["edgecolors"]) != len(plot_data.values):
×
1842
            plot_kw["edgecolors"] = np.repeat(
×
1843
                plot_kw["edgecolors"][0], len(plot_data.where(mask).values)
1844
            )
1845
            warnings.warn(
×
1846
                "Length of edgecolors does not match length of data. Only first edgecolor is used for plotting."
1847
            )
1848
        else:
1849
            if isinstance(plot_kw["edgecolors"], list):
×
1850
                plot_kw["edgecolors"] = np.array(plot_kw["edgecolors"])
×
1851
            plot_kw["edgecolors"] = plot_kw["edgecolors"][mask]
×
1852
    else:
1853
        plot_kw.setdefault("edgecolors", "none")
×
1854

1855
    for key in ["vmin", "vmax"]:
×
NEW
1856
        plot_kw.pop(key, None)
×
1857
    # plot
1858
    plot_kw = {"x": "lon", "y": "lat", "hue": plot_data.name} | plot_kw
×
1859
    if ax:
×
1860
        plot_kw.setdefault("ax", ax)
×
1861

1862
    plot_data_masked = plot_data.where(mask).to_dataset()
×
1863
    im = plot_data_masked.plot.scatter(**plot_kw)
×
1864

1865
    # add features
1866
    if ax:
×
1867
        ax = add_features_map(
×
1868
            data,
1869
            ax,
1870
            use_attrs,
1871
            projection,
1872
            features,
1873
            geometries_kw,
1874
            frame,
1875
        )
1876

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

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

1898
    else:
1899
        for i, fax in enumerate(im.axs.flat):
×
1900
            fax = add_features_map(
×
1901
                data,
1902
                fax,
1903
                use_attrs,
1904
                projection,
1905
                features,
1906
                geometries_kw,
1907
                frame,
1908
            )
1909

1910
            if sizes:
×
1911
                # correct markersize for facetgrid
1912
                scat = fax.collections[0]
×
1913
                scat.set_sizes(pt_sizes[i])
×
1914

1915
        if (frame is False) and (im.cbar is not None):
×
1916
            im.cbar.outline.set_visible(False)
×
1917

1918
        if show_time:
×
1919
            if isinstance(show_time, bool):
×
1920
                plot_coords(
×
1921
                    None,
1922
                    plot_data,
1923
                    param="time",
1924
                    loc="lower right",
1925
                    backgroundalpha=1,
1926
                )
1927
            elif isinstance(show_time, (str, tuple, int)):
×
1928
                plot_coords(
×
1929
                    None,
1930
                    plot_data,
1931
                    param="time",
1932
                    loc=show_time,
1933
                    backgroundalpha=1,
1934
                )
1935

1936
    # size legend
1937
    if sizes:
×
1938
        legend_elements = size_legend_elements(
×
1939
            np.resize(sdata.values[mask], (sdata.values[mask].size, 1)),
1940
            np.resize(pt_sizes[mask], (pt_sizes[mask].size, 1)),
1941
            max_entries=6,
1942
            marker=plot_kw["marker"],
1943
        )
1944
        # legend spacing
1945
        if size_range[1] > 200:
×
1946
            ls = 0.5 + size_range[1] / 100 * 0.125
×
1947
        else:
1948
            ls = 0.5
×
1949

1950
        legend_kw = {
×
1951
            "loc": "lower left",
1952
            "facecolor": "w",
1953
            "framealpha": 1,
1954
            "edgecolor": "w",
1955
            "labelspacing": ls,
1956
            "handles": legend_elements,
1957
            "bbox_to_anchor": (-0.05, -0.1),
1958
        } | legend_kw
1959

1960
        if "title" not in legend_kw:
×
1961
            if hasattr(sdata, "long_name"):
×
1962
                lgd_title = wrap_text(
×
1963
                    getattr(sdata, "long_name"), min_line_len=1, max_line_len=15
1964
                )
1965
                if hasattr(sdata, "units"):
×
1966
                    lgd_title += f" ({getattr(sdata, 'units')})"
×
1967
            else:
1968
                lgd_title = sizes
×
1969
            legend_kw.setdefault("title", lgd_title)
×
1970

1971
        if ax:
×
1972
            lgd = ax.legend(**legend_kw)
×
1973
            lgd.set_zorder(11)
×
1974
        else:
1975
            im.figlegend = im.fig.legend(**legend_kw)
×
1976
        # im._adjust_fig_for_guide(im.figlegend)
1977

1978
    if ax:
×
1979
        return ax
×
1980
    else:
1981
        im.fig.suptitle(get_attributes("long_name", data))
×
1982
        im.set_titles(template="{value}")
×
1983
        if enumerate_subplots and isinstance(im, xr.plot.facetgrid.FacetGrid):
×
1984
            for idx, ax in enumerate(im.axs.flat):
×
1985
                ax.set_title(f"{string.ascii_lowercase[idx]}) {ax.get_title()}")
×
1986

1987
        return im
×
1988

1989

1990
def taylordiagram(
5✔
1991
    data: xr.DataArray | dict[str, xr.DataArray],
1992
    plot_kw: dict[str, Any] | None = None,
1993
    fig_kw: dict[str, Any] | None = None,
1994
    std_range: tuple = (0, 1.5),
1995
    contours: int | None = 4,
1996
    contours_kw: dict[str, Any] | None = None,
1997
    ref_std_line: bool = False,
1998
    legend_kw: dict[str, Any] | None = None,
1999
    std_label: str | None = None,
2000
    corr_label: str | None = None,
2001
    colors_key: str | None = None,
2002
    markers_key: str | None = None,
2003
):
2004
    """Build a Taylor diagram.
2005

2006
    Based on the following code: https://gist.github.com/ycopin/3342888.
2007

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

2039
    Returns
2040
    -------
2041
    (plt.figure, mpl_toolkits.axisartist.floating_axes.FloatingSubplot, plt.legend)
2042
    """
2043
    plot_kw = empty_dict(plot_kw)
×
2044
    fig_kw = empty_dict(fig_kw)
×
2045
    contours_kw = empty_dict(contours_kw)
×
2046
    legend_kw = empty_dict(legend_kw)
×
2047

2048
    # preserve order of dimensions if used for marker/color
2049
    ordered_markers_type = None
×
2050
    ordered_colors_type = None
×
2051

2052
    # convert SSP, RCP, CMIP formats in keys
2053
    if isinstance(data, dict):
×
2054
        data = process_keys(data, convert_scen_name)
×
2055
    if isinstance(plot_kw, dict):
×
2056
        plot_kw = process_keys(plot_kw, convert_scen_name)
×
2057

2058
    # if only one data input, insert in dict.
2059
    if not isinstance(data, dict):
×
2060
        data = {"_no_label": data}  # mpl excludes labels starting with "_" from legend
×
2061
        plot_kw = {"_no_label": empty_dict(plot_kw)}
×
2062
    elif not plot_kw:
×
2063
        plot_kw = {k: {} for k in data.keys()}
×
2064
    # check type
2065
    for key, v in data.items():
×
2066
        if not isinstance(v, xr.DataArray):
×
2067
            raise TypeError("All objects in 'data' must be xarray DataArrays.")
×
2068
        if "taylor_param" not in v.dims:
×
2069
            raise ValueError("All DataArrays must contain a 'taylor_param' dimension.")
×
2070
        if key == "reference":
×
2071
            raise ValueError("'reference' is not allowed as a key in data.")
×
2072

2073
    # If there are other dimensions than 'taylor_param', create a bigger dict with them
2074
    data_keys = list(data.keys())
×
2075
    for data_key in data_keys:
×
2076
        da = data[data_key]
×
2077
        dims = list(set(da.dims) - {"taylor_param"})
×
2078
        if dims != []:
×
2079
            if markers_key in dims:
×
2080
                ordered_markers_type = da[markers_key].values
×
2081
            if colors_key in dims:
×
2082
                ordered_colors_type = da[colors_key].values
×
2083

2084
            da = da.stack(pl_dims=dims)
×
2085
            for i, dim_key in enumerate(da.pl_dims.values):
×
2086
                if isinstance(dim_key, list) or isinstance(dim_key, tuple):
×
2087
                    dim_key = "-".join([str(k) for k in dim_key])
×
2088
                da0 = da.isel(pl_dims=i)
×
2089
                # if colors_key/markers_key is a dimension, add it as an attribute for later use
2090
                if markers_key in dims:
×
2091
                    da0.attrs[markers_key] = da0[markers_key].values.item()
×
2092
                if colors_key in dims:
×
2093
                    da0.attrs[colors_key] = da0[colors_key].values.item()
×
2094
                new_data_key = (
×
2095
                    f"{data_key}-{dim_key}" if data_key != "_no_label" else dim_key
2096
                )
2097
                data[new_data_key] = da0
×
2098
                plot_kw[new_data_key] = empty_dict(plot_kw[f"{data_key}"])
×
2099
            data.pop(data_key)
×
2100
            plot_kw.pop(data_key)
×
2101

2102
    # remove negative correlations
2103
    initial_len = len(data)
×
2104
    removed = [
×
2105
        key for key, da in data.items() if da.sel(taylor_param="corr").values < 0
2106
    ]
2107
    data = {
×
2108
        key: da for key, da in data.items() if da.sel(taylor_param="corr").values >= 0
2109
    }
2110
    if len(data) != initial_len:
×
2111
        warnings.warn(
×
2112
            f"{initial_len - len(data)} points with negative correlations will not be plotted: {', '.join(removed)}"
2113
        )
2114

2115
    # add missing keys to plot_kw
2116
    for key in data.keys():
×
2117
        if key not in plot_kw:
×
2118
            plot_kw[key] = {}
×
2119

2120
    # extract ref to be used in plot
2121
    ref_std = list(data.values())[0].sel(taylor_param="ref_std").values
×
2122
    # check if ref is the same in all DataArrays and get the highest std (for ax limits)
2123
    if len(data) > 1:
×
2124
        for key, da in data.items():
×
2125
            if da.sel(taylor_param="ref_std").values != ref_std:
×
2126
                raise ValueError(
×
2127
                    "All reference standard deviation values must be identical"
2128
                )
2129

2130
    # get highest std for axis limits
2131
    max_std = [ref_std]
×
2132
    for key, da in data.items():
×
2133
        max_std.append(
×
2134
            float(
2135
                max(
2136
                    da.sel(taylor_param="ref_std").values,
2137
                    da.sel(taylor_param="sim_std").values,
2138
                )
2139
            )
2140
        )
2141

2142
    # make labels
2143
    if not std_label:
×
2144
        try:
×
2145
            units = list(data.values())[0].units
×
2146
            std_label = get_localized_term("standard deviation")
×
2147
            std_label = std_label if units == "" else f"{std_label} ({units})"
×
2148
        except AttributeError:
×
2149
            std_label = get_localized_term("standard deviation").capitalize()
×
2150

2151
    if not corr_label:
×
2152
        try:
×
2153
            if "Pearson" in list(data.values())[0].correlation_type:
×
2154
                corr_label = get_localized_term("pearson correlation").capitalize()
×
2155
            else:
2156
                corr_label = get_localized_term("correlation").capitalize()
×
2157
        except AttributeError:
×
2158
            corr_label = get_localized_term("correlation").capitalize()
×
2159

2160
    # build diagram
2161
    transform = PolarAxes.PolarTransform()
×
2162

2163
    # Setup the axis, here we map angles in degrees to angles in radius
2164
    # Correlation labels
2165
    rlocs = np.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
×
2166
    tlocs = np.arccos(rlocs)  # Conversion to polar angles
×
2167
    gl1 = gf.FixedLocator(tlocs)  # Positions
×
2168
    tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, rlocs))))
×
2169
    # Standard deviation axis extent
2170
    radius_min = std_range[0] * max(max_std)
×
2171
    radius_max = std_range[1] * max(max_std)
×
2172

2173
    # Set up the axes range in the parameter "extremes"
2174
    ghelper = GridHelperCurveLinear(
×
2175
        transform,
2176
        extremes=(0, np.pi / 2, radius_min, radius_max),
2177
        grid_locator1=gl1,
2178
        tick_formatter1=tf1,
2179
    )
2180

2181
    fig = plt.figure(**fig_kw)
×
2182
    floating_ax = FloatingSubplot(fig, 111, grid_helper=ghelper)
×
2183
    fig.add_subplot(floating_ax)
×
2184

2185
    # Adjust axes
2186
    floating_ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
×
2187
    floating_ax.axis["top"].toggle(ticklabels=True, label=True)
×
2188
    floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
×
2189
    floating_ax.axis["top"].label.set_axis_direction("top")
×
2190
    floating_ax.axis["top"].label.set_text(corr_label)
×
2191

2192
    floating_ax.axis["left"].set_axis_direction("bottom")  # "X axis"
×
2193
    floating_ax.axis["left"].label.set_text(std_label)
×
2194

2195
    floating_ax.axis["right"].set_axis_direction("top")  # "Y axis"
×
2196
    floating_ax.axis["right"].toggle(ticklabels=True, label=True)
×
2197
    floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
×
2198
    floating_ax.axis["right"].label.set_text(std_label)
×
2199

2200
    floating_ax.axis["bottom"].set_visible(False)  # Useless
×
2201

2202
    # Contours along standard deviations
2203
    floating_ax.grid(visible=True, alpha=0.4)
×
2204
    floating_ax.set_title("")
×
2205

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

2208
    # plot reference
2209
    if "reference" in plot_kw:
×
2210
        ref_kw = plot_kw.pop("reference")
×
2211
    else:
2212
        ref_kw = {}
×
2213
    ref_kw = {
×
2214
        "color": "#154504",
2215
        "marker": "s",
2216
        "label": get_localized_term("reference"),
2217
    } | ref_kw
2218

2219
    ref_pt = ax.scatter(0, ref_std, **ref_kw)
×
2220

2221
    points = [ref_pt]  # set up for later
×
2222

2223
    # plot a circular line along `ref_std`
2224
    if ref_std_line:
×
2225
        angles_for_line = np.linspace(0, np.pi / 2, 100)
×
2226
        radii_for_line = np.full_like(angles_for_line, ref_std)
×
2227
        ax.plot(
×
2228
            angles_for_line,
2229
            radii_for_line,
2230
            color=ref_kw["color"],
2231
            linewidth=0.5,
2232
            linestyle="-",
2233
        )
2234

2235
    # rmse contours from reference standard deviation
2236
    if contours:
×
2237
        radii, angles = np.meshgrid(
×
2238
            np.linspace(radius_min, radius_max),
2239
            np.linspace(0, np.pi / 2),
2240
        )
2241
        # Compute centered RMS difference
2242
        rms = np.sqrt(ref_std**2 + radii**2 - 2 * ref_std * radii * np.cos(angles))
×
2243

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

2247
        ax.clabel(ct, ct.levels, fontsize=8)
×
2248

2249
        # points.append(ct_line)
2250
        ct_line = ax.plot(
×
2251
            [0],
2252
            [0],
2253
            ls=contours_kw["linestyles"],
2254
            lw=1,
2255
            c="k" if "colors" not in contours_kw else contours_kw["colors"],
2256
            label="rmse",
2257
        )
2258
        points.append(ct_line[0])
×
2259

2260
    # get color options
2261
    style_colors = matplotlib.rcParams["axes.prop_cycle"].by_key()["color"]
×
2262
    if len(data) > len(style_colors):
×
2263
        style_colors = style_colors * math.ceil(len(data) / len(style_colors))
×
2264
    cat_colors = Path(__file__).parents[1] / "data/ipcc_colors/categorical_colors.json"
×
2265
    # get marker options (only used if `markers_key` is set)
2266
    style_markers = "oDv^<>p*hH+x|_"
×
2267
    if len(data) > len(style_markers):
×
2268
        style_markers = style_markers * math.ceil(len(data) / len(style_markers))
×
2269

2270
    # set colors and markers styles based on discrimnating attributes (if specified)
2271
    if colors_key or markers_key:
×
2272
        if colors_key:
×
2273
            # get_scen_color : look for SSP, RCP, CMIP model color
2274
            colors_type = (
×
2275
                ordered_colors_type
2276
                if ordered_colors_type is not None
2277
                else {da.attrs[colors_key] for da in data.values()}
2278
            )
2279
            colorsd = {
×
2280
                k: get_scen_color(k, cat_colors) or style_colors[i]
2281
                for i, k in enumerate(colors_type)
2282
            }
2283
        if markers_key:
×
2284
            markers_type = (
×
2285
                ordered_markers_type
2286
                if ordered_markers_type is not None
2287
                else {da.attrs[markers_key] for da in data.values()}
2288
            )
2289
            markersd = {k: style_markers[i] for i, k in enumerate(markers_type)}
×
2290

2291
        for key, da in data.items():
×
2292
            if colors_key:
×
2293
                plot_kw[key]["color"] = colorsd[da.attrs[colors_key]]
×
2294
            if markers_key:
×
2295
                plot_kw[key]["marker"] = markersd[da.attrs[markers_key]]
×
2296

2297
    # plot scatter
2298
    for (key, da), i in zip(data.items(), range(len(data))):
×
2299
        # look for SSP, RCP, CMIP model color
2300
        if colors_key is None:
×
2301
            plot_kw[key].setdefault(
×
2302
                "color", get_scen_color(key, cat_colors) or style_colors[i]
2303
            )
2304
        # set defaults
2305
        plot_kw[key] = {"label": key} | plot_kw[key]
×
2306

2307
        # legend will be handled later in this case
2308
        if markers_key or colors_key:
×
2309
            plot_kw[key]["label"] = ""
×
2310

2311
        # plot
2312
        pt = ax.scatter(
×
2313
            np.arccos(da.sel(taylor_param="corr").values),
2314
            da.sel(taylor_param="sim_std").values,
2315
            **plot_kw[key],
2316
        )
2317
        points.append(pt)
×
2318

2319
    # legend
2320
    legend_kw.setdefault("loc", "upper right")
×
2321
    legend = fig.legend(points, [pt.get_label() for pt in points], **legend_kw)
×
2322

2323
    # plot new legend if markers/colors represent a certain dimension
2324
    if colors_key or markers_key:
×
2325
        handles = list(floating_ax.get_legend_handles_labels()[0])
×
2326
        if markers_key:
×
2327
            for k, m in markersd.items():
×
2328
                handles.append(Line2D([0], [0], color="k", label=k, marker=m, ls=""))
×
2329
        if colors_key:
×
2330
            for k, c in colorsd.items():
×
2331
                handles.append(Line2D([0], [0], color=c, label=k, ls="-"))
×
2332
        legend.remove()
×
2333
        legend = fig.legend(handles=handles, **legend_kw)
×
2334

2335
    return fig, floating_ax, legend
×
2336

2337

2338
def hatchmap(
5✔
2339
    data: dict[str, Any] | xr.DataArray | xr.Dataset,
2340
    ax: matplotlib.axes.Axes | None = None,
2341
    use_attrs: dict[str, Any] | None = None,
2342
    fig_kw: dict[str, Any] | None = None,
2343
    plot_kw: dict[str, Any] | None = None,
2344
    projection: ccrs.Projection = ccrs.LambertConformal(),
2345
    transform: ccrs.Projection | None = None,
2346
    features: list[str] | dict[str, dict[str, Any]] | None = None,
2347
    geometries_kw: dict[str, Any] | None = None,
2348
    levels: int | None = None,
2349
    legend_kw: dict[str, Any] | bool = True,
2350
    show_time: bool | str | int | tuple[float, float] = False,
2351
    frame: bool = False,
2352
    enumerate_subplots: bool = False,
2353
) -> matplotlib.axes.Axes:
2354
    """Create map of hatches from 2D data.
2355

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

2389
        ==================   =============
2390
        Location String      Location Code
2391
        ==================   =============
2392
        'upper right'        1
2393
        'upper left'         2
2394
        'lower left'         3
2395
        'lower right'        4
2396
        'right'              5
2397
        'center left'        6
2398
        'center right'       7
2399
        'lower center'       8
2400
        'upper center'       9
2401
        'center'             10
2402
        ==================   =============
2403
    frame : bool
2404
        Show or hide frame. Default False.
2405
    enumerate_subplots: bool
2406
        If True, enumerate subplots with letters.
2407
        Only works with facetgrids (pass `col` or `row` in plot_kw).
2408

2409
    Returns
2410
    -------
2411
    matplotlib.axes.Axes
2412
    """
2413
    # default hatches
2414
    dfh = [
×
2415
        "/",
2416
        "\\",
2417
        "|",
2418
        "-",
2419
        "+",
2420
        "x",
2421
        "o",
2422
        "O",
2423
        ".",
2424
        "*",
2425
        "//",
2426
        "\\\\",
2427
        "||",
2428
        "--",
2429
        "++",
2430
        "xx",
2431
        "oo",
2432
        "OO",
2433
        "..",
2434
        "**",
2435
    ]
2436

2437
    # create empty dicts if None
2438
    use_attrs = empty_dict(use_attrs)
×
2439
    fig_kw = empty_dict(fig_kw)
×
2440
    plot_kw = empty_dict(plot_kw)
×
2441
    legend_kw = empty_dict(legend_kw)
×
2442

2443
    dattrs = None
×
2444
    plot_data = {}
×
2445

2446
    # convert data to dict (if not one)
2447
    if not isinstance(data, dict):
×
2448
        if isinstance(data, xr.DataArray):
×
2449
            plot_data = {data.name: data}
×
2450
            if data.name not in plot_kw.keys():
×
2451
                plot_kw = {data.name: plot_kw}
×
2452
        elif isinstance(data, xr.Dataset):
×
2453
            dattrs = data
×
2454
            plot_data = {var: data[var] for var in data.data_vars}
×
2455
            for v in plot_data.keys():
×
2456
                if v not in plot_kw.keys():
×
2457
                    plot_kw[v] = plot_kw
×
2458
    else:
2459
        for k, v in data.items():
×
2460
            if k not in plot_kw.keys():
×
2461
                plot_kw[k] = plot_kw
×
2462
            if isinstance(v, xr.Dataset):
×
2463
                dattrs = k
×
2464
                plot_data[k] = v[list(v.data_vars)[0]]
×
2465
                warnings.warn("Only first variable of Dataset is plotted.")
×
2466
            else:
2467
                plot_data[k] = v
×
2468

2469
    # setup transform from first data entry
2470
    trdata = list(plot_data.values())[0]
×
2471
    if transform is None:
×
2472
        if "lat" in trdata.dims and "lon" in trdata.dims:
×
2473
            transform = ccrs.PlateCarree()
×
2474
        elif "rlat" in trdata.dims and "rlon" in trdata.dims:
×
2475
            transform = get_rotpole(list(plot_data.values())[0])
×
2476

2477
    # bug xlim / ylim + transform in facetgrids
2478
    # (see https://github.com/pydata/xarray/issues/8562#issuecomment-1865189766)
2479
    if transform and (
×
2480
        "xlim" in list(plot_kw.values())[0] and "ylim" in list(plot_kw.values())[0]
2481
    ):
2482
        extent = [
×
2483
            list(plot_kw.values())[0]["xlim"][0],
2484
            list(plot_kw.values())[0]["xlim"][1],
2485
            list(plot_kw.values())[0]["ylim"][0],
2486
            list(plot_kw.values())[0]["ylim"][1],
2487
        ]
2488
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2489

2490
    elif transform and (
×
2491
        "xlim" in list(plot_kw.values())[0] or "ylim" in list(plot_kw.values())[0]
2492
    ):
2493
        extent = None
×
2494
        warnings.warn(
×
2495
            "Requires both xlim and ylim with 'transform'. Xlim or ylim was dropped"
2496
        )
2497
        [v.pop(lim) for lim in ["xlim", "ylim"] for v in plot_kw.values() if lim in v]
×
2498

2499
    else:
2500
        extent = None
×
2501

2502
    # setup fig, ax
2503
    if ax is None and (
×
2504
        "row" not in list(plot_kw.values())[0].keys()
2505
        and "col" not in list(plot_kw.values())[0].keys()
2506
    ):
2507
        fig, ax = plt.subplots(subplot_kw={"projection": projection}, **fig_kw)
×
2508
    elif ax is not None and (
×
2509
        "col" in list(plot_kw.values())[0].keys()
2510
        or "row" in list(plot_kw.values())[0].keys()
2511
    ):
2512
        raise ValueError("Cannot use 'ax' and 'col'/'row' at the same time.")
×
2513
    elif ax is None:
×
2514
        [
×
2515
            v.setdefault("subplot_kws", {}).setdefault("projection", projection)
2516
            for v in plot_kw.values()
2517
        ]
2518
        cfig_kw = copy.deepcopy(fig_kw)
×
2519
        if "figsize" in fig_kw:  # add figsize to plot_kw for facetgrid
×
2520
            plot_kw[0].setdefault("figsize", fig_kw["figsize"])
×
2521
            cfig_kw.pop("figsize")
×
2522
        if cfig_kw:
×
2523
            for v in plot_kw.values():
×
2524
                {"subplots_kws": cfig_kw} | v
×
2525
            warnings.warn(
×
2526
                "Only figsize and figure.add_subplot() arguments can be passed to fig_kw when using facetgrid."
2527
            )
2528

2529
    pat_leg = []
×
2530
    n = 0
×
2531
    for k, v in plot_data.items():
×
2532
        # if levels plot multiple hatching from one data entry
2533
        if "levels" in plot_kw[k] and len(plot_data) == 1:
×
2534
            # nans
2535
            mask = ~np.isnan(v.values)
×
2536
            if np.sum(mask) < len(mask):
×
2537
                warnings.warn(
×
2538
                    f"{len(mask) - np.sum(mask)} nan values were dropped when plotting the pattern values"
2539
                )
2540
            if "hatches" in plot_kw[k] and plot_kw[k]["levels"] != len(
×
2541
                plot_kw[k]["hatches"]
2542
            ):
2543
                warnings.warn("Hatches number is not equivalent to number of levels")
×
2544
                hatches = dfh[0:levels]
×
2545
            if "hatches" not in plot_kw[k]:
×
2546
                hatches = dfh[0:levels]
×
2547

2548
            plot_kw[k] = {
×
2549
                "hatches": hatches,
2550
                "colors": "none",
2551
                "add_colorbar": False,
2552
            } | plot_kw[k]
2553

2554
            if "lat" in v.dims:
×
2555
                v.coords["mask"] = (("lat", "lon"), mask)
×
2556
            else:
2557
                v.coords["mask"] = (("rlat", "rlon"), mask)
×
2558

2559
            plot_kw[k].setdefault("transform", transform)
×
2560
            if ax:
×
2561
                plot_kw[k].setdefault("ax", ax)
×
2562

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

2566
            if ax and legend_kw:
×
2567
                ax.legend(artists, labels, **legend_kw)
×
2568
            elif legend_kw:
×
2569
                im.figlegend = im.fig.legend(**legend_kw)
×
2570

2571
        elif len(plot_data) > 1 and "levels" in plot_kw[k]:
×
2572
            raise TypeError(
×
2573
                "To plot levels only one xr.DataArray or xr.Dataset accepted"
2574
            )
2575
        else:
2576
            # since pattern remove colors and colorbar from plotting (done by gridmap)
2577
            plot_kw[k] = {"colors": "none", "add_colorbar": False} | plot_kw[k]
×
2578

2579
            if "hatches" not in plot_kw[k].keys():
×
2580
                plot_kw[k]["hatches"] = dfh[n]
×
2581
                n += 1
×
2582
            elif isinstance(
×
2583
                plot_kw[k]["hatches"], str
2584
            ):  # make sure the hatches are in a list
2585
                warnings.warn(
×
2586
                    "Hatches argument must be of type 'list'. Wrapping string argument as list."
2587
                )
2588
                plot_kw[k]["hatches"] = [plot_kw[k]["hatches"]]
×
2589

2590
            plot_kw[k].setdefault("transform", transform)
×
2591
            if ax:
×
2592
                im = v.plot.contourf(ax=ax, **plot_kw[k])
×
2593

2594
            if not ax:
×
2595
                if k == list(plot_data.keys())[0]:
×
2596
                    im = v.plot.contourf(**plot_kw[k])
×
2597

2598
                for i, fax in enumerate(im.axs.flat):
×
2599
                    if len(plot_data) > 1 and k != list(plot_data.keys())[0]:
×
2600
                        # select data to plot from DataSet in loop to plot on facetgrids axis
2601
                        c_pkw = plot_kw[k].copy()
×
2602
                        c_pkw.pop("subplot_kws")
×
2603
                        sel = {}
×
2604
                        if "row" in c_pkw.keys():
×
2605
                            sel[c_pkw["row"]] = i
×
2606
                            c_pkw.pop("row")
×
2607
                        elif "col" in c_pkw.keys():
×
2608
                            sel[c_pkw["col"]] = i
×
2609
                            c_pkw.pop("col")
×
2610
                        v.isel(sel).plot.contourf(ax=fax, **c_pkw)
×
2611

2612
                    if k == list(plot_data.keys())[-1]:
×
2613
                        add_features_map(
×
2614
                            dattrs,
2615
                            fax,
2616
                            use_attrs,
2617
                            projection,
2618
                            features,
2619
                            geometries_kw,
2620
                            frame,
2621
                        )
2622
                        if extent:
×
2623
                            fax.set_extent(extent)
×
2624

2625
            pat_leg.append(
×
2626
                matplotlib.patches.Patch(
2627
                    hatch=plot_kw[k]["hatches"][0], fill=False, label=k
2628
                )
2629
            )
2630

2631
    if pat_leg and legend_kw:
×
2632
        legend_kw = {
×
2633
            "loc": "lower right",
2634
            "handleheight": 2,
2635
            "handlelength": 4,
2636
        } | legend_kw
2637

2638
        if ax and legend_kw:
×
2639
            ax.legend(handles=pat_leg, **legend_kw)
×
2640
        elif legend_kw:
×
2641
            im.figlegend = im.fig.legend(handles=pat_leg, **legend_kw)
×
2642

2643
    # add features
2644
    if ax:
×
2645
        if extent:
×
2646
            ax.set_extent(extent)
×
2647
        if dattrs:
×
2648
            use_attrs.setdefault("title", "description")
×
2649

2650
        ax = add_features_map(
×
2651
            dattrs,
2652
            ax,
2653
            use_attrs,
2654
            projection,
2655
            features,
2656
            geometries_kw,
2657
            frame,
2658
        )
2659

2660
        if show_time:
×
2661
            if isinstance(show_time, bool):
×
2662
                plot_coords(
×
2663
                    ax,
2664
                    plot_data,
2665
                    param="time",
2666
                    loc="lower right",
2667
                    backgroundalpha=1,
2668
                )
2669
            elif isinstance(show_time, (str, tuple, int)):
×
2670
                plot_coords(
×
2671
                    ax,
2672
                    plot_data,
2673
                    param="time",
2674
                    loc=show_time,
2675
                    backgroundalpha=1,
2676
                )
2677

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

2685
            set_plot_attrs(use_attrs, dattrs, ax, wrap_kw={"max_line_len": 60})
×
2686
        return ax
×
2687

2688
    else:
2689
        # when im is an ax, it has a colorbar attribute. If it is a facetgrid, it has a cbar attribute.
2690
        if (frame is False) and (
×
2691
            (getattr(im, "colorbar", None) is not None)
2692
            or (getattr(im, "cbar", None) is not None)
2693
        ):
2694
            im.cbar.outline.set_visible(False)
×
2695

2696
        if show_time:
×
2697
            if show_time is True:
×
2698
                plot_coords(
×
2699
                    None,
2700
                    dattrs,
2701
                    param="time",
2702
                    loc="lower right",
2703
                    backgroundalpha=1,
2704
                )
2705
            elif isinstance(show_time, (str, tuple, int)):
×
2706
                plot_coords(
×
2707
                    None, dattrs, param="time", loc=show_time, backgroundalpha=1
2708
                )
2709
        if dattrs:
×
2710
            use_attrs.setdefault("suptitle", "long_name")
×
2711
            set_plot_attrs(use_attrs, dattrs, facetgrid=im)
×
2712

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

2717
        return im
×
2718

2719

2720
def _add_lead_time_coord(da, ref):
5✔
2721
    """Add a lead time coordinate to the data. Modifies da in-place."""
2722
    lead_time = da.time.dt.year - int(ref)
×
2723
    da["Lead time"] = lead_time
×
2724
    da["Lead time"].attrs["units"] = f"years from {ref}"
×
2725
    return lead_time
×
2726

2727

2728
def partition(
5✔
2729
    data: xr.DataArray | xr.Dataset,
2730
    ax: matplotlib.axes.Axes | None = None,
2731
    start_year: str | None = None,
2732
    show_num: bool = True,
2733
    fill_kw: dict[str, Any] | None = None,
2734
    line_kw: dict[str, Any] | None = None,
2735
    fig_kw: dict[str, Any] | None = None,
2736
    legend_kw: dict[str, Any] | None = None,
2737
) -> matplotlib.axes.Axes:
2738
    """Figure of the partition of total uncertainty by components.
2739

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

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

2767
    Returns
2768
    -------
2769
    mpl.axes.Axes
2770
    """
2771
    if isinstance(data, xr.Dataset):
×
2772
        if len(data.data_vars) > 1:
×
2773
            warnings.warn(
×
2774
                "data is xr.Dataset; only the first variable will be used in plot"
2775
            )
2776
        data = data[list(data.keys())[0]].squeeze()
×
2777

2778
    if data.attrs["units"] != "%":
×
2779
        raise ValueError(
×
2780
            "The units are not %. Use `fraction=True` in the xclim function call."
2781
        )
2782

2783
    fill_kw = empty_dict(fill_kw)
×
2784
    line_kw = empty_dict(line_kw)
×
2785
    fig_kw = empty_dict(fig_kw)
×
2786
    legend_kw = empty_dict(legend_kw)
×
2787

2788
    # select data to plot
2789
    if isinstance(data, xr.DataArray):
×
2790
        data = data.squeeze()
×
2791
    elif isinstance(data, xr.Dataset):  # in case, it was saved to disk before plotting.
×
2792
        if len(data.data_vars) > 1:
×
2793
            warnings.warn(
×
2794
                "data is xr.Dataset; only the first variable will be used in plot"
2795
            )
2796
        data = data[list(data.keys())[0]].squeeze()
×
2797
    else:
2798
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2799

2800
    if ax is None:
×
2801
        fig, ax = plt.subplots(**fig_kw)
×
2802

2803
    # Select data from reference year onward
2804
    if start_year:
×
2805
        data = data.sel(time=slice(start_year, None))
×
2806

2807
        # Lead time coordinate
2808
        time = _add_lead_time_coord(data, start_year)
×
2809
        ax.set_xlabel(f"Lead time (years from {start_year})")
×
2810
    else:
2811
        time = data.time.dt.year
×
2812

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

2816
    # Draw areas
2817
    past_y = 0
×
2818
    black_lines = []
×
2819
    for u in data.uncertainty.values:
×
2820
        if u not in ["total", "variability"]:
×
2821
            present_y = past_y + data.sel(uncertainty=u)
×
2822
            num = len(data.attrs.get(u, []))  # compatible with pre PR PR #1529
×
2823
            label = f"{u} ({num})" if show_num and num else u
×
2824
            ax.fill_between(
×
2825
                time,
2826
                past_y,
2827
                present_y,
2828
                label=label,
2829
                **fill_kw.get(u, fk_direct),
2830
            )
2831
            black_lines.append(present_y)
×
2832
            past_y = present_y
×
2833
    ax.fill_between(
×
2834
        time,
2835
        past_y,
2836
        100,
2837
        label="variability",
2838
        **fill_kw.get("variability", fk_direct),
2839
    )
2840

2841
    # Draw black lines
2842
    line_kw.setdefault("color", "k")
×
2843
    line_kw.setdefault("lw", 2)
×
2844
    ax.plot(time, np.array(black_lines).T, **line_kw)
×
2845

2846
    ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(20))
×
2847
    ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=5))
×
2848

2849
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))
×
2850
    ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator(n=2))
×
2851

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

2854
    ax.set_ylim(0, 100)
×
2855
    ax.legend(**legend_kw)
×
2856

2857
    return ax
×
2858

2859

2860
def triheatmap(
5✔
2861
    data: xr.DataArray | xr.Dataset,
2862
    z: str,
2863
    ax: matplotlib.axes.Axes | None = None,
2864
    use_attrs: dict[str, Any] | None = None,
2865
    fig_kw: dict[str, Any] | None = None,
2866
    plot_kw: dict[str, Any] | None | list = None,
2867
    cmap: str | matplotlib.colors.Colormap | None = None,
2868
    divergent: bool | int | float = False,
2869
    cbar: bool | str = "unique",
2870
    cbar_kw: dict[str, Any] | None | list = None,
2871
) -> matplotlib.axes.Axes:
2872
    """Create a triangle heatmap from a DataArray.
2873

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

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

2909
    Returns
2910
    -------
2911
    matplotlib.axes.Axes
2912
    """
2913
    # create empty dicts if None
2914
    use_attrs = empty_dict(use_attrs)
×
2915
    fig_kw = empty_dict(fig_kw)
×
2916
    plot_kw = empty_dict(plot_kw)
×
2917
    cbar_kw = empty_dict(cbar_kw)
×
2918

2919
    # select data to plot
2920
    if isinstance(data, xr.DataArray):
×
2921
        da = data
×
2922
    elif isinstance(data, xr.Dataset):
×
2923
        if len(data.data_vars) > 1:
×
2924
            warnings.warn(
×
2925
                "data is xr.Dataset; only the first variable will be used in plot"
2926
            )
2927
        da = list(data.values())[0]
×
2928
    else:
2929
        raise TypeError("`data` must contain a xr.DataArray or xr.Dataset")
×
2930

2931
    # setup fig, axis
2932
    if ax is None:
×
2933
        fig, ax = plt.subplots(**fig_kw)
×
2934

2935
    # colormap
2936
    if isinstance(cmap, str):
×
2937
        if cmap not in plt.colormaps():
×
2938
            try:
×
2939
                cmap = create_cmap(filename=cmap)
×
2940
            except FileNotFoundError:
×
2941
                pass
×
2942
                logging.log("Colormap not found. Using default.")
×
2943

2944
    elif cmap is None:
×
2945
        cdata = Path(__file__).parents[1] / "data/ipcc_colors/variable_groups.json"
×
2946
        cmap = create_cmap(
×
2947
            get_var_group(path_to_json=cdata, da=da),
2948
            divergent=divergent,
2949
        )
2950

2951
    # prep data
2952
    d = [da.sel(**{z: v}).values for v in da[z].values]
×
2953

2954
    other_dims = [di for di in da.dims if di != z]
×
2955
    if len(other_dims) > 2:
×
2956
        warnings.warn(
×
2957
            "More than 3 dimensions in data. The first two after dim will be used as the dimensions of the heatmap."
2958
        )
2959
    if len(other_dims) < 2:
×
2960
        raise ValueError(
×
2961
            "Data must have 3 dimensions. If you only have 2 dimensions, use fg.heatmap."
2962
        )
2963

2964
    if plot_kw == {} and cbar in ["unique", True]:
×
2965
        warnings.warn(
×
2966
            'With cbar="unique" only the colorbar of the first triangle'
2967
            " will be shown. No `plot_kw` was passed. vmin and vmax will be set the max"
2968
            " and min of data."
2969
        )
2970
        plot_kw = {"vmax": da.max().values, "vmin": da.min().values}
×
2971

2972
    if isinstance(plot_kw, dict):
×
2973
        plot_kw.setdefault("cmap", cmap)
×
2974
        plot_kw.setdefault("ec", "white")
×
2975
        plot_kw = [plot_kw for _ in range(len(d))]
×
2976

2977
    labels_x = da[other_dims[0]].values
×
2978
    labels_y = da[other_dims[1]].values
×
2979
    m, n = d[0].shape[0], d[0].shape[1]
×
2980

2981
    # plot
2982
    if len(d) == 2:
×
2983
        x = np.arange(m + 1)
×
2984
        y = np.arange(n + 1)
×
2985
        xss, ys = np.meshgrid(x, y)
×
2986
        zs = (xss * ys) % 10
×
2987
        triangles1 = [
×
2988
            (i + j * (m + 1), i + 1 + j * (m + 1), i + (j + 1) * (m + 1))
2989
            for j in range(n)
2990
            for i in range(m)
2991
        ]
2992
        triangles2 = [
×
2993
            (
2994
                i + 1 + j * (m + 1),
2995
                i + 1 + (j + 1) * (m + 1),
2996
                i + (j + 1) * (m + 1),
2997
            )
2998
            for j in range(n)
2999
            for i in range(m)
3000
        ]
3001
        triang1 = Triangulation(xss.ravel(), ys.ravel(), triangles1)
×
3002
        triang2 = Triangulation(xss.ravel(), ys.ravel(), triangles2)
×
3003
        triangul = [triang1, triang2]
×
3004

3005
        imgs = [
×
3006
            ax.tripcolor(t, np.ravel(val), **plotkw)
3007
            for t, val, plotkw in zip(triangul, d, plot_kw)
3008
        ]
3009

3010
        ax.set_xticks(np.array(range(m)) + 0.5, labels=labels_x, rotation=45)
×
3011
        ax.set_yticks(np.array(range(n)) + 0.5, labels=labels_y, rotation=90)
×
3012

3013
    elif len(d) == 4:
×
3014
        xv, yv = np.meshgrid(
×
3015
            np.arange(-0.5, m), np.arange(-0.5, n)
3016
        )  # vertices of the little squares
3017
        xc, yc = np.meshgrid(
×
3018
            np.arange(0, m), np.arange(0, n)
3019
        )  # centers of the little squares
3020
        x = np.concatenate([xv.ravel(), xc.ravel()])
×
3021
        y = np.concatenate([yv.ravel(), yc.ravel()])
×
3022
        cstart = (m + 1) * (n + 1)  # indices of the centers
×
3023

3024
        triangles_n = [
×
3025
            (i + j * (m + 1), i + 1 + j * (m + 1), cstart + i + j * m)
3026
            for j in range(n)
3027
            for i in range(m)
3028
        ]
3029
        triangles_e = [
×
3030
            (i + 1 + j * (m + 1), i + 1 + (j + 1) * (m + 1), cstart + i + j * m)
3031
            for j in range(n)
3032
            for i in range(m)
3033
        ]
3034
        triangles_s = [
×
3035
            (
3036
                i + 1 + (j + 1) * (m + 1),
3037
                i + (j + 1) * (m + 1),
3038
                cstart + i + j * m,
3039
            )
3040
            for j in range(n)
3041
            for i in range(m)
3042
        ]
3043
        triangles_w = [
×
3044
            (i + (j + 1) * (m + 1), i + j * (m + 1), cstart + i + j * m)
3045
            for j in range(n)
3046
            for i in range(m)
3047
        ]
3048
        triangul = [
×
3049
            Triangulation(x, y, triangles)
3050
            for triangles in [
3051
                triangles_n,
3052
                triangles_e,
3053
                triangles_s,
3054
                triangles_w,
3055
            ]
3056
        ]
3057

3058
        imgs = [
×
3059
            ax.tripcolor(t, np.ravel(val), **plotkw)
3060
            for t, val, plotkw in zip(triangul, d, plot_kw)
3061
        ]
3062
        ax.set_xticks(np.array(range(m)), labels=labels_x, rotation=45)
×
3063
        ax.set_yticks(np.array(range(n)), labels=labels_y, rotation=90)
×
3064

3065
    else:
3066
        raise ValueError(
×
3067
            f"The length of the dimensiondim ({z},{len(d)}) should be either 2 or 4. It represents the number of triangles."
3068
        )
3069

3070
    ax.set_title(get_attributes(use_attrs.get("title", None), data))
×
3071
    ax.set_xlabel(other_dims[0])
×
3072
    ax.set_ylabel(other_dims[1])
×
3073
    if "xlabel" in use_attrs:
×
3074
        ax.set_xlabel(get_attributes(use_attrs["xlabel"], data))
×
3075
    if "ylabel" in use_attrs:
×
3076
        ax.set_ylabel(get_attributes(use_attrs["ylabel"], data))
×
3077
    ax.set_aspect("equal", "box")
×
3078
    ax.invert_yaxis()
×
3079
    ax.tick_params(left=False, bottom=False)
×
3080
    ax.spines["bottom"].set_visible(False)
×
3081
    ax.spines["left"].set_visible(False)
×
3082

3083
    # create cbar label
3084
    # set default use_attrs values
3085
    use_attrs.setdefault("cbar_label", "long_name")
×
3086
    use_attrs.setdefault("cbar_units", "units")
×
3087
    if (
×
3088
        "cbar_units" in use_attrs
3089
        and len(get_attributes(use_attrs["cbar_units"], data)) >= 1
3090
    ):  # avoids '()' as label
3091
        cbar_label = (
×
3092
            get_attributes(use_attrs["cbar_label"], data)
3093
            + " ("
3094
            + get_attributes(use_attrs["cbar_units"], data)
3095
            + ")"
3096
        )
3097
    else:
3098
        cbar_label = get_attributes(use_attrs["cbar_label"], data)
×
3099

3100
    if isinstance(cbar_kw, dict):
×
3101
        cbar_kw.setdefault("label", cbar_label)
×
3102
        cbar_kw = [cbar_kw for _ in range(len(d))]
×
3103
    if cbar == "unique":
×
3104
        plt.colorbar(imgs[0], ax=ax, **cbar_kw[0])
×
3105

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

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

© 2025 Coveralls, Inc