-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtest_plot.py
More file actions
3569 lines (2950 loc) · 129 KB
/
test_plot.py
File metadata and controls
3569 lines (2950 loc) · 129 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 contextlib
import inspect
import math
from collections.abc import Callable, Generator, Hashable
from copy import copy
from datetime import date, timedelta
from typing import Any, Literal, cast
import numpy as np
import pandas as pd
import pytest
import xarray as xr
import xarray.plot as xplt
from xarray import DataArray, Dataset
from xarray.namedarray.utils import module_available
from xarray.plot.dataarray_plot import _infer_interval_breaks
from xarray.plot.dataset_plot import _infer_meta_data
from xarray.plot.utils import (
_assert_valid_xy,
_build_discrete_cmap,
_color_palette,
_determine_cmap_params,
_maybe_gca,
get_axis,
label_from_attrs,
)
from xarray.tests import (
assert_array_equal,
assert_equal,
assert_no_warnings,
requires_cartopy,
requires_cftime,
requires_dask,
requires_matplotlib,
requires_seaborn,
)
# this should not be imported to test if the automatic lazy import works
has_nc_time_axis = module_available("nc_time_axis")
# import mpl and change the backend before other mpl imports
try:
import matplotlib as mpl
import matplotlib.dates
import matplotlib.pyplot as plt
import mpl_toolkits
except ImportError:
pass
with contextlib.suppress(ImportError):
import cartopy
@contextlib.contextmanager
def figure_context(*args, **kwargs):
"""context manager which autocloses a figure (even if the test failed)"""
try:
yield None
finally:
plt.close("all")
@pytest.fixture(autouse=True)
def test_all_figures_closed():
"""meta-test to ensure all figures are closed at the end of a test
Notes: Scope is kept to module (only invoke this function once per test
module) else tests cannot be run in parallel (locally). Disadvantage: only
catches one open figure per run. May still give a false positive if tests
are run in parallel.
"""
yield None
open_figs = len(plt.get_fignums())
if open_figs:
raise RuntimeError(
f"tests did not close all figures ({open_figs} figures open)"
)
@pytest.mark.flaky
@pytest.mark.skip(reason="maybe flaky")
def text_in_fig() -> set[str]:
"""
Return the set of all text in the figure
"""
return {t.get_text() for t in plt.gcf().findobj(mpl.text.Text)}
def find_possible_colorbars() -> list[mpl.collections.QuadMesh]:
# nb. this function also matches meshes from pcolormesh
return plt.gcf().findobj(mpl.collections.QuadMesh)
def substring_in_axes(substring: str, ax: mpl.axes.Axes) -> bool:
"""
Return True if a substring is found anywhere in an axes
"""
alltxt: set[str] = {t.get_text() for t in ax.findobj(mpl.text.Text)}
return any(substring in txt for txt in alltxt)
def substring_not_in_axes(substring: str, ax: mpl.axes.Axes) -> bool:
"""
Return True if a substring is not found anywhere in an axes
"""
alltxt: set[str] = {t.get_text() for t in ax.findobj(mpl.text.Text)}
check = [(substring not in txt) for txt in alltxt]
return all(check)
def property_in_axes_text(
property, property_str, target_txt, ax: mpl.axes.Axes
) -> bool:
"""
Return True if the specified text in an axes
has the property assigned to property_str
"""
alltxt: list[mpl.text.Text] = ax.findobj(mpl.text.Text)
return all(
plt.getp(t, property) == property_str
for t in alltxt
if t.get_text() == target_txt
)
def easy_array(shape: tuple[int, ...], start: float = 0, stop: float = 1) -> np.ndarray:
"""
Make an array with desired shape using np.linspace
shape is a tuple like (2, 3)
"""
a = np.linspace(start, stop, num=math.prod(shape))
return a.reshape(shape)
def get_colorbar_label(colorbar) -> str:
if colorbar.orientation == "vertical":
return colorbar.ax.get_ylabel()
else:
return colorbar.ax.get_xlabel()
@requires_matplotlib
class PlotTestCase:
@pytest.fixture(autouse=True)
def setup(self) -> Generator:
yield
# Remove all matplotlib figures
plt.close("all")
def pass_in_axis(self, plotmethod, subplot_kw=None) -> None:
_fig, axs = plt.subplots(ncols=2, subplot_kw=subplot_kw, squeeze=False)
ax = axs[0, 0]
plotmethod(ax=ax)
assert ax.has_data()
@pytest.mark.slow
def imshow_called(self, plotmethod) -> bool:
plotmethod()
images = plt.gca().findobj(mpl.image.AxesImage)
return len(images) > 0
def contourf_called(self, plotmethod) -> bool:
plotmethod()
# Compatible with mpl before (PathCollection) and after (QuadContourSet) 3.8
def matchfunc(x) -> bool:
return isinstance(
x, mpl.collections.PathCollection | mpl.contour.QuadContourSet
)
paths = plt.gca().findobj(matchfunc)
return len(paths) > 0
class TestPlot(PlotTestCase):
@pytest.fixture(autouse=True)
def setup_array(self) -> None:
self.darray = DataArray(easy_array((2, 3, 4)))
def test_accessor(self) -> None:
from xarray.plot.accessor import DataArrayPlotAccessor
assert DataArray.plot is DataArrayPlotAccessor
assert isinstance(self.darray.plot, DataArrayPlotAccessor)
def test_label_from_attrs(self) -> None:
da = self.darray.copy()
assert "" == label_from_attrs(da)
da.name = 0
assert "0" == label_from_attrs(da)
da.name = "a"
da.attrs["units"] = "a_units"
da.attrs["long_name"] = "a_long_name"
da.attrs["standard_name"] = "a_standard_name"
assert "a_long_name [a_units]" == label_from_attrs(da)
da.attrs.pop("long_name")
assert "a_standard_name [a_units]" == label_from_attrs(da)
da.attrs.pop("units")
assert "a_standard_name" == label_from_attrs(da)
da.attrs["units"] = "a_units"
da.attrs.pop("standard_name")
assert "a [a_units]" == label_from_attrs(da)
da.attrs.pop("units")
assert "a" == label_from_attrs(da)
# Latex strings can be longer without needing a new line:
long_latex_name = r"$Ra_s = \mathrm{mean}(\epsilon_k) / \mu M^2_\infty$"
da.attrs = dict(long_name=long_latex_name)
assert label_from_attrs(da) == long_latex_name
def test1d(self) -> None:
self.darray[:, 0, 0].plot() # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"x must be one of None, 'dim_0'"):
self.darray[:, 0, 0].plot(x="dim_1") # type: ignore[call-arg]
with pytest.raises(TypeError, match=r"complex128"):
(self.darray[:, 0, 0] + 1j).plot() # type: ignore[call-arg]
def test_1d_bool(self) -> None:
xr.ones_like(self.darray[:, 0, 0], dtype=bool).plot() # type: ignore[call-arg]
def test_1d_x_y_kw(self) -> None:
z = np.arange(10)
da = DataArray(np.cos(z), dims=["z"], coords=[z], name="f")
xy: list[list[str | None]] = [[None, None], [None, "z"], ["z", None]]
_f, axs = plt.subplots(3, 1, squeeze=False)
for aa, (x, y) in enumerate(xy):
da.plot(x=x, y=y, ax=axs.flat[aa]) # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"Cannot specify both"):
da.plot(x="z", y="z") # type: ignore[call-arg]
error_msg = "must be one of None, 'z'"
with pytest.raises(ValueError, match=rf"x {error_msg}"):
da.plot(x="f") # type: ignore[call-arg]
with pytest.raises(ValueError, match=rf"y {error_msg}"):
da.plot(y="f") # type: ignore[call-arg]
def test_multiindex_level_as_coord(self) -> None:
da = xr.DataArray(
np.arange(5),
dims="x",
coords=dict(a=("x", np.arange(5)), b=("x", np.arange(5, 10))),
)
da = da.set_index(x=["a", "b"])
for x in ["a", "b"]:
h = da.plot(x=x)[0] # type: ignore[call-arg]
assert_array_equal(h.get_xdata(), da[x].values)
for y in ["a", "b"]:
h = da.plot(y=y)[0] # type: ignore[call-arg]
assert_array_equal(h.get_ydata(), da[y].values)
# Test for bug in GH issue #2725
def test_infer_line_data(self) -> None:
current = DataArray(
name="I",
data=np.array([5, 8]),
dims=["t"],
coords={
"t": (["t"], np.array([0.1, 0.2])),
"V": (["t"], np.array([100, 200])),
},
)
# Plot current against voltage
line = current.plot.line(x="V")[0]
assert_array_equal(line.get_xdata(), current.coords["V"].values)
# Plot current against time
line = current.plot.line()[0]
assert_array_equal(line.get_xdata(), current.coords["t"].values)
def test_line_plot_along_1d_coord(self) -> None:
# Test for bug in GH #3334
x_coord = xr.DataArray(data=[0.1, 0.2], dims=["x"])
t_coord = xr.DataArray(data=[10, 20], dims=["t"])
da = xr.DataArray(
data=np.array([[0, 1], [5, 9]]),
dims=["x", "t"],
coords={"x": x_coord, "time": t_coord},
)
line = da.plot(x="time", hue="x")[0] # type: ignore[call-arg]
assert_array_equal(line.get_xdata(), da.coords["time"].values)
line = da.plot(y="time", hue="x")[0] # type: ignore[call-arg]
assert_array_equal(line.get_ydata(), da.coords["time"].values)
def test_line_plot_wrong_hue(self) -> None:
da = xr.DataArray(
data=np.array([[0, 1], [5, 9]]),
dims=["x", "t"],
)
with pytest.raises(ValueError, match="hue must be one of"):
da.plot(x="t", hue="wrong_coord") # type: ignore[call-arg]
def test_2d_line(self) -> None:
with pytest.raises(ValueError, match=r"hue"):
self.darray[:, :, 0].plot.line()
self.darray[:, :, 0].plot.line(hue="dim_1")
self.darray[:, :, 0].plot.line(x="dim_1")
self.darray[:, :, 0].plot.line(y="dim_1")
self.darray[:, :, 0].plot.line(x="dim_0", hue="dim_1")
self.darray[:, :, 0].plot.line(y="dim_0", hue="dim_1")
with pytest.raises(ValueError, match=r"Cannot"):
self.darray[:, :, 0].plot.line(x="dim_1", y="dim_0", hue="dim_1")
def test_2d_line_accepts_legend_kw(self) -> None:
self.darray[:, :, 0].plot.line(x="dim_0", add_legend=False)
assert not plt.gca().get_legend()
plt.cla()
self.darray[:, :, 0].plot.line(x="dim_0", add_legend=True)
legend = plt.gca().get_legend()
assert legend is not None
# check whether legend title is set
assert legend.get_title().get_text() == "dim_1"
def test_2d_line_accepts_x_kw(self) -> None:
self.darray[:, :, 0].plot.line(x="dim_0")
assert plt.gca().get_xlabel() == "dim_0"
plt.cla()
self.darray[:, :, 0].plot.line(x="dim_1")
assert plt.gca().get_xlabel() == "dim_1"
def test_2d_line_accepts_hue_kw(self) -> None:
self.darray[:, :, 0].plot.line(hue="dim_0")
legend = plt.gca().get_legend()
assert legend is not None
assert legend.get_title().get_text() == "dim_0"
plt.cla()
self.darray[:, :, 0].plot.line(hue="dim_1")
legend = plt.gca().get_legend()
assert legend is not None
assert legend.get_title().get_text() == "dim_1"
def test_2d_coords_line_plot(self) -> None:
lon, lat = np.meshgrid(np.linspace(-20, 20, 5), np.linspace(0, 30, 4))
lon += lat / 10
lat += lon / 10
da = xr.DataArray(
np.arange(20).reshape(4, 5),
dims=["y", "x"],
coords={"lat": (("y", "x"), lat), "lon": (("y", "x"), lon)},
)
with figure_context():
hdl = da.plot.line(x="lon", hue="x")
assert len(hdl) == 5
with figure_context():
hdl = da.plot.line(x="lon", hue="y")
assert len(hdl) == 4
with pytest.raises(ValueError, match="For 2D inputs, hue must be a dimension"):
da.plot.line(x="lon", hue="lat")
def test_2d_coord_line_plot_coords_transpose_invariant(self) -> None:
# checks for bug reported in GH #3933
x = np.arange(10)
y = np.arange(20)
ds = xr.Dataset(coords={"x": x, "y": y})
for z in [ds.y + ds.x, ds.x + ds.y]:
ds = ds.assign_coords(z=z)
ds["v"] = ds.x + ds.y
ds["v"].plot.line(y="z", hue="x")
def test_2d_before_squeeze(self) -> None:
a = DataArray(easy_array((1, 5)))
a.plot() # type: ignore[call-arg]
def test2d_uniform_calls_imshow(self) -> None:
assert self.imshow_called(self.darray[:, :, 0].plot.imshow)
@pytest.mark.slow
def test2d_nonuniform_calls_contourf(self) -> None:
a = self.darray[:, :, 0]
a.coords["dim_1"] = [2, 1, 89]
assert self.contourf_called(a.plot.contourf)
def test2d_1d_2d_coordinates_contourf(self) -> None:
sz = (20, 10)
depth = easy_array(sz)
a = DataArray(
easy_array(sz),
dims=["z", "time"],
coords={"depth": (["z", "time"], depth), "time": np.linspace(0, 1, sz[1])},
)
a.plot.contourf(x="time", y="depth")
a.plot.contourf(x="depth", y="time")
def test2d_1d_2d_coordinates_pcolormesh(self) -> None:
# Test with equal coordinates to catch bug from #5097
sz = 10
y2d, x2d = np.meshgrid(np.arange(sz), np.arange(sz))
a = DataArray(
easy_array((sz, sz)),
dims=["x", "y"],
coords={"x2d": (["x", "y"], x2d), "y2d": (["x", "y"], y2d)},
)
for x, y in [
("x", "y"),
("y", "x"),
("x2d", "y"),
("y", "x2d"),
("x", "y2d"),
("y2d", "x"),
("x2d", "y2d"),
("y2d", "x2d"),
]:
p = a.plot.pcolormesh(x=x, y=y)
v = p.get_paths()[0].vertices
assert isinstance(v, np.ndarray)
# Check all vertices are different, except last vertex which should be the
# same as the first
_, unique_counts = np.unique(v[:-1], axis=0, return_counts=True)
assert np.all(unique_counts == 1)
def test_str_coordinates_pcolormesh(self) -> None:
# test for #6775
x = DataArray(
[[1, 2, 3], [4, 5, 6]],
dims=("a", "b"),
coords={"a": [1, 2], "b": ["a", "b", "c"]},
)
x.plot.pcolormesh()
x.T.plot.pcolormesh()
def test_contourf_cmap_set(self) -> None:
a = DataArray(easy_array((4, 4)), dims=["z", "time"])
cmap_expected = mpl.colormaps["viridis"]
# use copy to ensure cmap is not changed by contourf()
# Set vmin and vmax so that _build_discrete_colormap is called with
# extend='both'. extend is passed to
# mpl.colors.from_levels_and_colors(), which returns a result with
# sensible under and over values if extend='both', but not if
# extend='neither' (but if extend='neither' the under and over values
# would not be used because the data would all be within the plotted
# range)
pl = a.plot.contourf(cmap=copy(cmap_expected), vmin=0.1, vmax=0.9)
# check the set_bad color
cmap = pl.cmap
assert cmap is not None
assert_array_equal(
cmap(np.ma.masked_invalid([np.nan]))[0],
cmap_expected(np.ma.masked_invalid([np.nan]))[0],
)
# check the set_under color
assert cmap(-np.inf) == cmap_expected(-np.inf)
# check the set_over color
assert cmap(np.inf) == cmap_expected(np.inf)
def test_contourf_cmap_set_with_bad_under_over(self) -> None:
a = DataArray(easy_array((4, 4)), dims=["z", "time"])
# make a copy using with_extremes because we want a local cmap:
cmap_expected = mpl.colormaps["viridis"].with_extremes(
bad="w", under="r", over="g"
)
# check we actually changed the set_bad color
assert np.all(
cmap_expected(np.ma.masked_invalid([np.nan]))[0]
!= mpl.colormaps["viridis"](np.ma.masked_invalid([np.nan]))[0]
)
# check we actually changed the set_under color
assert cmap_expected(-np.inf) != mpl.colormaps["viridis"](-np.inf)
# check we actually changed the set_over color
assert cmap_expected(np.inf) != mpl.colormaps["viridis"](-np.inf)
# copy to ensure cmap is not changed by contourf()
pl = a.plot.contourf(cmap=copy(cmap_expected))
cmap = pl.cmap
assert cmap is not None
# check the set_bad color has been kept
assert_array_equal(
cmap(np.ma.masked_invalid([np.nan]))[0],
cmap_expected(np.ma.masked_invalid([np.nan]))[0],
)
# check the set_under color has been kept
assert cmap(-np.inf) == cmap_expected(-np.inf)
# check the set_over color has been kept
assert cmap(np.inf) == cmap_expected(np.inf)
def test3d(self) -> None:
self.darray.plot() # type: ignore[call-arg]
def test_can_pass_in_axis(self) -> None:
self.pass_in_axis(self.darray.plot)
def test__infer_interval_breaks(self) -> None:
assert_array_equal([-0.5, 0.5, 1.5], _infer_interval_breaks([0, 1]))
assert_array_equal(
[-0.5, 0.5, 5.0, 9.5, 10.5], _infer_interval_breaks([0, 1, 9, 10])
)
assert_array_equal(
pd.date_range("20000101", periods=4) - np.timedelta64(12, "h"),
_infer_interval_breaks(pd.date_range("20000101", periods=3)),
)
# make a bounded 2D array that we will center and re-infer
xref, yref = np.meshgrid(np.arange(6), np.arange(5))
cx = (xref[1:, 1:] + xref[:-1, :-1]) / 2
cy = (yref[1:, 1:] + yref[:-1, :-1]) / 2
x = _infer_interval_breaks(cx, axis=1)
x = _infer_interval_breaks(x, axis=0)
y = _infer_interval_breaks(cy, axis=1)
y = _infer_interval_breaks(y, axis=0)
np.testing.assert_allclose(xref, x)
np.testing.assert_allclose(yref, y)
# test that ValueError is raised for non-monotonic 1D inputs
with pytest.raises(ValueError):
_infer_interval_breaks(np.array([0, 2, 1]), check_monotonic=True)
def test__infer_interval_breaks_logscale(self) -> None:
"""
Check if interval breaks are defined in the logspace if scale="log"
"""
# Check for 1d arrays
x = np.logspace(-4, 3, 8)
expected_interval_breaks = 10 ** np.linspace(-4.5, 3.5, 9)
np.testing.assert_allclose(
_infer_interval_breaks(x, scale="log"), expected_interval_breaks
)
# Check for 2d arrays
x = np.logspace(-4, 3, 8)
y = np.linspace(-5, 5, 11)
x, y = np.meshgrid(x, y)
expected_interval_breaks = np.vstack([10 ** np.linspace(-4.5, 3.5, 9)] * 12)
x = _infer_interval_breaks(x, axis=1, scale="log")
x = _infer_interval_breaks(x, axis=0, scale="log")
np.testing.assert_allclose(x, expected_interval_breaks)
def test__infer_interval_breaks_logscale_invalid_coords(self) -> None:
"""
Check error is raised when passing non-positive coordinates with logscale
"""
# Check if error is raised after a zero value in the array
x = np.linspace(0, 5, 6)
with pytest.raises(ValueError):
_infer_interval_breaks(x, scale="log")
# Check if error is raised after negative values in the array
x = np.linspace(-5, 5, 11)
with pytest.raises(ValueError):
_infer_interval_breaks(x, scale="log")
def test_geo_data(self) -> None:
# Regression test for gh2250
# Realistic coordinates taken from the example dataset
lat = np.array(
[
[16.28, 18.48, 19.58, 19.54, 18.35],
[28.07, 30.52, 31.73, 31.68, 30.37],
[39.65, 42.27, 43.56, 43.51, 42.11],
[50.52, 53.22, 54.55, 54.50, 53.06],
]
)
lon = np.array(
[
[-126.13, -113.69, -100.92, -88.04, -75.29],
[-129.27, -115.62, -101.54, -87.32, -73.26],
[-133.10, -118.00, -102.31, -86.42, -70.76],
[-137.85, -120.99, -103.28, -85.28, -67.62],
]
)
data = np.hypot(lon, lat)
da = DataArray(
data,
dims=("y", "x"),
coords={"lon": (("y", "x"), lon), "lat": (("y", "x"), lat)},
)
da.plot(x="lon", y="lat") # type: ignore[call-arg]
ax = plt.gca()
assert ax.has_data()
da.plot(x="lat", y="lon") # type: ignore[call-arg]
ax = plt.gca()
assert ax.has_data()
def test_datetime_dimension(self) -> None:
nrow = 3
ncol = 4
time = pd.date_range("2000-01-01", periods=nrow)
a = DataArray(
easy_array((nrow, ncol)), coords=[("time", time), ("y", range(ncol))]
)
a.plot() # type: ignore[call-arg]
ax = plt.gca()
assert ax.has_data()
def test_date_dimension(self) -> None:
nrow = 3
ncol = 4
start = date(2000, 1, 1)
time = [start + timedelta(days=i) for i in range(nrow)]
a = DataArray(
easy_array((nrow, ncol)), coords=[("time", time), ("y", range(ncol))]
)
a.plot() # type: ignore[call-arg]
ax = plt.gca()
assert ax.has_data()
@pytest.mark.slow
@pytest.mark.filterwarnings("ignore:tight_layout cannot")
def test_convenient_facetgrid(self) -> None:
a = easy_array((10, 15, 4))
d = DataArray(a, dims=["y", "x", "z"])
d.coords["z"] = list("abcd")
g = d.plot(x="x", y="y", col="z", col_wrap=2, cmap="cool") # type: ignore[call-arg]
assert_array_equal(g.axs.shape, [2, 2])
for ax in g.axs.flat:
assert ax.has_data()
with pytest.raises(ValueError, match=r"[Ff]acet"):
d.plot(x="x", y="y", col="z", ax=plt.gca()) # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"[Ff]acet"):
d[0].plot(x="x", y="y", col="z", ax=plt.gca()) # type: ignore[call-arg]
@pytest.mark.slow
def test_subplot_kws(self) -> None:
a = easy_array((10, 15, 4))
d = DataArray(a, dims=["y", "x", "z"])
d.coords["z"] = list("abcd")
g = d.plot( # type: ignore[call-arg]
x="x",
y="y",
col="z",
col_wrap=2,
cmap="cool",
subplot_kws=dict(facecolor="r"),
)
for ax in g.axs.flat:
# mpl V2
assert ax.get_facecolor()[0:3] == mpl.colors.to_rgb("r")
@pytest.mark.slow
def test_plot_size(self) -> None:
self.darray[:, 0, 0].plot(figsize=(13, 5)) # type: ignore[call-arg]
assert tuple(plt.gcf().get_size_inches()) == (13, 5)
self.darray.plot(figsize=(13, 5)) # type: ignore[call-arg]
assert tuple(plt.gcf().get_size_inches()) == (13, 5)
self.darray.plot(size=5) # type: ignore[call-arg]
assert plt.gcf().get_size_inches()[1] == 5
self.darray.plot(size=5, aspect=2) # type: ignore[call-arg]
assert tuple(plt.gcf().get_size_inches()) == (10, 5)
with pytest.raises(ValueError, match=r"cannot provide both"):
self.darray.plot(ax=plt.gca(), figsize=(3, 4)) # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"cannot provide both"):
self.darray.plot(size=5, figsize=(3, 4)) # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"cannot provide both"):
self.darray.plot(size=5, ax=plt.gca()) # type: ignore[call-arg]
with pytest.raises(ValueError, match=r"cannot provide `aspect`"):
self.darray.plot(aspect=1) # type: ignore[call-arg]
@pytest.mark.slow
@pytest.mark.filterwarnings("ignore:tight_layout cannot")
def test_convenient_facetgrid_4d(self) -> None:
a = easy_array((10, 15, 2, 3))
d = DataArray(a, dims=["y", "x", "columns", "rows"])
g = d.plot(x="x", y="y", col="columns", row="rows") # type: ignore[call-arg]
assert_array_equal(g.axs.shape, [3, 2])
for ax in g.axs.flat:
assert ax.has_data()
with pytest.raises(ValueError, match=r"[Ff]acet"):
d.plot(x="x", y="y", col="columns", ax=plt.gca()) # type: ignore[call-arg]
def test_coord_with_interval(self) -> None:
"""Test line plot with intervals."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot() # type: ignore[call-arg]
def test_coord_with_interval_x(self) -> None:
"""Test line plot with intervals explicitly on x axis."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot(x="dim_0_bins") # type: ignore[call-arg]
def test_coord_with_interval_y(self) -> None:
"""Test line plot with intervals explicitly on y axis."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot(y="dim_0_bins") # type: ignore[call-arg]
def test_coord_with_interval_xy(self) -> None:
"""Test line plot with intervals on both x and y axes."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).dim_0_bins.plot()
@pytest.mark.parametrize("dim", ("x", "y"))
def test_labels_with_units_with_interval(self, dim) -> None:
"""Test line plot with intervals and a units attribute."""
bins = [-1, 0, 1, 2]
arr = self.darray.groupby_bins("dim_0", bins).mean(...)
arr.dim_0_bins.attrs["units"] = "m"
(mappable,) = arr.plot(**{dim: "dim_0_bins"}) # type: ignore[arg-type]
ax = mappable.figure.gca()
actual = getattr(ax, f"get_{dim}label")()
expected = "dim_0_bins_center [m]"
assert actual == expected
def test_multiplot_over_length_one_dim(self) -> None:
a = easy_array((3, 1, 1, 1))
d = DataArray(a, dims=("x", "col", "row", "hue"))
d.plot(col="col") # type: ignore[call-arg]
d.plot(row="row") # type: ignore[call-arg]
d.plot(hue="hue") # type: ignore[call-arg]
class TestPlot1D(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
d = [0, 1.1, 0, 2]
self.darray = DataArray(d, coords={"period": range(len(d))}, dims="period")
self.darray.period.attrs["units"] = "s"
def test_xlabel_is_index_name(self) -> None:
self.darray.plot() # type: ignore[call-arg]
assert "period [s]" == plt.gca().get_xlabel()
def test_no_label_name_on_x_axis(self) -> None:
self.darray.plot(y="period") # type: ignore[call-arg]
assert "" == plt.gca().get_xlabel()
def test_no_label_name_on_y_axis(self) -> None:
self.darray.plot() # type: ignore[call-arg]
assert "" == plt.gca().get_ylabel()
def test_ylabel_is_data_name(self) -> None:
self.darray.name = "temperature"
self.darray.attrs["units"] = "degrees_Celsius"
self.darray.plot() # type: ignore[call-arg]
assert "temperature [degrees_Celsius]" == plt.gca().get_ylabel()
def test_xlabel_is_data_name(self) -> None:
self.darray.name = "temperature"
self.darray.attrs["units"] = "degrees_Celsius"
self.darray.plot(y="period") # type: ignore[call-arg]
assert "temperature [degrees_Celsius]" == plt.gca().get_xlabel()
def test_format_string(self) -> None:
self.darray.plot.line("ro")
def test_can_pass_in_axis(self) -> None:
self.pass_in_axis(self.darray.plot.line)
def test_nonnumeric_index(self) -> None:
a = DataArray([1, 2, 3], {"letter": ["a", "b", "c"]}, dims="letter")
a.plot.line()
def test_primitive_returned(self) -> None:
p = self.darray.plot.line()
assert isinstance(p[0], mpl.lines.Line2D)
@pytest.mark.slow
def test_plot_nans(self) -> None:
self.darray[1] = np.nan
self.darray.plot.line()
def test_dates_are_concise(self) -> None:
import matplotlib.dates as mdates
time = pd.date_range("2000-01-01", "2000-01-10")
a = DataArray(np.arange(len(time)), [("t", time)])
a.plot.line()
ax = plt.gca()
assert isinstance(ax.xaxis.get_major_locator(), mdates.AutoDateLocator)
assert isinstance(ax.xaxis.get_major_formatter(), mdates.ConciseDateFormatter)
def test_xyincrease_false_changes_axes(self) -> None:
self.darray.plot.line(xincrease=False, yincrease=False)
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()
diffs = xlim[1] - xlim[0], ylim[1] - ylim[0]
assert all(x < 0 for x in diffs)
def test_slice_in_title(self) -> None:
self.darray.coords["d"] = 10.009
self.darray.plot.line()
title = plt.gca().get_title()
assert "d = 10.01" == title
def test_slice_in_title_single_item_array(self) -> None:
"""Edge case for data of shape (1, N) or (N, 1)."""
darray = self.darray.expand_dims({"d": np.array([10.009])})
darray.plot.line(x="period")
title = plt.gca().get_title()
assert "d = [10.009]" == title
def test_warns_for_few_positional_args(self) -> None:
with pytest.warns(FutureWarning, match="Using positional arguments"):
self.darray.plot.scatter("period")
def test_raises_for_too_many_positional_args(self) -> None:
with pytest.raises(ValueError, match="Using positional arguments"):
self.darray.plot.scatter("period", "foo", "bar", "blue", {})
class TestPlotStep(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
self.darray = DataArray(easy_array((2, 3, 4)))
def test_step(self) -> None:
hdl = self.darray[0, 0].plot.step()
assert "steps" in hdl[0].get_drawstyle()
@pytest.mark.parametrize("where", ["pre", "post", "mid"])
def test_step_with_where(self, where) -> None:
hdl = self.darray[0, 0].plot.step(where=where)
assert hdl[0].get_drawstyle() == f"steps-{where}"
def test_step_with_hue(self) -> None:
hdl = self.darray[0].plot.step(hue="dim_2")
assert hdl[0].get_drawstyle() == "steps-pre"
@pytest.mark.parametrize("where", ["pre", "post", "mid"])
def test_step_with_hue_and_where(self, where) -> None:
hdl = self.darray[0].plot.step(hue="dim_2", where=where)
assert hdl[0].get_drawstyle() == f"steps-{where}"
def test_drawstyle_steps(self) -> None:
hdl = self.darray[0].plot(hue="dim_2", drawstyle="steps") # type: ignore[call-arg]
assert hdl[0].get_drawstyle() == "steps"
@pytest.mark.parametrize("where", ["pre", "post", "mid"])
def test_drawstyle_steps_with_where(self, where) -> None:
hdl = self.darray[0].plot(hue="dim_2", drawstyle=f"steps-{where}") # type: ignore[call-arg]
assert hdl[0].get_drawstyle() == f"steps-{where}"
def test_coord_with_interval_step(self) -> None:
"""Test step plot with intervals."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot.step()
line = plt.gca().lines[0]
assert isinstance(line, mpl.lines.Line2D)
assert len(np.asarray(line.get_xdata())) == ((len(bins) - 1) * 2)
def test_coord_with_interval_step_x(self) -> None:
"""Test step plot with intervals explicitly on x axis."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot.step(x="dim_0_bins")
line = plt.gca().lines[0]
assert isinstance(line, mpl.lines.Line2D)
assert len(np.asarray(line.get_xdata())) == ((len(bins) - 1) * 2)
def test_coord_with_interval_step_y(self) -> None:
"""Test step plot with intervals explicitly on y axis."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot.step(y="dim_0_bins")
line = plt.gca().lines[0]
assert isinstance(line, mpl.lines.Line2D)
assert len(np.asarray(line.get_xdata())) == ((len(bins) - 1) * 2)
def test_coord_with_interval_step_x_and_y_raises_valueeerror(self) -> None:
"""Test that step plot with intervals both on x and y axes raises an error."""
arr = xr.DataArray(
[pd.Interval(0, 1), pd.Interval(1, 2)],
coords=[("x", [pd.Interval(0, 1), pd.Interval(1, 2)])],
)
with pytest.raises(TypeError, match="intervals against intervals"):
arr.plot.step()
class TestPlotHistogram(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
self.darray = DataArray(easy_array((2, 3, 4)))
def test_3d_array(self) -> None:
self.darray.plot.hist() # type: ignore[call-arg]
def test_xlabel_uses_name(self) -> None:
self.darray.name = "testpoints"
self.darray.attrs["units"] = "testunits"
self.darray.plot.hist() # type: ignore[call-arg]
assert "testpoints [testunits]" == plt.gca().get_xlabel()
def test_title_is_histogram(self) -> None:
self.darray.coords["d"] = 10
self.darray.plot.hist() # type: ignore[call-arg]
assert "d = 10" == plt.gca().get_title()
def test_can_pass_in_kwargs(self) -> None:
nbins = 5
self.darray.plot.hist(bins=nbins) # type: ignore[call-arg]
assert nbins == len(plt.gca().patches)
def test_can_pass_in_axis(self) -> None:
self.pass_in_axis(self.darray.plot.hist)
def test_primitive_returned(self) -> None:
n, bins, patches = self.darray.plot.hist() # type: ignore[call-arg]
assert isinstance(n, np.ndarray)
assert isinstance(bins, np.ndarray)
assert isinstance(patches, mpl.container.BarContainer)
assert isinstance(patches[0], mpl.patches.Rectangle)
@pytest.mark.slow
def test_plot_nans(self) -> None:
self.darray[0, 0, 0] = np.nan
self.darray.plot.hist() # type: ignore[call-arg]
def test_hist_coord_with_interval(self) -> None:
(
self.darray.groupby_bins("dim_0", [-1, 0, 1, 2]) # type: ignore[call-arg]
.mean(...)
.plot.hist(range=(-1, 2))
)
@requires_matplotlib
class TestDetermineCmapParams:
@pytest.fixture(autouse=True)
def setUp(self) -> None:
self.data = np.linspace(0, 1, num=100)
def test_robust(self) -> None:
cmap_params = _determine_cmap_params(self.data, robust=True)
assert cmap_params["vmin"] == np.percentile(self.data, 2)
assert cmap_params["vmax"] == np.percentile(self.data, 98)
assert cmap_params["cmap"] == "viridis"
assert cmap_params["extend"] == "both"
assert cmap_params["levels"] is None
assert cmap_params["norm"] is None
def test_center(self) -> None:
cmap_params = _determine_cmap_params(self.data, center=0.5)
assert cmap_params["vmax"] - 0.5 == 0.5 - cmap_params["vmin"]
assert cmap_params["cmap"] == "RdBu_r"
assert cmap_params["extend"] == "neither"
assert cmap_params["levels"] is None
assert cmap_params["norm"] is None
def test_cmap_sequential_option(self) -> None:
with xr.set_options(cmap_sequential="magma"):
cmap_params = _determine_cmap_params(self.data)
assert cmap_params["cmap"] == "magma"
def test_cmap_sequential_explicit_option(self) -> None:
with xr.set_options(cmap_sequential=mpl.colormaps["magma"]):
cmap_params = _determine_cmap_params(self.data)
assert cmap_params["cmap"] == mpl.colormaps["magma"]
def test_cmap_divergent_option(self) -> None:
with xr.set_options(cmap_divergent="magma"):
cmap_params = _determine_cmap_params(self.data, center=0.5)
assert cmap_params["cmap"] == "magma"
def test_nan_inf_are_ignored(self) -> None:
cmap_params1 = _determine_cmap_params(self.data)
data = self.data
data[50:55] = np.nan