/
test_plot.py
2435 lines (1990 loc) · 85 KB
/
test_plot.py
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
import inspect
from copy import deepcopy
from datetime import datetime
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.plot.dataset_plot import _infer_meta_data
from xarray.plot.plot import _infer_interval_breaks
from xarray.plot.utils import (
_build_discrete_cmap,
_color_palette,
_determine_cmap_params,
get_axis,
label_from_attrs,
)
from . import (
assert_array_equal,
assert_equal,
has_nc_time_axis,
raises_regex,
requires_cartopy,
requires_cftime,
requires_matplotlib,
requires_nc_time_axis,
requires_seaborn,
)
# import mpl and change the backend before other mpl imports
try:
import matplotlib as mpl
import matplotlib.pyplot as plt
except ImportError:
pass
try:
import cartopy as ctpy # type: ignore
except ImportError:
ctpy = None
@pytest.mark.flaky
@pytest.mark.skip(reason="maybe flaky")
def text_in_fig():
"""
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():
# nb. this function also matches meshes from pcolormesh
return plt.gcf().findobj(mpl.collections.QuadMesh)
def substring_in_axes(substring, ax):
"""
Return True if a substring is found anywhere in an axes
"""
alltxt = {t.get_text() for t in ax.findobj(mpl.text.Text)}
for txt in alltxt:
if substring in txt:
return True
return False
def substring_not_in_axes(substring, ax):
"""
Return True if a substring is not found anywhere in an axes
"""
alltxt = {t.get_text() for t in ax.findobj(mpl.text.Text)}
check = [(substring not in txt) for txt in alltxt]
return all(check)
def easy_array(shape, start=0, stop=1):
"""
Make an array with desired shape using np.linspace
shape is a tuple like (2, 3)
"""
a = np.linspace(start, stop, num=np.prod(shape))
return a.reshape(shape)
@requires_matplotlib
class PlotTestCase:
@pytest.fixture(autouse=True)
def setup(self):
yield
# Remove all matplotlib figures
plt.close("all")
def pass_in_axis(self, plotmethod):
fig, axes = plt.subplots(ncols=2)
plotmethod(ax=axes[0])
assert axes[0].has_data()
@pytest.mark.slow
def imshow_called(self, plotmethod):
plotmethod()
images = plt.gca().findobj(mpl.image.AxesImage)
return len(images) > 0
def contourf_called(self, plotmethod):
plotmethod()
paths = plt.gca().findobj(mpl.collections.PathCollection)
return len(paths) > 0
class TestPlot(PlotTestCase):
@pytest.fixture(autouse=True)
def setup_array(self):
self.darray = DataArray(easy_array((2, 3, 4)))
def test_accessor(self):
from ..plot.plot import _PlotMethods
assert DataArray.plot is _PlotMethods
assert isinstance(self.darray.plot, _PlotMethods)
def test_label_from_attrs(self):
da = self.darray.copy()
assert "" == 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)
def test1d(self):
self.darray[:, 0, 0].plot()
with raises_regex(ValueError, "x must be one of None, 'dim_0'"):
self.darray[:, 0, 0].plot(x="dim_1")
with raises_regex(TypeError, "complex128"):
(self.darray[:, 0, 0] + 1j).plot()
def test_1d_bool(self):
xr.ones_like(self.darray[:, 0, 0], dtype=bool).plot()
def test_1d_x_y_kw(self):
z = np.arange(10)
da = DataArray(np.cos(z), dims=["z"], coords=[z], name="f")
xy = [[None, None], [None, "z"], ["z", None]]
f, ax = plt.subplots(3, 1)
for aa, (x, y) in enumerate(xy):
da.plot(x=x, y=y, ax=ax.flat[aa])
with raises_regex(ValueError, "Cannot specify both"):
da.plot(x="z", y="z")
error_msg = "must be one of None, 'z'"
with raises_regex(ValueError, f"x {error_msg}"):
da.plot(x="f")
with raises_regex(ValueError, f"y {error_msg}"):
da.plot(y="f")
def test_multiindex_level_as_coord(self):
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]
assert_array_equal(h.get_xdata(), da[x].values)
for y in ["a", "b"]:
h = da.plot(y=y)[0]
assert_array_equal(h.get_ydata(), da[y].values)
# Test for bug in GH issue #2725
def test_infer_line_data(self):
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):
# 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]
assert_array_equal(line.get_xdata(), da.coords["time"].values)
line = da.plot(y="time", hue="x")[0]
assert_array_equal(line.get_ydata(), da.coords["time"].values)
def test_2d_line(self):
with raises_regex(ValueError, "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 raises_regex(ValueError, "Cannot"):
self.darray[:, :, 0].plot.line(x="dim_1", y="dim_0", hue="dim_1")
def test_2d_line_accepts_legend_kw(self):
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)
assert plt.gca().get_legend()
# check whether legend title is set
assert plt.gca().get_legend().get_title().get_text() == "dim_1"
def test_2d_line_accepts_x_kw(self):
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):
self.darray[:, :, 0].plot.line(hue="dim_0")
assert plt.gca().get_legend().get_title().get_text() == "dim_0"
plt.cla()
self.darray[:, :, 0].plot.line(hue="dim_1")
assert plt.gca().get_legend().get_title().get_text() == "dim_1"
def test_2d_coords_line_plot(self):
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)},
)
hdl = da.plot.line(x="lon", hue="x")
assert len(hdl) == 5
plt.clf()
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):
# 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):
a = DataArray(easy_array((1, 5)))
a.plot()
def test2d_uniform_calls_imshow(self):
assert self.imshow_called(self.darray[:, :, 0].plot.imshow)
@pytest.mark.slow
def test2d_nonuniform_calls_contourf(self):
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):
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 test_contourf_cmap_set(self):
a = DataArray(easy_array((4, 4)), dims=["z", "time"])
cmap = mpl.cm.viridis
# deepcopy 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=deepcopy(cmap), vmin=0.1, vmax=0.9)
# check the set_bad color
assert np.all(
pl.cmap(np.ma.masked_invalid([np.nan]))[0]
== cmap(np.ma.masked_invalid([np.nan]))[0]
)
# check the set_under color
assert pl.cmap(-np.inf) == cmap(-np.inf)
# check the set_over color
assert pl.cmap(np.inf) == cmap(np.inf)
def test_contourf_cmap_set_with_bad_under_over(self):
a = DataArray(easy_array((4, 4)), dims=["z", "time"])
# Make a copy here because we want a local cmap that we will modify.
# Use deepcopy because matplotlib Colormap objects have tuple members
# and we want to ensure we do not change the original.
cmap = deepcopy(mpl.cm.viridis)
cmap.set_bad("w")
# check we actually changed the set_bad color
assert np.all(
cmap(np.ma.masked_invalid([np.nan]))[0]
!= mpl.cm.viridis(np.ma.masked_invalid([np.nan]))[0]
)
cmap.set_under("r")
# check we actually changed the set_under color
assert cmap(-np.inf) != mpl.cm.viridis(-np.inf)
cmap.set_over("g")
# check we actually changed the set_over color
assert cmap(np.inf) != mpl.cm.viridis(-np.inf)
# deepcopy to ensure cmap is not changed by contourf()
pl = a.plot.contourf(cmap=deepcopy(cmap))
# check the set_bad color has been kept
assert np.all(
pl.cmap(np.ma.masked_invalid([np.nan]))[0]
== cmap(np.ma.masked_invalid([np.nan]))[0]
)
# check the set_under color has been kept
assert pl.cmap(-np.inf) == cmap(-np.inf)
# check the set_over color has been kept
assert pl.cmap(np.inf) == cmap(np.inf)
def test3d(self):
self.darray.plot()
def test_can_pass_in_axis(self):
self.pass_in_axis(self.darray.plot)
def test__infer_interval_breaks(self):
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_geo_data(self):
# 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.sqrt(lon ** 2 + lat ** 2)
da = DataArray(
data,
dims=("y", "x"),
coords={"lon": (("y", "x"), lon), "lat": (("y", "x"), lat)},
)
da.plot(x="lon", y="lat")
ax = plt.gca()
assert ax.has_data()
da.plot(x="lat", y="lon")
ax = plt.gca()
assert ax.has_data()
def test_datetime_dimension(self):
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()
ax = plt.gca()
assert ax.has_data()
@pytest.mark.slow
@pytest.mark.filterwarnings("ignore:tight_layout cannot")
def test_convenient_facetgrid(self):
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")
assert_array_equal(g.axes.shape, [2, 2])
for ax in g.axes.flat:
assert ax.has_data()
with raises_regex(ValueError, "[Ff]acet"):
d.plot(x="x", y="y", col="z", ax=plt.gca())
with raises_regex(ValueError, "[Ff]acet"):
d[0].plot(x="x", y="y", col="z", ax=plt.gca())
@pytest.mark.slow
def test_subplot_kws(self):
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",
subplot_kws=dict(facecolor="r"),
)
for ax in g.axes.flat:
# mpl V2
assert ax.get_facecolor()[0:3] == mpl.colors.to_rgb("r")
@pytest.mark.slow
def test_plot_size(self):
self.darray[:, 0, 0].plot(figsize=(13, 5))
assert tuple(plt.gcf().get_size_inches()) == (13, 5)
self.darray.plot(figsize=(13, 5))
assert tuple(plt.gcf().get_size_inches()) == (13, 5)
self.darray.plot(size=5)
assert plt.gcf().get_size_inches()[1] == 5
self.darray.plot(size=5, aspect=2)
assert tuple(plt.gcf().get_size_inches()) == (10, 5)
with raises_regex(ValueError, "cannot provide both"):
self.darray.plot(ax=plt.gca(), figsize=(3, 4))
with raises_regex(ValueError, "cannot provide both"):
self.darray.plot(size=5, figsize=(3, 4))
with raises_regex(ValueError, "cannot provide both"):
self.darray.plot(size=5, ax=plt.gca())
with raises_regex(ValueError, "cannot provide `aspect`"):
self.darray.plot(aspect=1)
@pytest.mark.slow
@pytest.mark.filterwarnings("ignore:tight_layout cannot")
def test_convenient_facetgrid_4d(self):
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")
assert_array_equal(g.axes.shape, [3, 2])
for ax in g.axes.flat:
assert ax.has_data()
with raises_regex(ValueError, "[Ff]acet"):
d.plot(x="x", y="y", col="columns", ax=plt.gca())
def test_coord_with_interval(self):
"""Test line plot with intervals."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot()
def test_coord_with_interval_x(self):
"""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")
def test_coord_with_interval_y(self):
"""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")
def test_coord_with_interval_xy(self):
"""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()
class TestPlot1D(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self):
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):
self.darray.plot()
assert "period [s]" == plt.gca().get_xlabel()
def test_no_label_name_on_x_axis(self):
self.darray.plot(y="period")
assert "" == plt.gca().get_xlabel()
def test_no_label_name_on_y_axis(self):
self.darray.plot()
assert "" == plt.gca().get_ylabel()
def test_ylabel_is_data_name(self):
self.darray.name = "temperature"
self.darray.attrs["units"] = "degrees_Celsius"
self.darray.plot()
assert "temperature [degrees_Celsius]" == plt.gca().get_ylabel()
def test_xlabel_is_data_name(self):
self.darray.name = "temperature"
self.darray.attrs["units"] = "degrees_Celsius"
self.darray.plot(y="period")
assert "temperature [degrees_Celsius]" == plt.gca().get_xlabel()
def test_format_string(self):
self.darray.plot.line("ro")
def test_can_pass_in_axis(self):
self.pass_in_axis(self.darray.plot.line)
def test_nonnumeric_index_raises_typeerror(self):
a = DataArray([1, 2, 3], {"letter": ["a", "b", "c"]}, dims="letter")
with raises_regex(TypeError, r"[Pp]lot"):
a.plot.line()
def test_primitive_returned(self):
p = self.darray.plot.line()
assert isinstance(p[0], mpl.lines.Line2D)
@pytest.mark.slow
def test_plot_nans(self):
self.darray[1] = np.nan
self.darray.plot.line()
def test_x_ticks_are_rotated_for_time(self):
time = pd.date_range("2000-01-01", "2000-01-10")
a = DataArray(np.arange(len(time)), [("t", time)])
a.plot.line()
rotation = plt.gca().get_xticklabels()[0].get_rotation()
assert rotation != 0
def test_xyincrease_false_changes_axes(self):
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):
self.darray.coords["d"] = 10
self.darray.plot.line()
title = plt.gca().get_title()
assert "d = 10" == title
class TestPlotStep(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self):
self.darray = DataArray(easy_array((2, 3, 4)))
def test_step(self):
self.darray[0, 0].plot.step()
@pytest.mark.parametrize("ds", ["pre", "post", "mid"])
def test_step_with_drawstyle(self, ds):
self.darray[0, 0].plot.step(drawstyle=ds)
def test_coord_with_interval_step(self):
"""Test step plot with intervals."""
bins = [-1, 0, 1, 2]
self.darray.groupby_bins("dim_0", bins).mean(...).plot.step()
assert len(plt.gca().lines[0].get_xdata()) == ((len(bins) - 1) * 2)
def test_coord_with_interval_step_x(self):
"""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")
assert len(plt.gca().lines[0].get_xdata()) == ((len(bins) - 1) * 2)
def test_coord_with_interval_step_y(self):
"""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")
assert len(plt.gca().lines[0].get_xdata()) == ((len(bins) - 1) * 2)
class TestPlotHistogram(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self):
self.darray = DataArray(easy_array((2, 3, 4)))
def test_3d_array(self):
self.darray.plot.hist()
def test_xlabel_uses_name(self):
self.darray.name = "testpoints"
self.darray.attrs["units"] = "testunits"
self.darray.plot.hist()
assert "testpoints [testunits]" == plt.gca().get_xlabel()
def test_title_is_histogram(self):
self.darray.plot.hist()
assert "Histogram" == plt.gca().get_title()
def test_can_pass_in_kwargs(self):
nbins = 5
self.darray.plot.hist(bins=nbins)
assert nbins == len(plt.gca().patches)
def test_can_pass_in_axis(self):
self.pass_in_axis(self.darray.plot.hist)
def test_primitive_returned(self):
h = self.darray.plot.hist()
assert isinstance(h[-1][0], mpl.patches.Rectangle)
@pytest.mark.slow
def test_plot_nans(self):
self.darray[0, 0, 0] = np.nan
self.darray.plot.hist()
def test_hist_coord_with_interval(self):
(
self.darray.groupby_bins("dim_0", [-1, 0, 1, 2])
.mean(...)
.plot.hist(range=(-1, 2))
)
@requires_matplotlib
class TestDetermineCmapParams:
@pytest.fixture(autouse=True)
def setUp(self):
self.data = np.linspace(0, 1, num=100)
def test_robust(self):
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):
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):
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):
with xr.set_options(cmap_sequential=mpl.cm.magma):
cmap_params = _determine_cmap_params(self.data)
assert cmap_params["cmap"] == mpl.cm.magma
def test_cmap_divergent_option(self):
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):
cmap_params1 = _determine_cmap_params(self.data)
data = self.data
data[50:55] = np.nan
data[56:60] = np.inf
cmap_params2 = _determine_cmap_params(data)
assert cmap_params1["vmin"] == cmap_params2["vmin"]
assert cmap_params1["vmax"] == cmap_params2["vmax"]
@pytest.mark.slow
def test_integer_levels(self):
data = self.data + 1
# default is to cover full data range but with no guarantee on Nlevels
for level in np.arange(2, 10, dtype=int):
cmap_params = _determine_cmap_params(data, levels=level)
assert cmap_params["vmin"] == cmap_params["levels"][0]
assert cmap_params["vmax"] == cmap_params["levels"][-1]
assert cmap_params["extend"] == "neither"
# with min max we are more strict
cmap_params = _determine_cmap_params(
data, levels=5, vmin=0, vmax=5, cmap="Blues"
)
assert cmap_params["vmin"] == 0
assert cmap_params["vmax"] == 5
assert cmap_params["vmin"] == cmap_params["levels"][0]
assert cmap_params["vmax"] == cmap_params["levels"][-1]
assert cmap_params["cmap"].name == "Blues"
assert cmap_params["extend"] == "neither"
assert cmap_params["cmap"].N == 4
assert cmap_params["norm"].N == 5
cmap_params = _determine_cmap_params(data, levels=5, vmin=0.5, vmax=1.5)
assert cmap_params["cmap"].name == "viridis"
assert cmap_params["extend"] == "max"
cmap_params = _determine_cmap_params(data, levels=5, vmin=1.5)
assert cmap_params["cmap"].name == "viridis"
assert cmap_params["extend"] == "min"
cmap_params = _determine_cmap_params(data, levels=5, vmin=1.3, vmax=1.5)
assert cmap_params["cmap"].name == "viridis"
assert cmap_params["extend"] == "both"
def test_list_levels(self):
data = self.data + 1
orig_levels = [0, 1, 2, 3, 4, 5]
# vmin and vmax should be ignored if levels are explicitly provided
cmap_params = _determine_cmap_params(data, levels=orig_levels, vmin=0, vmax=3)
assert cmap_params["vmin"] == 0
assert cmap_params["vmax"] == 5
assert cmap_params["cmap"].N == 5
assert cmap_params["norm"].N == 6
for wrap_levels in [list, np.array, pd.Index, DataArray]:
cmap_params = _determine_cmap_params(data, levels=wrap_levels(orig_levels))
assert_array_equal(cmap_params["levels"], orig_levels)
def test_divergentcontrol(self):
neg = self.data - 0.1
pos = self.data
# Default with positive data will be a normal cmap
cmap_params = _determine_cmap_params(pos)
assert cmap_params["vmin"] == 0
assert cmap_params["vmax"] == 1
assert cmap_params["cmap"] == "viridis"
# Default with negative data will be a divergent cmap
cmap_params = _determine_cmap_params(neg)
assert cmap_params["vmin"] == -0.9
assert cmap_params["vmax"] == 0.9
assert cmap_params["cmap"] == "RdBu_r"
# Setting vmin or vmax should prevent this only if center is false
cmap_params = _determine_cmap_params(neg, vmin=-0.1, center=False)
assert cmap_params["vmin"] == -0.1
assert cmap_params["vmax"] == 0.9
assert cmap_params["cmap"] == "viridis"
cmap_params = _determine_cmap_params(neg, vmax=0.5, center=False)
assert cmap_params["vmin"] == -0.1
assert cmap_params["vmax"] == 0.5
assert cmap_params["cmap"] == "viridis"
# Setting center=False too
cmap_params = _determine_cmap_params(neg, center=False)
assert cmap_params["vmin"] == -0.1
assert cmap_params["vmax"] == 0.9
assert cmap_params["cmap"] == "viridis"
# However, I should still be able to set center and have a div cmap
cmap_params = _determine_cmap_params(neg, center=0)
assert cmap_params["vmin"] == -0.9
assert cmap_params["vmax"] == 0.9
assert cmap_params["cmap"] == "RdBu_r"
# Setting vmin or vmax alone will force symmetric bounds around center
cmap_params = _determine_cmap_params(neg, vmin=-0.1)
assert cmap_params["vmin"] == -0.1
assert cmap_params["vmax"] == 0.1
assert cmap_params["cmap"] == "RdBu_r"
cmap_params = _determine_cmap_params(neg, vmax=0.5)
assert cmap_params["vmin"] == -0.5
assert cmap_params["vmax"] == 0.5
assert cmap_params["cmap"] == "RdBu_r"
cmap_params = _determine_cmap_params(neg, vmax=0.6, center=0.1)
assert cmap_params["vmin"] == -0.4
assert cmap_params["vmax"] == 0.6
assert cmap_params["cmap"] == "RdBu_r"
# But this is only true if vmin or vmax are negative
cmap_params = _determine_cmap_params(pos, vmin=-0.1)
assert cmap_params["vmin"] == -0.1
assert cmap_params["vmax"] == 0.1
assert cmap_params["cmap"] == "RdBu_r"
cmap_params = _determine_cmap_params(pos, vmin=0.1)
assert cmap_params["vmin"] == 0.1
assert cmap_params["vmax"] == 1
assert cmap_params["cmap"] == "viridis"
cmap_params = _determine_cmap_params(pos, vmax=0.5)
assert cmap_params["vmin"] == 0
assert cmap_params["vmax"] == 0.5
assert cmap_params["cmap"] == "viridis"
# If both vmin and vmax are provided, output is non-divergent
cmap_params = _determine_cmap_params(neg, vmin=-0.2, vmax=0.6)
assert cmap_params["vmin"] == -0.2
assert cmap_params["vmax"] == 0.6
assert cmap_params["cmap"] == "viridis"
# regression test for GH3524
# infer diverging colormap from divergent levels
cmap_params = _determine_cmap_params(pos, levels=[-0.1, 0, 1])
# specifying levels makes cmap a Colormap object
assert cmap_params["cmap"].name == "RdBu_r"
def test_norm_sets_vmin_vmax(self):
vmin = self.data.min()
vmax = self.data.max()
for norm, extend, levels in zip(
[
mpl.colors.Normalize(),
mpl.colors.Normalize(),
mpl.colors.Normalize(vmin + 0.1, vmax - 0.1),
mpl.colors.Normalize(None, vmax - 0.1),
mpl.colors.Normalize(vmin + 0.1, None),
],
["neither", "neither", "both", "max", "min"],
[7, None, None, None, None],
):
test_min = vmin if norm.vmin is None else norm.vmin
test_max = vmax if norm.vmax is None else norm.vmax
cmap_params = _determine_cmap_params(self.data, norm=norm, levels=levels)
assert cmap_params["vmin"] == test_min
assert cmap_params["vmax"] == test_max
assert cmap_params["extend"] == extend
assert cmap_params["norm"] == norm
@requires_matplotlib
class TestDiscreteColorMap:
@pytest.fixture(autouse=True)
def setUp(self):
x = np.arange(start=0, stop=10, step=2)
y = np.arange(start=9, stop=-7, step=-3)
xy = np.dstack(np.meshgrid(x, y))
distance = np.linalg.norm(xy, axis=2)
self.darray = DataArray(distance, list(zip(("y", "x"), (y, x))))
self.data_min = distance.min()
self.data_max = distance.max()
@pytest.mark.slow
def test_recover_from_seaborn_jet_exception(self):
pal = _color_palette("jet", 4)
assert type(pal) == np.ndarray
assert len(pal) == 4
@pytest.mark.slow
def test_build_discrete_cmap(self):
for (cmap, levels, extend, filled) in [
("jet", [0, 1], "both", False),
("hot", [-4, 4], "max", True),
]:
ncmap, cnorm = _build_discrete_cmap(cmap, levels, extend, filled)
assert ncmap.N == len(levels) - 1
assert len(ncmap.colors) == len(levels) - 1
assert cnorm.N == len(levels)
assert_array_equal(cnorm.boundaries, levels)
assert max(levels) == cnorm.vmax
assert min(levels) == cnorm.vmin
if filled:
assert ncmap.colorbar_extend == extend
else:
assert ncmap.colorbar_extend == "max"
@pytest.mark.slow
def test_discrete_colormap_list_of_levels(self):
for extend, levels in [
("max", [-1, 2, 4, 8, 10]),
("both", [2, 5, 10, 11]),
("neither", [0, 5, 10, 15]),
("min", [2, 5, 10, 15]),
]:
for kind in ["imshow", "pcolormesh", "contourf", "contour"]:
primitive = getattr(self.darray.plot, kind)(levels=levels)
assert_array_equal(levels, primitive.norm.boundaries)
assert max(levels) == primitive.norm.vmax
assert min(levels) == primitive.norm.vmin
if kind != "contour":
assert extend == primitive.cmap.colorbar_extend
else:
assert "max" == primitive.cmap.colorbar_extend
assert len(levels) - 1 == len(primitive.cmap.colors)
@pytest.mark.slow
def test_discrete_colormap_int_levels(self):
for extend, levels, vmin, vmax, cmap in [
("neither", 7, None, None, None),
("neither", 7, None, 20, mpl.cm.RdBu),
("both", 7, 4, 8, None),
("min", 10, 4, 15, None),
]:
for kind in ["imshow", "pcolormesh", "contourf", "contour"]:
primitive = getattr(self.darray.plot, kind)(
levels=levels, vmin=vmin, vmax=vmax, cmap=cmap
)
assert levels >= len(primitive.norm.boundaries) - 1
if vmax is None:
assert primitive.norm.vmax >= self.data_max
else:
assert primitive.norm.vmax >= vmax
if vmin is None:
assert primitive.norm.vmin <= self.data_min
else:
assert primitive.norm.vmin <= vmin
if kind != "contour":
assert extend == primitive.cmap.colorbar_extend
else:
assert "max" == primitive.cmap.colorbar_extend
assert levels >= len(primitive.cmap.colors)
def test_discrete_colormap_list_levels_and_vmin_or_vmax(self):
levels = [0, 5, 10, 15]
primitive = self.darray.plot(levels=levels, vmin=-3, vmax=20)
assert primitive.norm.vmax == max(levels)
assert primitive.norm.vmin == min(levels)
def test_discrete_colormap_provided_boundary_norm(self):
norm = mpl.colors.BoundaryNorm([0, 5, 10, 15], 4)
primitive = self.darray.plot.contourf(norm=norm)
np.testing.assert_allclose(primitive.levels, norm.boundaries)