FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
xarray/xarray/tests/test_plot.py at main · bhemmer/xarray · GitHub
xarray/xarray/tests/test_plot.py at main · bhemmer/xarray · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
bhemmer
/
xarray
Public
forked from
pydata/xarray
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
xarray
/
xarray
/
tests
/
test_plot.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
2996 lines (2459 loc) · 105 KB
Breadcrumbs
xarray
/
xarray
/
tests
/
test_plot.py
Copy path
File metadata and controls
2996 lines (2459 loc) · 105 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
contextlib
import
inspect
from
copy
import
copy
from
datetime
import
datetime
from
typing
import
Any
,
Dict
,
Union
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
,
_maybe_gca
,
get_axis
,
label_from_attrs
,
)
from
.
import
(
assert_array_equal
,
assert_equal
,
has_nc_time_axis
,
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
import
mpl_toolkits
# type: ignore
except
ImportError
:
pass
try
:
import
cartopy
except
ImportError
:
pass
@
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
(
scope
=
"function"
,
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
():
"""
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
)
def
get_colorbar_label
(
colorbar
):
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
):
yield
# Remove all matplotlib figures
plt
.
close
(
"all"
)
def
pass_in_axis
(
self
,
plotmethod
,
subplot_kw
=
None
):
fig
,
axes
=
plt
.
subplots
(
ncols
=
2
,
subplot_kw
=
subplot_kw
)
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
)
# 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
):
self
.
darray
[:,
0
,
0
].
plot
()
with
pytest
.
raises
(
ValueError
,
match
=
r"x must be one of None, 'dim_0'"
):
self
.
darray
[:,
0
,
0
].
plot
(
x
=
"dim_1"
)
with
pytest
.
raises
(
TypeError
,
match
=
r"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
pytest
.
raises
(
ValueError
,
match
=
r"Cannot specify both"
):
da
.
plot
(
x
=
"z"
,
y
=
"z"
)
error_msg
=
"must be one of None, 'z'"
with
pytest
.
raises
(
ValueError
,
match
=
rf"x
{
error_msg
}
"
):
da
.
plot
(
x
=
"f"
)
with
pytest
.
raises
(
ValueError
,
match
=
rf"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_line_plot_wrong_hue
(
self
):
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"
)
def
test_2d_line
(
self
):
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
):
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
)},
)
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
):
# 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
test2d_1d_2d_coordinates_pcolormesh
(
self
):
# 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
# 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_contourf_cmap_set
(
self
):
a
=
DataArray
(
easy_array
((
4
,
4
)),
dims
=
[
"z"
,
"time"
])
cmap
=
mpl
.
cm
.
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
),
vmin
=
0.1
,
vmax
=
0.9
)
# check the set_bad color
assert_array_equal
(
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.
cmap
=
copy
(
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
)
# copy to ensure cmap is not changed by contourf()
pl
=
a
.
plot
.
contourf
(
cmap
=
copy
(
cmap
))
# check the set_bad color has been kept
assert_array_equal
(
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__infer_interval_breaks_logscale
(
self
):
"""
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
):
"""
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 nagative 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
):
# 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
pytest
.
raises
(
ValueError
,
match
=
r"[Ff]acet"
):
d
.
plot
(
x
=
"x"
,
y
=
"y"
,
col
=
"z"
,
ax
=
plt
.
gca
())
with
pytest
.
raises
(
ValueError
,
match
=
r"[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
pytest
.
raises
(
ValueError
,
match
=
r"cannot provide both"
):
self
.
darray
.
plot
(
ax
=
plt
.
gca
(),
figsize
=
(
3
,
4
))
with
pytest
.
raises
(
ValueError
,
match
=
r"cannot provide both"
):
self
.
darray
.
plot
(
size
=
5
,
figsize
=
(
3
,
4
))
with
pytest
.
raises
(
ValueError
,
match
=
r"cannot provide both"
):
self
.
darray
.
plot
(
size
=
5
,
ax
=
plt
.
gca
())
with
pytest
.
raises
(
ValueError
,
match
=
r"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
pytest
.
raises
(
ValueError
,
match
=
r"[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
()
@
pytest
.
mark
.
parametrize
(
"dim"
, (
"x"
,
"y"
))
def
test_labels_with_units_with_interval
(
self
,
dim
):
"""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"
})
ax
=
mappable
.
figure
.
gca
()
actual
=
getattr
(
ax
,
f"get_
{
dim
}
label"
)()
expected
=
"dim_0_bins_center [m]"
assert
actual
==
expected
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
(
self
):
a
=
DataArray
([
1
,
2
,
3
], {
"letter"
: [
"a"
,
"b"
,
"c"
]},
dims
=
"letter"
)
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.009
self
.
darray
.
plot
.
line
()
title
=
plt
.
gca
().
get_title
()
assert
"d = 10.01"
==
title
def
test_slice_in_title_single_item_array
(
self
):
"""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.01"
==
title
class
TestPlotStep
(
PlotTestCase
):
@
pytest
.
fixture
(
autouse
=
True
)
def
setUp
(
self
):
self
.
darray
=
DataArray
(
easy_array
((
2
,
3
,
4
)))
def
test_step
(
self
):
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
):
hdl
=
self
.
darray
[
0
,
0
].
plot
.
step
(
where
=
where
)
assert
hdl
[
0
].
get_drawstyle
()
==
f"steps-
{
where
}
"
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
.
coords
[
"d"
]
=
10
self
.
darray
.
plot
.
hist
()
assert
"d = 10"
==
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"
]
is
None
assert
cmap_params
[
"vmax"
]
is
None
assert
cmap_params
[
"norm"
].
vmin
==
cmap_params
[
"levels"
][
0
]
assert
cmap_params
[
"norm"
].
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"
]
is
None
assert
cmap_params
[
"vmax"
]
is
None
assert
cmap_params
[
"norm"
].
vmin
==
0
assert
cmap_params
[
"norm"
].
vmax
==
5
assert
cmap_params
[
"norm"
].
vmin
==
cmap_params
[
"levels"
][
0
]
assert
cmap_params
[
"norm"
].
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"
]
is
None
assert
cmap_params
[
"vmax"
]
is
None
assert
cmap_params
[
"norm"
].
vmin
==
0
assert
cmap_params
[
"norm"
].
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
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL