forked from pydata/xarray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataarray_plot.py
More file actions
2476 lines (2210 loc) · 85 KB
/
dataarray_plot.py
File metadata and controls
2476 lines (2210 loc) · 85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import functools
import warnings
from collections.abc import Hashable, Iterable, MutableMapping
from typing import TYPE_CHECKING, Any, Callable, Literal, Union, cast, overload
import numpy as np
import pandas as pd
from xarray.core.alignment import broadcast
from xarray.core.concat import concat
from xarray.plot.facetgrid import _easy_facetgrid
from xarray.plot.utils import (
_LINEWIDTH_RANGE,
_MARKERSIZE_RANGE,
_add_colorbar,
_add_legend,
_assert_valid_xy,
_determine_guide,
_ensure_plottable,
_guess_coords_to_plot,
_infer_interval_breaks,
_infer_xy_labels,
_Normalize,
_process_cmap_cbar_kwargs,
_rescale_imshow_rgb,
_resolve_intervals_1dplot,
_resolve_intervals_2dplot,
_set_concise_date,
_update_axes,
get_axis,
label_from_attrs,
)
if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.collections import PathCollection, QuadMesh
from matplotlib.colors import Colormap, Normalize
from matplotlib.container import BarContainer
from matplotlib.contour import QuadContourSet
from matplotlib.image import AxesImage
from matplotlib.patches import Polygon
from mpl_toolkits.mplot3d.art3d import Line3D, Poly3DCollection
from numpy.typing import ArrayLike
from xarray.core.dataarray import DataArray
from xarray.core.types import (
AspectOptions,
ExtendOptions,
HueStyleOptions,
ScaleOptions,
T_DataArray,
)
from xarray.plot.facetgrid import FacetGrid
_styles: dict[str, Any] = {
# Add a white border to make it easier seeing overlapping markers:
"scatter.edgecolors": "w",
}
def _infer_line_data(
darray: DataArray, x: Hashable | None, y: Hashable | None, hue: Hashable | None
) -> tuple[DataArray, DataArray, DataArray | None, str]:
ndims = len(darray.dims)
if x is not None and y is not None:
raise ValueError("Cannot specify both x and y kwargs for line plots.")
if x is not None:
_assert_valid_xy(darray, x, "x")
if y is not None:
_assert_valid_xy(darray, y, "y")
if ndims == 1:
huename = None
hueplt = None
huelabel = ""
if x is not None:
xplt = darray[x]
yplt = darray
elif y is not None:
xplt = darray
yplt = darray[y]
else: # Both x & y are None
dim = darray.dims[0]
xplt = darray[dim]
yplt = darray
else:
if x is None and y is None and hue is None:
raise ValueError("For 2D inputs, please specify either hue, x or y.")
if y is None:
if hue is not None:
_assert_valid_xy(darray, hue, "hue")
xname, huename = _infer_xy_labels(darray=darray, x=x, y=hue)
xplt = darray[xname]
if xplt.ndim > 1:
if huename in darray.dims:
otherindex = 1 if darray.dims.index(huename) == 0 else 0
otherdim = darray.dims[otherindex]
yplt = darray.transpose(otherdim, huename, transpose_coords=False)
xplt = xplt.transpose(otherdim, huename, transpose_coords=False)
else:
raise ValueError(
"For 2D inputs, hue must be a dimension"
" i.e. one of " + repr(darray.dims)
)
else:
(xdim,) = darray[xname].dims
(huedim,) = darray[huename].dims
yplt = darray.transpose(xdim, huedim)
else:
yname, huename = _infer_xy_labels(darray=darray, x=y, y=hue)
yplt = darray[yname]
if yplt.ndim > 1:
if huename in darray.dims:
otherindex = 1 if darray.dims.index(huename) == 0 else 0
otherdim = darray.dims[otherindex]
xplt = darray.transpose(otherdim, huename, transpose_coords=False)
yplt = yplt.transpose(otherdim, huename, transpose_coords=False)
else:
raise ValueError(
"For 2D inputs, hue must be a dimension"
" i.e. one of " + repr(darray.dims)
)
else:
(ydim,) = darray[yname].dims
(huedim,) = darray[huename].dims
xplt = darray.transpose(ydim, huedim)
huelabel = label_from_attrs(darray[huename])
hueplt = darray[huename]
return xplt, yplt, hueplt, huelabel
def _prepare_plot1d_data(
darray: T_DataArray,
coords_to_plot: MutableMapping[str, Hashable],
plotfunc_name: str | None = None,
_is_facetgrid: bool = False,
) -> dict[str, T_DataArray]:
"""
Prepare data for usage with plt.scatter.
Parameters
----------
darray : T_DataArray
Base DataArray.
coords_to_plot : MutableMapping[str, Hashable]
Coords that will be plotted.
plotfunc_name : str | None
Name of the plotting function that will be used.
Returns
-------
plts : dict[str, T_DataArray]
Dict of DataArrays that will be sent to matplotlib.
Examples
--------
>>> # Make sure int coords are plotted:
>>> a = xr.DataArray(
... data=[1, 2],
... coords={1: ("x", [0, 1], {"units": "s"})},
... dims=("x",),
... name="a",
... )
>>> plts = xr.plot.dataarray_plot._prepare_plot1d_data(
... a, coords_to_plot={"x": 1, "z": None, "hue": None, "size": None}
... )
>>> # Check which coords to plot:
>>> print({k: v.name for k, v in plts.items()})
{'y': 'a', 'x': 1}
"""
# If there are more than 1 dimension in the array than stack all the
# dimensions so the plotter can plot anything:
if darray.ndim > 1:
# When stacking dims the lines will continue connecting. For floats
# this can be solved by adding a nan element in between the flattening
# points:
dims_T = []
if np.issubdtype(darray.dtype, np.floating):
for v in ["z", "x"]:
dim = coords_to_plot.get(v, None)
if (dim is not None) and (dim in darray.dims):
darray_nan = np.nan * darray.isel({dim: -1})
darray = concat([darray, darray_nan], dim=dim)
dims_T.append(coords_to_plot[v])
# Lines should never connect to the same coordinate when stacked,
# transpose to avoid this as much as possible:
darray = darray.transpose(..., *dims_T)
# Array is now ready to be stacked:
darray = darray.stack(_stacked_dim=darray.dims)
# Broadcast together all the chosen variables:
plts = dict(y=darray)
plts.update(
{k: darray.coords[v] for k, v in coords_to_plot.items() if v is not None}
)
plts = dict(zip(plts.keys(), broadcast(*(plts.values()))))
return plts
# return type is Any due to the many different possibilities
def plot(
darray: DataArray,
*,
row: Hashable | None = None,
col: Hashable | None = None,
col_wrap: int | None = None,
ax: Axes | None = None,
hue: Hashable | None = None,
subplot_kws: dict[str, Any] | None = None,
**kwargs: Any,
) -> Any:
"""
Default plot of DataArray using :py:mod:`matplotlib:matplotlib.pyplot`.
Calls xarray plotting function based on the dimensions of
the squeezed DataArray.
=============== ===========================
Dimensions Plotting function
=============== ===========================
1 :py:func:`xarray.plot.line`
2 :py:func:`xarray.plot.pcolormesh`
Anything else :py:func:`xarray.plot.hist`
=============== ===========================
Parameters
----------
darray : DataArray
row : Hashable or None, optional
If passed, make row faceted plots on this dimension name.
col : Hashable or None, optional
If passed, make column faceted plots on this dimension name.
col_wrap : int or None, optional
Use together with ``col`` to wrap faceted plots.
ax : matplotlib axes object, optional
Axes on which to plot. By default, use the current axes.
Mutually exclusive with ``size``, ``figsize`` and facets.
hue : Hashable or None, optional
If passed, make faceted line plots with hue on this dimension name.
subplot_kws : dict, optional
Dictionary of keyword arguments for Matplotlib subplots
(see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`).
**kwargs : optional
Additional keyword arguments for Matplotlib.
See Also
--------
xarray.DataArray.squeeze
"""
darray = darray.squeeze(
d for d, s in darray.sizes.items() if s == 1 and d not in (row, col, hue)
).compute()
plot_dims = set(darray.dims)
plot_dims.discard(row)
plot_dims.discard(col)
plot_dims.discard(hue)
ndims = len(plot_dims)
plotfunc: Callable
if ndims == 0 or darray.size == 0:
raise TypeError("No numeric data to plot.")
if ndims in (1, 2):
if row or col:
kwargs["subplot_kws"] = subplot_kws
kwargs["row"] = row
kwargs["col"] = col
kwargs["col_wrap"] = col_wrap
if ndims == 1:
plotfunc = line
kwargs["hue"] = hue
elif ndims == 2:
if hue:
plotfunc = line
kwargs["hue"] = hue
else:
plotfunc = pcolormesh
kwargs["subplot_kws"] = subplot_kws
else:
if row or col or hue:
raise ValueError(
"Only 1d and 2d plots are supported for facets in xarray. "
"See the package `Seaborn` for more options."
)
plotfunc = hist
kwargs["ax"] = ax
return plotfunc(darray, **kwargs)
@overload
def line( # type: ignore[misc,unused-ignore] # None is hashable :(
darray: DataArray,
*args: Any,
row: None = None, # no wrap -> primitive
col: None = None, # no wrap -> primitive
figsize: Iterable[float] | None = None,
aspect: AspectOptions = None,
size: float | None = None,
ax: Axes | None = None,
hue: Hashable | None = None,
x: Hashable | None = None,
y: Hashable | None = None,
xincrease: bool | None = None,
yincrease: bool | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
add_legend: bool = True,
_labels: bool = True,
**kwargs: Any,
) -> list[Line3D]:
...
@overload
def line(
darray: T_DataArray,
*args: Any,
row: Hashable, # wrap -> FacetGrid
col: Hashable | None = None,
figsize: Iterable[float] | None = None,
aspect: AspectOptions = None,
size: float | None = None,
ax: Axes | None = None,
hue: Hashable | None = None,
x: Hashable | None = None,
y: Hashable | None = None,
xincrease: bool | None = None,
yincrease: bool | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
add_legend: bool = True,
_labels: bool = True,
**kwargs: Any,
) -> FacetGrid[T_DataArray]:
...
@overload
def line(
darray: T_DataArray,
*args: Any,
row: Hashable | None = None,
col: Hashable, # wrap -> FacetGrid
figsize: Iterable[float] | None = None,
aspect: AspectOptions = None,
size: float | None = None,
ax: Axes | None = None,
hue: Hashable | None = None,
x: Hashable | None = None,
y: Hashable | None = None,
xincrease: bool | None = None,
yincrease: bool | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
add_legend: bool = True,
_labels: bool = True,
**kwargs: Any,
) -> FacetGrid[T_DataArray]:
...
# This function signature should not change so that it can use
# matplotlib format strings
def line(
darray: T_DataArray,
*args: Any,
row: Hashable | None = None,
col: Hashable | None = None,
figsize: Iterable[float] | None = None,
aspect: AspectOptions = None,
size: float | None = None,
ax: Axes | None = None,
hue: Hashable | None = None,
x: Hashable | None = None,
y: Hashable | None = None,
xincrease: bool | None = None,
yincrease: bool | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
add_legend: bool = True,
_labels: bool = True,
**kwargs: Any,
) -> list[Line3D] | FacetGrid[T_DataArray]:
"""
Line plot of DataArray values.
Wraps :py:func:`matplotlib:matplotlib.pyplot.plot`.
Parameters
----------
darray : DataArray
Either 1D or 2D. If 2D, one of ``hue``, ``x`` or ``y`` must be provided.
row : Hashable, optional
If passed, make row faceted plots on this dimension name.
col : Hashable, optional
If passed, make column faceted plots on this dimension name.
figsize : tuple, optional
A tuple (width, height) of the figure in inches.
Mutually exclusive with ``size`` and ``ax``.
aspect : "auto", "equal", scalar or None, optional
Aspect ratio of plot, so that ``aspect * size`` gives the *width* in
inches. Only used if a ``size`` is provided.
size : scalar, optional
If provided, create a new figure for the plot with the given size:
*height* (in inches) of each plot. See also: ``aspect``.
ax : matplotlib axes object, optional
Axes on which to plot. By default, the current is used.
Mutually exclusive with ``size`` and ``figsize``.
hue : Hashable, optional
Dimension or coordinate for which you want multiple lines plotted.
If plotting against a 2D coordinate, ``hue`` must be a dimension.
x, y : Hashable, optional
Dimension, coordinate or multi-index level for *x*, *y* axis.
Only one of these may be specified.
The other will be used for values from the DataArray on which this
plot method is called.
xincrease : bool or None, optional
Should the values on the *x* axis be increasing from left to right?
if ``None``, use the default for the Matplotlib function.
yincrease : bool or None, optional
Should the values on the *y* axis be increasing from top to bottom?
if ``None``, use the default for the Matplotlib function.
xscale, yscale : {'linear', 'symlog', 'log', 'logit'}, optional
Specifies scaling for the *x*- and *y*-axis, respectively.
xticks, yticks : array-like, optional
Specify tick locations for *x*- and *y*-axis.
xlim, ylim : tuple[float, float], optional
Specify *x*- and *y*-axis limits.
add_legend : bool, default: True
Add legend with *y* axis coordinates (2D inputs only).
*args, **kwargs : optional
Additional arguments to :py:func:`matplotlib:matplotlib.pyplot.plot`.
Returns
-------
primitive : list of Line3D or FacetGrid
When either col or row is given, returns a FacetGrid, otherwise
a list of matplotlib Line3D objects.
"""
# Handle facetgrids first
if row or col:
allargs = locals().copy()
allargs.update(allargs.pop("kwargs"))
allargs.pop("darray")
return _easy_facetgrid(darray, line, kind="line", **allargs)
ndims = len(darray.dims)
if ndims == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")
if ndims > 2:
raise ValueError(
"Line plots are for 1- or 2-dimensional DataArrays. "
f"Passed DataArray has {ndims} "
"dimensions"
)
# The allargs dict passed to _easy_facetgrid above contains args
if args == ():
args = kwargs.pop("args", ())
else:
assert "args" not in kwargs
ax = get_axis(figsize, size, aspect, ax)
xplt, yplt, hueplt, hue_label = _infer_line_data(darray, x, y, hue)
# Remove pd.Intervals if contained in xplt.values and/or yplt.values.
xplt_val, yplt_val, x_suffix, y_suffix, kwargs = _resolve_intervals_1dplot(
xplt.to_numpy(), yplt.to_numpy(), kwargs
)
xlabel = label_from_attrs(xplt, extra=x_suffix)
ylabel = label_from_attrs(yplt, extra=y_suffix)
_ensure_plottable(xplt_val, yplt_val)
primitive = ax.plot(xplt_val, yplt_val, *args, **kwargs)
if _labels:
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
ax.set_title(darray._title_for_slice())
if darray.ndim == 2 and add_legend:
assert hueplt is not None
ax.legend(handles=primitive, labels=list(hueplt.to_numpy()), title=hue_label)
if np.issubdtype(xplt.dtype, np.datetime64):
_set_concise_date(ax, axis="x")
_update_axes(ax, xincrease, yincrease, xscale, yscale, xticks, yticks, xlim, ylim)
return primitive
@overload
def step( # type: ignore[misc,unused-ignore] # None is hashable :(
darray: DataArray,
*args: Any,
where: Literal["pre", "post", "mid"] = "pre",
drawstyle: str | None = None,
ds: str | None = None,
row: None = None, # no wrap -> primitive
col: None = None, # no wrap -> primitive
**kwargs: Any,
) -> list[Line3D]:
...
@overload
def step(
darray: DataArray,
*args: Any,
where: Literal["pre", "post", "mid"] = "pre",
drawstyle: str | None = None,
ds: str | None = None,
row: Hashable, # wrap -> FacetGrid
col: Hashable | None = None,
**kwargs: Any,
) -> FacetGrid[DataArray]:
...
@overload
def step(
darray: DataArray,
*args: Any,
where: Literal["pre", "post", "mid"] = "pre",
drawstyle: str | None = None,
ds: str | None = None,
row: Hashable | None = None,
col: Hashable, # wrap -> FacetGrid
**kwargs: Any,
) -> FacetGrid[DataArray]:
...
def step(
darray: DataArray,
*args: Any,
where: Literal["pre", "post", "mid"] = "pre",
drawstyle: str | None = None,
ds: str | None = None,
row: Hashable | None = None,
col: Hashable | None = None,
**kwargs: Any,
) -> list[Line3D] | FacetGrid[DataArray]:
"""
Step plot of DataArray values.
Similar to :py:func:`matplotlib:matplotlib.pyplot.step`.
Parameters
----------
where : {'pre', 'post', 'mid'}, default: 'pre'
Define where the steps should be placed:
- ``'pre'``: The y value is continued constantly to the left from
every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
value ``y[i]``.
- ``'post'``: The y value is continued constantly to the right from
every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
value ``y[i]``.
- ``'mid'``: Steps occur half-way between the *x* positions.
Note that this parameter is ignored if one coordinate consists of
:py:class:`pandas.Interval` values, e.g. as a result of
:py:func:`xarray.Dataset.groupby_bins`. In this case, the actual
boundaries of the interval are used.
drawstyle, ds : str or None, optional
Additional drawstyle. Only use one of drawstyle and ds.
row : Hashable, optional
If passed, make row faceted plots on this dimension name.
col : Hashable, optional
If passed, make column faceted plots on this dimension name.
*args, **kwargs : optional
Additional arguments for :py:func:`xarray.plot.line`.
Returns
-------
primitive : list of Line3D or FacetGrid
When either col or row is given, returns a FacetGrid, otherwise
a list of matplotlib Line3D objects.
"""
if where not in {"pre", "post", "mid"}:
raise ValueError("'where' argument to step must be 'pre', 'post' or 'mid'")
if ds is not None:
if drawstyle is None:
drawstyle = ds
else:
raise TypeError("ds and drawstyle are mutually exclusive")
if drawstyle is None:
drawstyle = ""
drawstyle = "steps-" + where + drawstyle
return line(darray, *args, drawstyle=drawstyle, col=col, row=row, **kwargs)
def hist(
darray: DataArray,
*args: Any,
figsize: Iterable[float] | None = None,
size: float | None = None,
aspect: AspectOptions = None,
ax: Axes | None = None,
xincrease: bool | None = None,
yincrease: bool | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
**kwargs: Any,
) -> tuple[np.ndarray, np.ndarray, BarContainer | Polygon]:
"""
Histogram of DataArray.
Wraps :py:func:`matplotlib:matplotlib.pyplot.hist`.
Plots *N*-dimensional arrays by first flattening the array.
Parameters
----------
darray : DataArray
Can have any number of dimensions.
figsize : Iterable of float, optional
A tuple (width, height) of the figure in inches.
Mutually exclusive with ``size`` and ``ax``.
aspect : "auto", "equal", scalar or None, optional
Aspect ratio of plot, so that ``aspect * size`` gives the *width* in
inches. Only used if a ``size`` is provided.
size : scalar, optional
If provided, create a new figure for the plot with the given size:
*height* (in inches) of each plot. See also: ``aspect``.
ax : matplotlib axes object, optional
Axes on which to plot. By default, use the current axes.
Mutually exclusive with ``size`` and ``figsize``.
xincrease : bool or None, optional
Should the values on the *x* axis be increasing from left to right?
if ``None``, use the default for the Matplotlib function.
yincrease : bool or None, optional
Should the values on the *y* axis be increasing from top to bottom?
if ``None``, use the default for the Matplotlib function.
xscale, yscale : {'linear', 'symlog', 'log', 'logit'}, optional
Specifies scaling for the *x*- and *y*-axis, respectively.
xticks, yticks : array-like, optional
Specify tick locations for *x*- and *y*-axis.
xlim, ylim : tuple[float, float], optional
Specify *x*- and *y*-axis limits.
**kwargs : optional
Additional keyword arguments to :py:func:`matplotlib:matplotlib.pyplot.hist`.
"""
assert len(args) == 0
if darray.ndim == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")
ax = get_axis(figsize, size, aspect, ax)
no_nan = np.ravel(darray.to_numpy())
no_nan = no_nan[pd.notnull(no_nan)]
n, bins, patches = cast(
tuple[np.ndarray, np.ndarray, Union["BarContainer", "Polygon"]],
ax.hist(no_nan, **kwargs),
)
ax.set_title(darray._title_for_slice())
ax.set_xlabel(label_from_attrs(darray))
_update_axes(ax, xincrease, yincrease, xscale, yscale, xticks, yticks, xlim, ylim)
return n, bins, patches
def _plot1d(plotfunc):
"""Decorator for common 1d plotting logic."""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots.
x : Hashable or None, optional
Coordinate for x axis. If None use darray.dims[1].
y : Hashable or None, optional
Coordinate for y axis. If None use darray.dims[0].
z : Hashable or None, optional
If specified plot 3D and use this coordinate for *z* axis.
hue : Hashable or None, optional
Dimension or coordinate for which you want multiple lines plotted.
markersize: Hashable or None, optional
scatter only. Variable by which to vary size of scattered points.
linewidth: Hashable or None, optional
Variable by which to vary linewidth.
row : Hashable, optional
If passed, make row faceted plots on this dimension name.
col : Hashable, optional
If passed, make column faceted plots on this dimension name.
col_wrap : int, optional
Use together with ``col`` to wrap faceted plots
ax : matplotlib axes object, optional
If None, uses the current axis. Not applicable when using facets.
figsize : Iterable[float] or None, optional
A tuple (width, height) of the figure in inches.
Mutually exclusive with ``size`` and ``ax``.
size : scalar, optional
If provided, create a new figure for the plot with the given size.
Height (in inches) of each plot. See also: ``aspect``.
aspect : "auto", "equal", scalar or None, optional
Aspect ratio of plot, so that ``aspect * size`` gives the width in
inches. Only used if a ``size`` is provided.
xincrease : bool or None, default: True
Should the values on the x axes be increasing from left to right?
if None, use the default for the matplotlib function.
yincrease : bool or None, default: True
Should the values on the y axes be increasing from top to bottom?
if None, use the default for the matplotlib function.
add_legend : bool or None, optional
If True use xarray metadata to add a legend.
add_colorbar : bool or None, optional
If True add a colorbar.
add_labels : bool or None, optional
If True use xarray metadata to label axes
add_title : bool or None, optional
If True use xarray metadata to add a title
subplot_kws : dict, optional
Dictionary of keyword arguments for matplotlib subplots. Only applies
to FacetGrid plotting.
xscale : {'linear', 'symlog', 'log', 'logit'} or None, optional
Specifies scaling for the x-axes.
yscale : {'linear', 'symlog', 'log', 'logit'} or None, optional
Specifies scaling for the y-axes.
xticks : ArrayLike or None, optional
Specify tick locations for x-axes.
yticks : ArrayLike or None, optional
Specify tick locations for y-axes.
xlim : tuple[float, float] or None, optional
Specify x-axes limits.
ylim : tuple[float, float] or None, optional
Specify y-axes limits.
cmap : matplotlib colormap name or colormap, optional
The mapping from data values to color space. Either a
Matplotlib colormap name or object. If not provided, this will
be either ``'viridis'`` (if the function infers a sequential
dataset) or ``'RdBu_r'`` (if the function infers a diverging
dataset).
See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>`
for more information.
If *seaborn* is installed, ``cmap`` may also be a
`seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_.
Note: if ``cmap`` is a seaborn color palette,
``levels`` must also be specified.
vmin : float or None, optional
Lower value to anchor the colormap, otherwise it is inferred from the
data and other keyword arguments. When a diverging dataset is inferred,
setting `vmin` or `vmax` will fix the other by symmetry around
``center``. Setting both values prevents use of a diverging colormap.
If discrete levels are provided as an explicit list, both of these
values are ignored.
vmax : float or None, optional
Upper value to anchor the colormap, otherwise it is inferred from the
data and other keyword arguments. When a diverging dataset is inferred,
setting `vmin` or `vmax` will fix the other by symmetry around
``center``. Setting both values prevents use of a diverging colormap.
If discrete levels are provided as an explicit list, both of these
values are ignored.
norm : matplotlib.colors.Normalize, optional
If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding
kwarg must be ``None``.
extend : {'neither', 'both', 'min', 'max'}, optional
How to draw arrows extending the colorbar beyond its limits. If not
provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits.
levels : int or array-like, optional
Split the colormap (``cmap``) into discrete color intervals. If an integer
is provided, "nice" levels are chosen based on the data range: this can
imply that the final number of levels is not exactly the expected one.
Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to
setting ``levels=np.linspace(vmin, vmax, N)``.
**kwargs : optional
Additional arguments to wrapped matplotlib function
Returns
-------
artist :
The same type of primitive artist that the wrapped matplotlib
function returns
"""
# Build on the original docstring
plotfunc.__doc__ = f"{plotfunc.__doc__}\n{commondoc}"
@functools.wraps(
plotfunc, assigned=("__module__", "__name__", "__qualname__", "__doc__")
)
def newplotfunc(
darray: DataArray,
*args: Any,
x: Hashable | None = None,
y: Hashable | None = None,
z: Hashable | None = None,
hue: Hashable | None = None,
hue_style: HueStyleOptions = None,
markersize: Hashable | None = None,
linewidth: Hashable | None = None,
row: Hashable | None = None,
col: Hashable | None = None,
col_wrap: int | None = None,
ax: Axes | None = None,
figsize: Iterable[float] | None = None,
size: float | None = None,
aspect: float | None = None,
xincrease: bool | None = True,
yincrease: bool | None = True,
add_legend: bool | None = None,
add_colorbar: bool | None = None,
add_labels: bool | Iterable[bool] = True,
add_title: bool = True,
subplot_kws: dict[str, Any] | None = None,
xscale: ScaleOptions = None,
yscale: ScaleOptions = None,
xticks: ArrayLike | None = None,
yticks: ArrayLike | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
cmap: str | Colormap | None = None,
vmin: float | None = None,
vmax: float | None = None,
norm: Normalize | None = None,
extend: ExtendOptions = None,
levels: ArrayLike | None = None,
**kwargs,
) -> Any:
# All 1d plots in xarray share this function signature.
# Method signature below should be consistent.
import matplotlib.pyplot as plt
if subplot_kws is None:
subplot_kws = dict()
# Handle facetgrids first
if row or col:
if z is not None:
subplot_kws.update(projection="3d")
allargs = locals().copy()
allargs.update(allargs.pop("kwargs"))
allargs.pop("darray")
allargs.pop("plt")
allargs["plotfunc"] = globals()[plotfunc.__name__]
return _easy_facetgrid(darray, kind="plot1d", **allargs)
if darray.ndim == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")
# The allargs dict passed to _easy_facetgrid above contains args
if args == ():
args = kwargs.pop("args", ())
if args:
assert "args" not in kwargs
# TODO: Deprecated since 2022.10:
msg = "Using positional arguments is deprecated for plot methods, use keyword arguments instead."
assert x is None
x = args[0]
if len(args) > 1:
assert y is None
y = args[1]
if len(args) > 2:
assert z is None
z = args[2]
if len(args) > 3:
assert hue is None
hue = args[3]
if len(args) > 4:
raise ValueError(msg)
else:
warnings.warn(msg, DeprecationWarning, stacklevel=2)
del args
if hue_style is not None:
# TODO: Not used since 2022.10. Deprecated since 2023.07.
warnings.warn(
(
"hue_style is no longer used for plot1d plots "
"and the argument will eventually be removed. "
"Convert numbers to string for a discrete hue "
"and use add_legend or add_colorbar to control which guide to display."
),
DeprecationWarning,
stacklevel=2,
)
_is_facetgrid = kwargs.pop("_is_facetgrid", False)
if plotfunc.__name__ == "scatter":
size_ = kwargs.pop("_size", markersize)
size_r = _MARKERSIZE_RANGE
# Remove any nulls, .where(m, drop=True) doesn't work when m is
# a dask array, so load the array to memory.
# It will have to be loaded to memory at some point anyway:
darray = darray.load()
darray = darray.where(darray.notnull(), drop=True)
else:
size_ = kwargs.pop("_size", linewidth)
size_r = _LINEWIDTH_RANGE
# Get data to plot:
coords_to_plot: MutableMapping[str, Hashable | None] = dict(
x=x, z=z, hue=hue, size=size_
)
if not _is_facetgrid:
# Guess what coords to use if some of the values in coords_to_plot are None:
coords_to_plot = _guess_coords_to_plot(darray, coords_to_plot, kwargs)
plts = _prepare_plot1d_data(darray, coords_to_plot, plotfunc.__name__)
xplt = plts.pop("x", None)
yplt = plts.pop("y", None)
zplt = plts.pop("z", None)
kwargs.update(zplt=zplt)
hueplt = plts.pop("hue", None)
sizeplt = plts.pop("size", None)
# Handle size and hue:
hueplt_norm = _Normalize(data=hueplt)
kwargs.update(hueplt=hueplt_norm.values)
sizeplt_norm = _Normalize(
data=sizeplt, width=size_r, _is_facetgrid=_is_facetgrid
)
kwargs.update(sizeplt=sizeplt_norm.values)
cmap_params_subset = kwargs.pop("cmap_params_subset", {})
cbar_kwargs = kwargs.pop("cbar_kwargs", {})
if hueplt_norm.data is not None:
if not hueplt_norm.data_is_numeric:
# Map hue values back to its original value:
cbar_kwargs.update(format=hueplt_norm.format, ticks=hueplt_norm.ticks)
levels = kwargs.get("levels", hueplt_norm.levels)
cmap_params, cbar_kwargs = _process_cmap_cbar_kwargs(
plotfunc,
cast("DataArray", hueplt_norm.values).data,
**locals(),
)
# subset that can be passed to scatter, hist2d
if not cmap_params_subset:
ckw = {vv: cmap_params[vv] for vv in ("vmin", "vmax", "norm", "cmap")}
cmap_params_subset.update(**ckw)
with plt.rc_context(_styles):
if z is not None: