-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Expand file tree
/
Copy pathtest_axes3d.py
More file actions
3178 lines (2584 loc) · 107 KB
/
test_axes3d.py
File metadata and controls
3178 lines (2584 loc) · 107 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
import functools
import itertools
import platform
import sys
from packaging.version import parse as parse_version
import pytest
from mpl_toolkits.mplot3d import Axes3D, axes3d, proj3d, art3d
from mpl_toolkits.mplot3d.axes3d import _Quaternion as Quaternion
import matplotlib as mpl
from matplotlib.backend_bases import (MouseButton, MouseEvent,
NavigationToolbar2)
from matplotlib import cm
from matplotlib import colors as mcolors, patches as mpatch
from matplotlib.testing.decorators import image_comparison, check_figures_equal
from matplotlib.collections import LineCollection, PolyCollection
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
from matplotlib.text import Text
from matplotlib import _api
import matplotlib.pyplot as plt
import numpy as np
mpl3d_image_comparison = functools.partial(
image_comparison, remove_text=True, style='default')
def plot_cuboid(ax, scale):
# plot a rectangular cuboid with side lengths given by scale (x, y, z)
r = [0, 1]
pts = itertools.combinations(np.array(list(itertools.product(r, r, r))), 2)
for start, end in pts:
if np.sum(np.abs(start - end)) == r[1] - r[0]:
ax.plot3D(*zip(start*np.array(scale), end*np.array(scale)))
@check_figures_equal()
def test_invisible_axes(fig_test, fig_ref):
ax = fig_test.subplots(subplot_kw=dict(projection='3d'))
ax.set_visible(False)
@mpl3d_image_comparison(['grid_off.png'], style='mpl20')
def test_grid_off():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.grid(False)
@mpl3d_image_comparison(['invisible_ticks_axis.png'], style='mpl20')
def test_invisible_ticks_axis():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
for axis in [ax.xaxis, ax.yaxis, ax.zaxis]:
axis.line.set_visible(False)
@mpl3d_image_comparison(['axis_positions.png'], remove_text=False, style='mpl20')
def test_axis_positions():
positions = ['upper', 'lower', 'both', 'none']
fig, axs = plt.subplots(2, 2, subplot_kw={'projection': '3d'})
for ax, pos in zip(axs.flatten(), positions):
for axis in ax.xaxis, ax.yaxis, ax.zaxis:
axis.set_label_position(pos)
axis.set_ticks_position(pos)
title = f'{pos}'
ax.set(xlabel='x', ylabel='y', zlabel='z', title=title)
@mpl3d_image_comparison(['aspects.png'], remove_text=False, style='mpl20')
def test_aspects():
aspects = ('auto', 'equal', 'equalxy', 'equalyz', 'equalxz', 'equal')
_, axs = plt.subplots(2, 3, subplot_kw={'projection': '3d'})
for ax in axs.flatten()[0:-1]:
plot_cuboid(ax, scale=[1, 1, 5])
# plot a cube as well to cover github #25443
plot_cuboid(axs[1][2], scale=[1, 1, 1])
for i, ax in enumerate(axs.flatten()):
ax.set_title(aspects[i])
ax.set_box_aspect((3, 4, 5))
ax.set_aspect(aspects[i], adjustable='datalim')
axs[1][2].set_title('equal (cube)')
@mpl3d_image_comparison(['aspects_adjust_box.png'],
remove_text=False, style='mpl20')
def test_aspects_adjust_box():
aspects = ('auto', 'equal', 'equalxy', 'equalyz', 'equalxz')
fig, axs = plt.subplots(1, len(aspects), subplot_kw={'projection': '3d'},
figsize=(11, 3))
for i, ax in enumerate(axs):
plot_cuboid(ax, scale=[4, 3, 5])
ax.set_title(aspects[i])
ax.set_aspect(aspects[i], adjustable='box')
def test_axes3d_repr():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_label('label')
ax.set_title('title')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
assert repr(ax) == (
"<Axes3D: label='label', "
"title={'center': 'title'}, xlabel='x', ylabel='y', zlabel='z'>")
@mpl3d_image_comparison(['axes3d_primary_views.png'], style='mpl20',
tol=0.045 if sys.platform == 'darwin' else 0)
def test_axes3d_primary_views():
# (elev, azim, roll)
views = [(90, -90, 0), # XY
(0, -90, 0), # XZ
(0, 0, 0), # YZ
(-90, 90, 0), # -XY
(0, 90, 0), # -XZ
(0, 180, 0)] # -YZ
# When viewing primary planes, draw the two visible axes so they intersect
# at their low values
fig, axs = plt.subplots(2, 3, subplot_kw={'projection': '3d'})
for i, ax in enumerate(axs.flat):
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_proj_type('ortho')
ax.view_init(elev=views[i][0], azim=views[i][1], roll=views[i][2])
plt.tight_layout()
@mpl3d_image_comparison(['bar3d.png'], style='mpl20')
def test_bar3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.arange(20)
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', align='edge', color=cs, alpha=0.8)
def test_bar3d_colors():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
for c in ['red', 'green', 'blue', 'yellow']:
xs = np.arange(len(c))
ys = np.zeros_like(xs)
zs = np.zeros_like(ys)
# Color names with same length as xs/ys/zs should not be split into
# individual letters.
ax.bar3d(xs, ys, zs, 1, 1, 1, color=c)
@mpl3d_image_comparison(['bar3d_shaded.png'], style='mpl20')
def test_bar3d_shaded():
x = np.arange(4)
y = np.arange(5)
x2d, y2d = np.meshgrid(x, y)
x2d, y2d = x2d.ravel(), y2d.ravel()
z = x2d + y2d + 1 # Avoid triggering bug with zero-depth boxes.
views = [(30, -60, 0), (30, 30, 30), (-30, 30, -90), (300, -30, 0)]
fig = plt.figure(figsize=plt.figaspect(1 / len(views)))
axs = fig.subplots(
1, len(views),
subplot_kw=dict(projection='3d')
)
for ax, (elev, azim, roll) in zip(axs, views):
ax.bar3d(x2d, y2d, x2d * 0, 1, 1, z, shade=True)
ax.view_init(elev=elev, azim=azim, roll=roll)
fig.canvas.draw()
@mpl3d_image_comparison(['bar3d_notshaded.png'], style='mpl20',
tol=0.01 if parse_version(np.version.version).major < 2 else 0)
def test_bar3d_notshaded():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x = np.arange(4)
y = np.arange(5)
x2d, y2d = np.meshgrid(x, y)
x2d, y2d = x2d.ravel(), y2d.ravel()
z = x2d + y2d
ax.bar3d(x2d, y2d, x2d * 0, 1, 1, z, shade=False)
fig.canvas.draw()
def test_bar3d_lightsource():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection="3d")
ls = mcolors.LightSource(azdeg=0, altdeg=90)
length, width = 3, 4
area = length * width
x, y = np.meshgrid(np.arange(length), np.arange(width))
x = x.ravel()
y = y.ravel()
dz = x + y
color = [cm.coolwarm(i/area) for i in range(area)]
collection = ax.bar3d(x=x, y=y, z=0,
dx=1, dy=1, dz=dz,
color=color, shade=True, lightsource=ls)
# Testing that the custom 90° lightsource produces different shading on
# the top facecolors compared to the default, and that those colors are
# precisely (within floating point rounding errors of 4 ULP) the colors
# from the colormap, due to the illumination parallel to the z-axis.
np.testing.assert_array_max_ulp(color, collection._facecolor3d[1::6], 4)
@mpl3d_image_comparison(['contour3d.png'], style='mpl20',
tol=0 if platform.machine() == 'x86_64' else 0.002)
def test_contour3d():
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contour(X, Y, Z, zdir='z', offset=-100, cmap="coolwarm")
ax.contour(X, Y, Z, zdir='x', offset=-40, cmap="coolwarm")
ax.contour(X, Y, Z, zdir='y', offset=40, cmap="coolwarm")
ax.axis(xmin=-40, xmax=40, ymin=-40, ymax=40, zmin=-100, zmax=100)
@mpl3d_image_comparison(['contour3d_extend3d.png'], style='mpl20')
def test_contour3d_extend3d():
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contour(X, Y, Z, zdir='z', offset=-100, cmap="coolwarm", extend3d=True)
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 40)
ax.set_zlim(-80, 80)
@mpl3d_image_comparison(['contourf3d.png'], style='mpl20')
def test_contourf3d():
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap="coolwarm")
ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap="coolwarm")
ax.contourf(X, Y, Z, zdir='y', offset=40, cmap="coolwarm")
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_zlim(-100, 100)
@mpl3d_image_comparison(['contourf3d_fill.png'], style='mpl20')
def test_contourf3d_fill():
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y = np.meshgrid(np.arange(-2, 2, 0.25), np.arange(-2, 2, 0.25))
Z = X.clip(0, 0)
# This produces holes in the z=0 surface that causes rendering errors if
# the Poly3DCollection is not aware of path code information (issue #4784)
Z[::5, ::5] = 0.1
ax.contourf(X, Y, Z, offset=0, levels=[-0.1, 0], cmap="coolwarm")
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-1, 1)
@pytest.mark.parametrize('extend, levels', [['both', [2, 4, 6]],
['min', [2, 4, 6, 8]],
['max', [0, 2, 4, 6]]])
@check_figures_equal()
def test_contourf3d_extend(fig_test, fig_ref, extend, levels):
X, Y = np.meshgrid(np.arange(-2, 2, 0.25), np.arange(-2, 2, 0.25))
# Z is in the range [0, 8]
Z = X**2 + Y**2
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.contourf(X, Y, Z, levels=[0, 2, 4, 6, 8], vmin=1, vmax=7)
ax_test = fig_test.add_subplot(projection='3d')
ax_test.contourf(X, Y, Z, levels, extend=extend, vmin=1, vmax=7)
for ax in [ax_ref, ax_test]:
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-10, 10)
@mpl3d_image_comparison(['tricontour.png'], tol=0.02, style='mpl20')
def test_tricontour():
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure()
np.random.seed(19680801)
x = np.random.rand(1000) - 0.5
y = np.random.rand(1000) - 0.5
z = -(x**2 + y**2)
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.tricontour(x, y, z)
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.tricontourf(x, y, z)
def test_contour3d_1d_input():
# Check that 1D sequences of different length for {x, y} doesn't error
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
nx, ny = 30, 20
x = np.linspace(-10, 10, nx)
y = np.linspace(-10, 10, ny)
z = np.random.randint(0, 2, [ny, nx])
ax.contour(x, y, z, [0.5])
@mpl3d_image_comparison(['lines3d.png'], style='mpl20')
def test_lines3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z)
@check_figures_equal()
def test_plot_scalar(fig_test, fig_ref):
ax1 = fig_test.add_subplot(projection='3d')
ax1.plot([1], [1], "o")
ax2 = fig_ref.add_subplot(projection='3d')
ax2.plot(1, 1, "o")
def test_invalid_line_data():
with pytest.raises(RuntimeError, match='x must be'):
art3d.Line3D(0, [], [])
with pytest.raises(RuntimeError, match='y must be'):
art3d.Line3D([], 0, [])
with pytest.raises(RuntimeError, match='z must be'):
art3d.Line3D([], [], 0)
line = art3d.Line3D([], [], [])
with pytest.raises(RuntimeError, match='x must be'):
line.set_data_3d(0, [], [])
with pytest.raises(RuntimeError, match='y must be'):
line.set_data_3d([], 0, [])
with pytest.raises(RuntimeError, match='z must be'):
line.set_data_3d([], [], 0)
@mpl3d_image_comparison(['mixedsubplot.png'], style='mpl20')
def test_mixedsubplots():
def f(t):
return np.cos(2*np.pi*t) * np.exp(-t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
fig = plt.figure(figsize=plt.figaspect(2.))
ax = fig.add_subplot(2, 1, 1)
ax.plot(t1, f(t1), 'bo', t2, f(t2), 'k--', markerfacecolor='green')
ax.grid(True)
ax = fig.add_subplot(2, 1, 2, projection='3d')
X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25))
R = np.hypot(X, Y)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rcount=40, ccount=40,
linewidth=0, antialiased=False)
ax.set_zlim3d(-1, 1)
@check_figures_equal()
def test_tight_layout_text(fig_test, fig_ref):
# text is currently ignored in tight layout. So the order of text() and
# tight_layout() calls should not influence the result.
ax1 = fig_test.add_subplot(projection='3d')
ax1.text(.5, .5, .5, s='some string')
fig_test.tight_layout()
ax2 = fig_ref.add_subplot(projection='3d')
fig_ref.tight_layout()
ax2.text(.5, .5, .5, s='some string')
@mpl3d_image_comparison(['scatter3d.png'], style='mpl20')
def test_scatter3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter(np.arange(10), np.arange(10), np.arange(10),
c='r', marker='o')
x = y = z = np.arange(10, 20)
ax.scatter(x, y, z, c='b', marker='^')
z[-1] = 0 # Check that scatter() copies the data.
# Ensure empty scatters do not break.
ax.scatter([], [], [], c='r', marker='X')
@mpl3d_image_comparison(['scatter3d_color.png'], style='mpl20')
def test_scatter3d_color():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# Check that 'none' color works; these two should overlay to produce the
# same as setting just `color`.
ax.scatter(np.arange(10), np.arange(10), np.arange(10),
facecolor='r', edgecolor='none', marker='o')
ax.scatter(np.arange(10), np.arange(10), np.arange(10),
facecolor='none', edgecolor='r', marker='o')
ax.scatter(np.arange(10, 20), np.arange(10, 20), np.arange(10, 20),
color='b', marker='s')
@mpl3d_image_comparison(['scatter3d_linewidth.png'], style='mpl20')
def test_scatter3d_linewidth():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# Check that array-like linewidth can be set
ax.scatter(np.arange(10), np.arange(10), np.arange(10),
marker='o', linewidth=np.arange(10))
@check_figures_equal()
def test_scatter3d_linewidth_modification(fig_ref, fig_test):
# Changing Path3DCollection linewidths with array-like post-creation
# should work correctly.
ax_test = fig_test.add_subplot(projection='3d')
c = ax_test.scatter(np.arange(10), np.arange(10), np.arange(10),
marker='o')
c.set_linewidths(np.arange(10))
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.scatter(np.arange(10), np.arange(10), np.arange(10), marker='o',
linewidths=np.arange(10))
@check_figures_equal()
def test_scatter3d_modification(fig_ref, fig_test):
# Changing Path3DCollection properties post-creation should work correctly.
ax_test = fig_test.add_subplot(projection='3d')
c = ax_test.scatter(np.arange(10), np.arange(10), np.arange(10),
marker='o', depthshade=True)
c.set_facecolor('C1')
c.set_edgecolor('C2')
c.set_alpha([0.3, 0.7] * 5)
assert c.get_depthshade()
c.set_depthshade(False)
assert not c.get_depthshade()
c.set_sizes(np.full(10, 75))
c.set_linewidths(3)
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.scatter(np.arange(10), np.arange(10), np.arange(10), marker='o',
facecolor='C1', edgecolor='C2', alpha=[0.3, 0.7] * 5,
depthshade=False, s=75, linewidths=3)
@check_figures_equal()
def test_scatter3d_sorting(fig_ref, fig_test):
"""Test that marker properties are correctly sorted."""
y, x = np.mgrid[:10, :10]
z = np.arange(x.size).reshape(x.shape)
depthshade = False
sizes = np.full(z.shape, 25)
sizes[0::2, 0::2] = 100
sizes[1::2, 1::2] = 100
facecolors = np.full(z.shape, 'C0')
facecolors[:5, :5] = 'C1'
facecolors[6:, :4] = 'C2'
facecolors[6:, 6:] = 'C3'
edgecolors = np.full(z.shape, 'C4')
edgecolors[1:5, 1:5] = 'C5'
edgecolors[5:9, 1:5] = 'C6'
edgecolors[5:9, 5:9] = 'C7'
linewidths = np.full(z.shape, 2)
linewidths[0::2, 0::2] = 5
linewidths[1::2, 1::2] = 5
x, y, z, sizes, facecolors, edgecolors, linewidths = (
a.flatten()
for a in [x, y, z, sizes, facecolors, edgecolors, linewidths]
)
ax_ref = fig_ref.add_subplot(projection='3d')
sets = (np.unique(a) for a in [sizes, facecolors, edgecolors, linewidths])
for s, fc, ec, lw in itertools.product(*sets):
subset = (
(sizes != s) |
(facecolors != fc) |
(edgecolors != ec) |
(linewidths != lw)
)
subset = np.ma.masked_array(z, subset, dtype=float)
# When depth shading is disabled, the colors are passed through as
# single-item lists; this triggers single path optimization. The
# following reshaping is a hack to disable that, since the optimization
# would not occur for the full scatter which has multiple colors.
fc = np.repeat(fc, sum(~subset.mask))
ax_ref.scatter(x, y, subset, s=s, fc=fc, ec=ec, lw=lw, alpha=1,
depthshade=depthshade)
ax_test = fig_test.add_subplot(projection='3d')
ax_test.scatter(x, y, z, s=sizes, fc=facecolors, ec=edgecolors,
lw=linewidths, alpha=1, depthshade=depthshade)
@pytest.mark.parametrize('azim', [-50, 130]) # yellow first, blue first
@check_figures_equal()
def test_marker_draw_order_data_reversed(fig_test, fig_ref, azim):
"""
Test that the draw order does not depend on the data point order.
For the given viewing angle at azim=-50, the yellow marker should be in
front. For azim=130, the blue marker should be in front.
"""
x = [-1, 1]
y = [1, -1]
z = [0, 0]
color = ['b', 'y']
ax = fig_test.add_subplot(projection='3d')
ax.scatter(x, y, z, s=3500, c=color)
ax.view_init(elev=0, azim=azim, roll=0)
ax = fig_ref.add_subplot(projection='3d')
ax.scatter(x[::-1], y[::-1], z[::-1], s=3500, c=color[::-1])
ax.view_init(elev=0, azim=azim, roll=0)
@check_figures_equal()
def test_marker_draw_order_view_rotated(fig_test, fig_ref):
"""
Test that the draw order changes with the direction.
If we rotate *azim* by 180 degrees and exchange the colors, the plot
plot should look the same again.
"""
azim = 130
x = [-1, 1]
y = [1, -1]
z = [0, 0]
color = ['b', 'y']
ax = fig_test.add_subplot(projection='3d')
# axis are not exactly invariant under 180 degree rotation -> deactivate
ax.set_axis_off()
ax.scatter(x, y, z, s=3500, c=color)
ax.view_init(elev=0, azim=azim, roll=0)
ax = fig_ref.add_subplot(projection='3d')
ax.set_axis_off()
ax.scatter(x, y, z, s=3500, c=color[::-1]) # color reversed
ax.view_init(elev=0, azim=azim - 180, roll=0) # view rotated by 180 deg
@mpl3d_image_comparison(['plot_3d_from_2d.png'], tol=0.019, style='mpl20')
def test_plot_3d_from_2d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
xs = np.arange(0, 5)
ys = np.arange(5, 10)
ax.plot(xs, ys, zs=0, zdir='x')
ax.plot(xs, ys, zs=0, zdir='y')
@mpl3d_image_comparison(['fill_between_quad.png'], style='mpl20')
def test_fill_between_quad():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
theta = np.linspace(0, 2*np.pi, 50)
x1 = np.cos(theta)
y1 = np.sin(theta)
z1 = 0.1 * np.sin(6 * theta)
x2 = 0.6 * np.cos(theta)
y2 = 0.6 * np.sin(theta)
z2 = 2
where = (theta < np.pi/2) | (theta > 3*np.pi/2)
# Since none of x1 == x2, y1 == y2, or z1 == z2 is True, the fill_between
# mode will map to 'quad'
ax.fill_between(x1, y1, z1, x2, y2, z2,
where=where, mode='auto', alpha=0.5, edgecolor='k')
@mpl3d_image_comparison(['fill_between_polygon.png'], style='mpl20')
def test_fill_between_polygon():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
theta = np.linspace(0, 2*np.pi, 50)
x1 = x2 = theta
y1 = y2 = 0
z1 = np.cos(theta)
z2 = z1 + 1
where = (theta < np.pi/2) | (theta > 3*np.pi/2)
# Since x1 == x2 and y1 == y2, the fill_between mode will be 'polygon'
ax.fill_between(x1, y1, z1, x2, y2, z2,
where=where, mode='auto', edgecolor='k')
@mpl3d_image_comparison(['surface3d.png'], style='mpl20')
def test_surface3d():
# Remove this line when this test image is regenerated.
plt.rcParams['pcolormesh.snap'] = False
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.hypot(X, Y)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40, cmap="coolwarm",
lw=0, antialiased=False)
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=5)
@image_comparison(['surface3d_label_offset_tick_position.png'], style='mpl20')
def test_surface3d_label_offset_tick_position():
ax = plt.figure().add_subplot(projection="3d")
x, y = np.mgrid[0:6 * np.pi:0.25, 0:4 * np.pi:0.25]
z = np.sqrt(np.abs(np.cos(x) + np.cos(y)))
ax.plot_surface(x * 1e5, y * 1e6, z * 1e8, cmap='autumn', cstride=2, rstride=2)
ax.set_xlabel("X label")
ax.set_ylabel("Y label")
ax.set_zlabel("Z label")
@mpl3d_image_comparison(['surface3d_shaded.png'], style='mpl20')
def test_surface3d_shaded():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=5, cstride=5,
color=[0.25, 1, 0.25], lw=1, antialiased=False)
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
ax.set_zlim(-1.01, 1.01)
@mpl3d_image_comparison(['surface3d_masked.png'], style='mpl20')
def test_surface3d_masked():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y = [1, 2, 3, 4, 5, 6, 7, 8]
x, y = np.meshgrid(x, y)
matrix = np.array(
[
[-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 1, 2, 3, 4, 4, 4, 3, 2, 1, 1],
[-1, -1., 4, 5, 6, 8, 6, 5, 4, 3, -1.],
[-1, -1., 7, 8, 11, 12, 11, 8, 7, -1., -1.],
[-1, -1., 8, 9, 10, 16, 10, 9, 10, 7, -1.],
[-1, -1., -1., 12, 16, 20, 16, 12, 11, -1., -1.],
[-1, -1., -1., -1., 22, 24, 22, 20, 18, -1., -1.],
[-1, -1., -1., -1., -1., 28, 26, 25, -1., -1., -1.],
]
)
z = np.ma.masked_less(matrix, 0)
norm = mcolors.Normalize(vmax=z.max(), vmin=z.min())
colors = mpl.colormaps["plasma"](norm(z))
ax.plot_surface(x, y, z, facecolors=colors)
ax.view_init(30, -80, 0)
@check_figures_equal()
def test_plot_scatter_masks(fig_test, fig_ref):
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
z = np.sin(x) * np.cos(y)
mask = z > 0
z_masked = np.ma.array(z, mask=mask)
ax_test = fig_test.add_subplot(projection='3d')
ax_test.scatter(x, y, z_masked)
ax_test.plot(x, y, z_masked)
x[mask] = y[mask] = z[mask] = np.nan
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.scatter(x, y, z)
ax_ref.plot(x, y, z)
@check_figures_equal()
def test_plot_surface_None_arg(fig_test, fig_ref):
x, y = np.meshgrid(np.arange(5), np.arange(5))
z = x + y
ax_test = fig_test.add_subplot(projection='3d')
ax_test.plot_surface(x, y, z, facecolors=None)
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.plot_surface(x, y, z)
@mpl3d_image_comparison(['surface3d_masked_strides.png'], style='mpl20')
def test_surface3d_masked_strides():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x, y = np.mgrid[-6:6.1:1, -6:6.1:1]
z = np.ma.masked_less(x * y, 2)
ax.plot_surface(x, y, z, rstride=4, cstride=4)
ax.view_init(60, -45, 0)
@mpl3d_image_comparison(['text3d.png'], remove_text=False, style='mpl20')
def test_text3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (2, 6, 4, 9, 7, 2)
ys = (6, 4, 8, 7, 2, 2)
zs = (4, 2, 5, 6, 1, 7)
for zdir, x, y, z in zip(zdirs, xs, ys, zs):
label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)
ax.text(x, y, z, label, zdir)
ax.text(1, 1, 1, "red", color='red')
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)
plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated
ax.set_xlim3d(0, 10)
ax.set_ylim3d(0, 10)
ax.set_zlim3d(0, 10)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
@check_figures_equal()
def test_text3d_modification(fig_ref, fig_test):
# Modifying the Text position after the fact should work the same as
# setting it directly.
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (2, 6, 4, 9, 7, 2)
ys = (6, 4, 8, 7, 2, 2)
zs = (4, 2, 5, 6, 1, 7)
ax_test = fig_test.add_subplot(projection='3d')
ax_test.set_xlim3d(0, 10)
ax_test.set_ylim3d(0, 10)
ax_test.set_zlim3d(0, 10)
for zdir, x, y, z in zip(zdirs, xs, ys, zs):
t = ax_test.text(0, 0, 0, f'({x}, {y}, {z}), dir={zdir}')
t.set_position_3d((x, y, z), zdir=zdir)
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.set_xlim3d(0, 10)
ax_ref.set_ylim3d(0, 10)
ax_ref.set_zlim3d(0, 10)
for zdir, x, y, z in zip(zdirs, xs, ys, zs):
ax_ref.text(x, y, z, f'({x}, {y}, {z}), dir={zdir}', zdir=zdir)
@mpl3d_image_comparison(['trisurf3d.png'], tol=0.061, style='mpl20')
def test_trisurf3d():
n_angles = 36
n_radii = 8
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
z = np.sin(-x*y)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_trisurf(x, y, z, cmap="jet", linewidth=0.2)
@mpl3d_image_comparison(['trisurf3d_shaded.png'], tol=0.03, style='mpl20')
def test_trisurf3d_shaded():
n_angles = 36
n_radii = 8
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
z = np.sin(-x*y)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_trisurf(x, y, z, color=[1, 0.5, 0], linewidth=0.2)
@mpl3d_image_comparison(['wireframe3d.png'], style='mpl20')
def test_wireframe3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rcount=13, ccount=13)
@mpl3d_image_comparison(['wireframe3dasymmetric.png'], style='mpl20')
def test_wireframe3dasymmetric():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rcount=3, ccount=13)
@mpl3d_image_comparison(['wireframe3dzerocstride.png'], style='mpl20')
def test_wireframe3dzerocstride():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rcount=13, ccount=0)
@mpl3d_image_comparison(['wireframe3dzerorstride.png'], style='mpl20')
def test_wireframe3dzerorstride():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=0, cstride=10)
def test_wireframe3dzerostrideraises():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
with pytest.raises(ValueError):
ax.plot_wireframe(X, Y, Z, rstride=0, cstride=0)
def test_mixedsamplesraises():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
with pytest.raises(ValueError):
ax.plot_wireframe(X, Y, Z, rstride=10, ccount=50)
with pytest.raises(ValueError):
ax.plot_surface(X, Y, Z, cstride=50, rcount=10)
# remove tolerance when regenerating the test image
@mpl3d_image_comparison(['quiver3d.png'], style='mpl20', tol=0.003)
def test_quiver3d():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
pivots = ['tip', 'middle', 'tail']
colors = ['tab:blue', 'tab:orange', 'tab:green']
for i, (pivot, color) in enumerate(zip(pivots, colors)):
x, y, z = np.meshgrid([-0.5, 0.5], [-0.5, 0.5], [-0.5, 0.5])
u = -x
v = -y
w = -z
# Offset each set in z direction
z += 2 * i
ax.quiver(x, y, z, u, v, w, length=1, pivot=pivot, color=color)
ax.scatter(x, y, z, color=color)
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)
ax.set_zlim(-1, 5)
@check_figures_equal()
def test_quiver3d_empty(fig_test, fig_ref):
fig_ref.add_subplot(projection='3d')
x = y = z = u = v = w = []
ax = fig_test.add_subplot(projection='3d')
ax.quiver(x, y, z, u, v, w, length=0.1, pivot='tip', normalize=True)
@mpl3d_image_comparison(['quiver3d_masked.png'], style='mpl20')
def test_quiver3d_masked():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# Using mgrid here instead of ogrid because masked_where doesn't
# seem to like broadcasting very much...
x, y, z = np.mgrid[-1:0.8:10j, -1:0.8:10j, -1:0.6:3j]
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (2/3)**0.5 * np.cos(np.pi * x) * np.cos(np.pi * y) * np.sin(np.pi * z)
u = np.ma.masked_where((-0.4 < x) & (x < 0.1), u, copy=False)
v = np.ma.masked_where((0.1 < y) & (y < 0.7), v, copy=False)
ax.quiver(x, y, z, u, v, w, length=0.1, pivot='tip', normalize=True)
@mpl3d_image_comparison(['quiver3d_colorcoded.png'], style='mpl20')
def test_quiver3d_colorcoded():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x = y = dx = dz = np.zeros(10)
z = dy = np.arange(10.)
color = plt.colormaps["Reds"](dy/dy.max())
ax.quiver(x, y, z, dx, dy, dz, colors=color)
ax.set_ylim(0, 10)
def test_patch_modification():
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
circle = Circle((0, 0))
ax.add_patch(circle)
art3d.patch_2d_to_3d(circle)
circle.set_facecolor((1.0, 0.0, 0.0, 1))
assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1))
fig.canvas.draw()
assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1))
@check_figures_equal()
def test_patch_collection_modification(fig_test, fig_ref):
# Test that modifying Patch3DCollection properties after creation works.
patch1 = Circle((0, 0), 0.05)
patch2 = Circle((0.1, 0.1), 0.03)
facecolors = np.array([[0., 0.5, 0., 1.], [0.5, 0., 0., 0.5]])
c = art3d.Patch3DCollection([patch1, patch2], linewidths=3, depthshade=True)
ax_test = fig_test.add_subplot(projection='3d')
ax_test.add_collection3d(c)
c.set_edgecolor('C2')
c.set_facecolor(facecolors)
c.set_alpha(0.7)
assert c.get_depthshade()
c.set_depthshade(False)
assert not c.get_depthshade()
patch1 = Circle((0, 0), 0.05)
patch2 = Circle((0.1, 0.1), 0.03)
facecolors = np.array([[0., 0.5, 0., 1.], [0.5, 0., 0., 0.5]])
c = art3d.Patch3DCollection([patch1, patch2], linewidths=3,
edgecolor='C2', facecolor=facecolors,
alpha=0.7, depthshade=False)
ax_ref = fig_ref.add_subplot(projection='3d')
ax_ref.add_collection3d(c)
def test_poly3dcollection_verts_validation():
poly = [[0, 0, 1], [0, 1, 1], [0, 1, 0], [0, 0, 0]]
with pytest.raises(ValueError, match=r'list of \(N, 3\) array-like'):
art3d.Poly3DCollection(poly) # should be Poly3DCollection([poly])
poly = np.array(poly, dtype=float)
with pytest.raises(ValueError, match=r'shape \(M, N, 3\)'):
art3d.Poly3DCollection(poly) # should be Poly3DCollection([poly])
@mpl3d_image_comparison(['poly3dcollection_closed.png'], style='mpl20')
def test_poly3dcollection_closed():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float)
c1 = art3d.Poly3DCollection([poly1], linewidths=3, edgecolor='k',