-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
test_axes.py
8162 lines (6552 loc) · 266 KB
/
test_axes.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
from collections import namedtuple
import datetime
from decimal import Decimal
from functools import partial
import inspect
import io
from itertools import product
import platform
from types import SimpleNamespace
import dateutil.tz
import numpy as np
from numpy import ma
from cycler import cycler
import pytest
import matplotlib
import matplotlib as mpl
from matplotlib import rc_context
from matplotlib._api import MatplotlibDeprecationWarning
import matplotlib.colors as mcolors
import matplotlib.dates as mdates
from matplotlib.figure import Figure
from matplotlib.axes import Axes
import matplotlib.font_manager as mfont_manager
import matplotlib.markers as mmarkers
import matplotlib.patches as mpatches
import matplotlib.path as mpath
from matplotlib.projections.geo import HammerAxes
from matplotlib.projections.polar import PolarAxes
import matplotlib.pyplot as plt
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import mpl_toolkits.axisartist as AA
from numpy.testing import (
assert_allclose, assert_array_equal, assert_array_almost_equal)
from matplotlib.testing.decorators import (
image_comparison, check_figures_equal, remove_ticks_and_titles)
# Note: Some test cases are run twice: once normally and once with labeled data
# These two must be defined in the same test function or need to have
# different baseline images to prevent race conditions when pytest runs
# the tests with multiple threads.
@check_figures_equal(extensions=["png"])
def test_invisible_axes(fig_test, fig_ref):
ax = fig_test.subplots()
ax.set_visible(False)
def test_get_labels():
fig, ax = plt.subplots()
ax.set_xlabel('x label')
ax.set_ylabel('y label')
assert ax.get_xlabel() == 'x label'
assert ax.get_ylabel() == 'y label'
def test_repr():
fig, ax = plt.subplots()
ax.set_label('label')
ax.set_title('title')
ax.set_xlabel('x')
ax.set_ylabel('y')
assert repr(ax) == (
"<AxesSubplot: "
"label='label', title={'center': 'title'}, xlabel='x', ylabel='y'>")
@check_figures_equal()
def test_label_loc_vertical(fig_test, fig_ref):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label', loc='top')
ax.set_xlabel('X Label', loc='right')
cbar = fig_test.colorbar(sc)
cbar.set_label("Z Label", loc='top')
ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label', y=1, ha='right')
ax.set_xlabel('X Label', x=1, ha='right')
cbar = fig_ref.colorbar(sc)
cbar.set_label("Z Label", y=1, ha='right')
@check_figures_equal()
def test_label_loc_horizontal(fig_test, fig_ref):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label', loc='bottom')
ax.set_xlabel('X Label', loc='left')
cbar = fig_test.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", loc='left')
ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label', y=0, ha='left')
ax.set_xlabel('X Label', x=0, ha='left')
cbar = fig_ref.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", x=0, ha='left')
@check_figures_equal()
def test_label_loc_rc(fig_test, fig_ref):
with matplotlib.rc_context({"xaxis.labellocation": "right",
"yaxis.labellocation": "top"}):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label')
ax.set_xlabel('X Label')
cbar = fig_test.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label")
ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2], label='scatter')
ax.legend()
ax.set_ylabel('Y Label', y=1, ha='right')
ax.set_xlabel('X Label', x=1, ha='right')
cbar = fig_ref.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", x=1, ha='right')
def test_label_shift():
fig, ax = plt.subplots()
# Test label re-centering on x-axis
ax.set_xlabel("Test label", loc="left")
ax.set_xlabel("Test label", loc="center")
assert ax.xaxis.get_label().get_horizontalalignment() == "center"
ax.set_xlabel("Test label", loc="right")
assert ax.xaxis.get_label().get_horizontalalignment() == "right"
ax.set_xlabel("Test label", loc="center")
assert ax.xaxis.get_label().get_horizontalalignment() == "center"
# Test label re-centering on y-axis
ax.set_ylabel("Test label", loc="top")
ax.set_ylabel("Test label", loc="center")
assert ax.yaxis.get_label().get_horizontalalignment() == "center"
ax.set_ylabel("Test label", loc="bottom")
assert ax.yaxis.get_label().get_horizontalalignment() == "left"
ax.set_ylabel("Test label", loc="center")
assert ax.yaxis.get_label().get_horizontalalignment() == "center"
@check_figures_equal(extensions=["png"])
def test_acorr(fig_test, fig_ref):
np.random.seed(19680801)
Nx = 512
x = np.random.normal(0, 1, Nx).cumsum()
maxlags = Nx-1
ax_test = fig_test.subplots()
ax_test.acorr(x, maxlags=maxlags)
ax_ref = fig_ref.subplots()
# Normalized autocorrelation
norm_auto_corr = np.correlate(x, x, mode="full")/np.dot(x, x)
lags = np.arange(-maxlags, maxlags+1)
norm_auto_corr = norm_auto_corr[Nx-1-maxlags:Nx+maxlags]
ax_ref.vlines(lags, [0], norm_auto_corr)
ax_ref.axhline(y=0, xmin=0, xmax=1)
@check_figures_equal(extensions=["png"])
def test_spy(fig_test, fig_ref):
np.random.seed(19680801)
a = np.ones(32 * 32)
a[:16 * 32] = 0
np.random.shuffle(a)
a = a.reshape((32, 32))
axs_test = fig_test.subplots(2)
axs_test[0].spy(a)
axs_test[1].spy(a, marker=".", origin="lower")
axs_ref = fig_ref.subplots(2)
axs_ref[0].imshow(a, cmap="gray_r", interpolation="nearest")
axs_ref[0].xaxis.tick_top()
axs_ref[1].plot(*np.nonzero(a)[::-1], ".", markersize=10)
axs_ref[1].set(
aspect=1, xlim=axs_ref[0].get_xlim(), ylim=axs_ref[0].get_ylim()[::-1])
for ax in axs_ref:
ax.xaxis.set_ticks_position("both")
def test_spy_invalid_kwargs():
fig, ax = plt.subplots()
for unsupported_kw in [{'interpolation': 'nearest'},
{'marker': 'o', 'linestyle': 'solid'}]:
with pytest.raises(TypeError):
ax.spy(np.eye(3, 3), **unsupported_kw)
@check_figures_equal(extensions=["png"])
def test_matshow(fig_test, fig_ref):
mpl.style.use("mpl20")
a = np.random.rand(32, 32)
fig_test.add_subplot().matshow(a)
ax_ref = fig_ref.add_subplot()
ax_ref.imshow(a)
ax_ref.xaxis.tick_top()
ax_ref.xaxis.set_ticks_position('both')
@image_comparison(['formatter_ticker_001',
'formatter_ticker_002',
'formatter_ticker_003',
'formatter_ticker_004',
'formatter_ticker_005',
])
def test_formatter_ticker():
import matplotlib.testing.jpl_units as units
units.register()
# This should affect the tick size. (Tests issue #543)
matplotlib.rcParams['lines.markeredgewidth'] = 30
# This essentially test to see if user specified labels get overwritten
# by the auto labeler functionality of the axes.
xdata = [x*units.sec for x in range(10)]
ydata1 = [(1.5*y - 0.5)*units.km for y in range(10)]
ydata2 = [(1.75*y - 1.0)*units.km for y in range(10)]
ax = plt.figure().subplots()
ax.set_xlabel("x-label 001")
ax = plt.figure().subplots()
ax.set_xlabel("x-label 001")
ax.plot(xdata, ydata1, color='blue', xunits="sec")
ax = plt.figure().subplots()
ax.set_xlabel("x-label 001")
ax.plot(xdata, ydata1, color='blue', xunits="sec")
ax.set_xlabel("x-label 003")
ax = plt.figure().subplots()
ax.plot(xdata, ydata1, color='blue', xunits="sec")
ax.plot(xdata, ydata2, color='green', xunits="hour")
ax.set_xlabel("x-label 004")
# See SF bug 2846058
# https://sourceforge.net/tracker/?func=detail&aid=2846058&group_id=80706&atid=560720
ax = plt.figure().subplots()
ax.plot(xdata, ydata1, color='blue', xunits="sec")
ax.plot(xdata, ydata2, color='green', xunits="hour")
ax.set_xlabel("x-label 005")
ax.autoscale_view()
def test_funcformatter_auto_formatter():
def _formfunc(x, pos):
return ''
ax = plt.figure().subplots()
assert ax.xaxis.isDefault_majfmt
assert ax.xaxis.isDefault_minfmt
assert ax.yaxis.isDefault_majfmt
assert ax.yaxis.isDefault_minfmt
ax.xaxis.set_major_formatter(_formfunc)
assert not ax.xaxis.isDefault_majfmt
assert ax.xaxis.isDefault_minfmt
assert ax.yaxis.isDefault_majfmt
assert ax.yaxis.isDefault_minfmt
targ_funcformatter = mticker.FuncFormatter(_formfunc)
assert isinstance(ax.xaxis.get_major_formatter(),
mticker.FuncFormatter)
assert ax.xaxis.get_major_formatter().func == targ_funcformatter.func
def test_strmethodformatter_auto_formatter():
formstr = '{x}_{pos}'
ax = plt.figure().subplots()
assert ax.xaxis.isDefault_majfmt
assert ax.xaxis.isDefault_minfmt
assert ax.yaxis.isDefault_majfmt
assert ax.yaxis.isDefault_minfmt
ax.yaxis.set_minor_formatter(formstr)
assert ax.xaxis.isDefault_majfmt
assert ax.xaxis.isDefault_minfmt
assert ax.yaxis.isDefault_majfmt
assert not ax.yaxis.isDefault_minfmt
targ_strformatter = mticker.StrMethodFormatter(formstr)
assert isinstance(ax.yaxis.get_minor_formatter(),
mticker.StrMethodFormatter)
assert ax.yaxis.get_minor_formatter().fmt == targ_strformatter.fmt
@image_comparison(["twin_axis_locators_formatters"])
def test_twin_axis_locators_formatters():
vals = np.linspace(0, 1, num=5, endpoint=True)
locs = np.sin(np.pi * vals / 2.0)
majl = plt.FixedLocator(locs)
minl = plt.FixedLocator([0.1, 0.2, 0.3])
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax1.plot([0.1, 100], [0, 1])
ax1.yaxis.set_major_locator(majl)
ax1.yaxis.set_minor_locator(minl)
ax1.yaxis.set_major_formatter(plt.FormatStrFormatter('%08.2lf'))
ax1.yaxis.set_minor_formatter(plt.FixedFormatter(['tricks', 'mind',
'jedi']))
ax1.xaxis.set_major_locator(plt.LinearLocator())
ax1.xaxis.set_minor_locator(plt.FixedLocator([15, 35, 55, 75]))
ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%05.2lf'))
ax1.xaxis.set_minor_formatter(plt.FixedFormatter(['c', '3', 'p', 'o']))
ax1.twiny()
ax1.twinx()
def test_twinx_cla():
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax3 = ax2.twiny()
plt.draw()
assert not ax2.xaxis.get_visible()
assert not ax2.patch.get_visible()
ax2.cla()
ax3.cla()
assert not ax2.xaxis.get_visible()
assert not ax2.patch.get_visible()
assert ax2.yaxis.get_visible()
assert ax3.xaxis.get_visible()
assert not ax3.patch.get_visible()
assert not ax3.yaxis.get_visible()
assert ax.xaxis.get_visible()
assert ax.patch.get_visible()
assert ax.yaxis.get_visible()
@pytest.mark.parametrize('twin', ('x', 'y'))
@check_figures_equal(extensions=['png'], tol=0.19)
def test_twin_logscale(fig_test, fig_ref, twin):
twin_func = f'twin{twin}' # test twinx or twiny
set_scale = f'set_{twin}scale'
x = np.arange(1, 100)
# Change scale after twinning.
ax_test = fig_test.add_subplot(2, 1, 1)
ax_twin = getattr(ax_test, twin_func)()
getattr(ax_test, set_scale)('log')
ax_twin.plot(x, x)
# Twin after changing scale.
ax_test = fig_test.add_subplot(2, 1, 2)
getattr(ax_test, set_scale)('log')
ax_twin = getattr(ax_test, twin_func)()
ax_twin.plot(x, x)
for i in [1, 2]:
ax_ref = fig_ref.add_subplot(2, 1, i)
getattr(ax_ref, set_scale)('log')
ax_ref.plot(x, x)
# This is a hack because twinned Axes double-draw the frame.
# Remove this when that is fixed.
Path = matplotlib.path.Path
fig_ref.add_artist(
matplotlib.patches.PathPatch(
Path([[0, 0], [0, 1],
[0, 1], [1, 1],
[1, 1], [1, 0],
[1, 0], [0, 0]],
[Path.MOVETO, Path.LINETO] * 4),
transform=ax_ref.transAxes,
facecolor='none',
edgecolor=mpl.rcParams['axes.edgecolor'],
linewidth=mpl.rcParams['axes.linewidth'],
capstyle='projecting'))
remove_ticks_and_titles(fig_test)
remove_ticks_and_titles(fig_ref)
@image_comparison(['twin_autoscale.png'])
def test_twinx_axis_scales():
x = np.array([0, 0.5, 1])
y = 0.5 * x
x2 = np.array([0, 1, 2])
y2 = 2 * x2
fig = plt.figure()
ax = fig.add_axes((0, 0, 1, 1), autoscalex_on=False, autoscaley_on=False)
ax.plot(x, y, color='blue', lw=10)
ax2 = plt.twinx(ax)
ax2.plot(x2, y2, 'r--', lw=5)
ax.margins(0, 0)
ax2.margins(0, 0)
def test_twin_inherit_autoscale_setting():
fig, ax = plt.subplots()
ax_x_on = ax.twinx()
ax.set_autoscalex_on(False)
ax_x_off = ax.twinx()
assert ax_x_on.get_autoscalex_on()
assert not ax_x_off.get_autoscalex_on()
ax_y_on = ax.twiny()
ax.set_autoscaley_on(False)
ax_y_off = ax.twiny()
assert ax_y_on.get_autoscaley_on()
assert not ax_y_off.get_autoscaley_on()
def test_inverted_cla():
# GitHub PR #5450. Setting autoscale should reset
# axes to be non-inverted.
# plotting an image, then 1d graph, axis is now down
fig = plt.figure(0)
ax = fig.gca()
# 1. test that a new axis is not inverted per default
assert not ax.xaxis_inverted()
assert not ax.yaxis_inverted()
img = np.random.random((100, 100))
ax.imshow(img)
# 2. test that a image axis is inverted
assert not ax.xaxis_inverted()
assert ax.yaxis_inverted()
# 3. test that clearing and plotting a line, axes are
# not inverted
ax.cla()
x = np.linspace(0, 2*np.pi, 100)
ax.plot(x, np.cos(x))
assert not ax.xaxis_inverted()
assert not ax.yaxis_inverted()
# 4. autoscaling should not bring back axes to normal
ax.cla()
ax.imshow(img)
plt.autoscale()
assert not ax.xaxis_inverted()
assert ax.yaxis_inverted()
for ax in fig.axes:
ax.remove()
# 5. two shared axes. Inverting the leader axis should invert the shared
# axes; clearing the leader axis should bring axes in shared
# axes back to normal.
ax0 = plt.subplot(211)
ax1 = plt.subplot(212, sharey=ax0)
ax0.yaxis.set_inverted(True)
assert ax1.yaxis_inverted()
ax1.plot(x, np.cos(x))
ax0.cla()
assert not ax1.yaxis_inverted()
ax1.cla()
# 6. clearing the follower should not touch limits
ax0.imshow(img)
ax1.plot(x, np.cos(x))
ax1.cla()
assert ax.yaxis_inverted()
# clean up
plt.close(fig)
def test_subclass_clear_cla():
# Ensure that subclasses of Axes call cla/clear correctly.
# Note, we cannot use mocking here as we want to be sure that the
# superclass fallback does not recurse.
with pytest.warns(PendingDeprecationWarning,
match='Overriding `Axes.cla`'):
class ClaAxes(Axes):
def cla(self):
nonlocal called
called = True
with pytest.warns(PendingDeprecationWarning,
match='Overriding `Axes.cla`'):
class ClaSuperAxes(Axes):
def cla(self):
nonlocal called
called = True
super().cla()
class SubClaAxes(ClaAxes):
pass
class ClearAxes(Axes):
def clear(self):
nonlocal called
called = True
class ClearSuperAxes(Axes):
def clear(self):
nonlocal called
called = True
super().clear()
class SubClearAxes(ClearAxes):
pass
fig = Figure()
for axes_class in [ClaAxes, ClaSuperAxes, SubClaAxes,
ClearAxes, ClearSuperAxes, SubClearAxes]:
called = False
ax = axes_class(fig, [0, 0, 1, 1])
# Axes.__init__ has already called clear (which aliases to cla or is in
# the subclass).
assert called
called = False
ax.cla()
assert called
def test_cla_not_redefined_internally():
for klass in Axes.__subclasses__():
# Check that cla does not get redefined in our Axes subclasses, except
# for in the above test function.
if 'test_subclass_clear_cla' not in klass.__qualname__:
assert 'cla' not in klass.__dict__
@check_figures_equal(extensions=["png"])
def test_minorticks_on_rcParams_both(fig_test, fig_ref):
with matplotlib.rc_context({"xtick.minor.visible": True,
"ytick.minor.visible": True}):
ax_test = fig_test.subplots()
ax_test.plot([0, 1], [0, 1])
ax_ref = fig_ref.subplots()
ax_ref.plot([0, 1], [0, 1])
ax_ref.minorticks_on()
@image_comparison(["autoscale_tiny_range"], remove_text=True)
def test_autoscale_tiny_range():
# github pull #904
fig, axs = plt.subplots(2, 2)
for i, ax in enumerate(axs.flat):
y1 = 10**(-11 - i)
ax.plot([0, 1], [1, 1 + y1])
@mpl.style.context('default')
def test_autoscale_tight():
fig, ax = plt.subplots(1, 1)
ax.plot([1, 2, 3, 4])
ax.autoscale(enable=True, axis='x', tight=False)
ax.autoscale(enable=True, axis='y', tight=True)
assert_allclose(ax.get_xlim(), (-0.15, 3.15))
assert_allclose(ax.get_ylim(), (1.0, 4.0))
# Check that autoscale is on
assert ax.get_autoscalex_on()
assert ax.get_autoscaley_on()
assert ax.get_autoscale_on()
# Set enable to None
ax.autoscale(enable=None)
# Same limits
assert_allclose(ax.get_xlim(), (-0.15, 3.15))
assert_allclose(ax.get_ylim(), (1.0, 4.0))
# autoscale still on
assert ax.get_autoscalex_on()
assert ax.get_autoscaley_on()
assert ax.get_autoscale_on()
@mpl.style.context('default')
def test_autoscale_log_shared():
# related to github #7587
# array starts at zero to trigger _minpos handling
x = np.arange(100, dtype=float)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.loglog(x, x)
ax2.semilogx(x, x)
ax1.autoscale(tight=True)
ax2.autoscale(tight=True)
plt.draw()
lims = (x[1], x[-1])
assert_allclose(ax1.get_xlim(), lims)
assert_allclose(ax1.get_ylim(), lims)
assert_allclose(ax2.get_xlim(), lims)
assert_allclose(ax2.get_ylim(), (x[0], x[-1]))
@mpl.style.context('default')
def test_use_sticky_edges():
fig, ax = plt.subplots()
ax.imshow([[0, 1], [2, 3]], origin='lower')
assert_allclose(ax.get_xlim(), (-0.5, 1.5))
assert_allclose(ax.get_ylim(), (-0.5, 1.5))
ax.use_sticky_edges = False
ax.autoscale()
xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
assert_allclose(ax.get_xlim(), xlim)
assert_allclose(ax.get_ylim(), ylim)
# Make sure it is reversible:
ax.use_sticky_edges = True
ax.autoscale()
assert_allclose(ax.get_xlim(), (-0.5, 1.5))
assert_allclose(ax.get_ylim(), (-0.5, 1.5))
@check_figures_equal(extensions=["png"])
def test_sticky_shared_axes(fig_test, fig_ref):
# Check that sticky edges work whether they are set in an Axes that is a
# "leader" in a share, or an Axes that is a "follower".
Z = np.arange(15).reshape(3, 5)
ax0 = fig_test.add_subplot(211)
ax1 = fig_test.add_subplot(212, sharex=ax0)
ax1.pcolormesh(Z)
ax0 = fig_ref.add_subplot(212)
ax1 = fig_ref.add_subplot(211, sharex=ax0)
ax0.pcolormesh(Z)
@image_comparison(['offset_points'], remove_text=True)
def test_basic_annotate():
# Setup some data
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2.0*np.pi * t)
# Offset Points
fig = plt.figure()
ax = fig.add_subplot(autoscale_on=False, xlim=(-1, 5), ylim=(-3, 5))
line, = ax.plot(t, s, lw=3, color='purple')
ax.annotate('local max', xy=(3, 1), xycoords='data',
xytext=(3, 3), textcoords='offset points')
@image_comparison(['arrow_simple.png'], remove_text=True)
def test_arrow_simple():
# Simple image test for ax.arrow
# kwargs that take discrete values
length_includes_head = (True, False)
shape = ('full', 'left', 'right')
head_starts_at_zero = (True, False)
# Create outer product of values
kwargs = product(length_includes_head, shape, head_starts_at_zero)
fig, axs = plt.subplots(3, 4)
for i, (ax, kwarg) in enumerate(zip(axs.flat, kwargs)):
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# Unpack kwargs
(length_includes_head, shape, head_starts_at_zero) = kwarg
theta = 2 * np.pi * i / 12
# Draw arrow
ax.arrow(0, 0, np.sin(theta), np.cos(theta),
width=theta/100,
length_includes_head=length_includes_head,
shape=shape,
head_starts_at_zero=head_starts_at_zero,
head_width=theta / 10,
head_length=theta / 10)
def test_arrow_empty():
_, ax = plt.subplots()
# Create an empty FancyArrow
ax.arrow(0, 0, 0, 0, head_length=0)
def test_arrow_in_view():
_, ax = plt.subplots()
ax.arrow(1, 1, 1, 1)
assert ax.get_xlim() == (0.8, 2.2)
assert ax.get_ylim() == (0.8, 2.2)
def test_annotate_default_arrow():
# Check that we can make an annotation arrow with only default properties.
fig, ax = plt.subplots()
ann = ax.annotate("foo", (0, 1), xytext=(2, 3))
assert ann.arrow_patch is None
ann = ax.annotate("foo", (0, 1), xytext=(2, 3), arrowprops={})
assert ann.arrow_patch is not None
def test_annotate_signature():
"""Check that the signature of Axes.annotate() matches Annotation."""
fig, ax = plt.subplots()
annotate_params = inspect.signature(ax.annotate).parameters
annotation_params = inspect.signature(mtext.Annotation).parameters
assert list(annotate_params.keys()) == list(annotation_params.keys())
for p1, p2 in zip(annotate_params.values(), annotation_params.values()):
assert p1 == p2
@image_comparison(['fill_units.png'], savefig_kwarg={'dpi': 60})
def test_fill_units():
import matplotlib.testing.jpl_units as units
units.register()
# generate some data
t = units.Epoch("ET", dt=datetime.datetime(2009, 4, 27))
value = 10.0 * units.deg
day = units.Duration("ET", 24.0 * 60.0 * 60.0)
dt = np.arange('2009-04-27', '2009-04-29', dtype='datetime64[D]')
dtn = mdates.date2num(dt)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot([t], [value], yunits='deg', color='red')
ind = [0, 0, 1, 1]
ax1.fill(dtn[ind], [0.0, 0.0, 90.0, 0.0], 'b')
ax2.plot([t], [value], yunits='deg', color='red')
ax2.fill([t, t, t + day, t + day],
[0.0, 0.0, 90.0, 0.0], 'b')
ax3.plot([t], [value], yunits='deg', color='red')
ax3.fill(dtn[ind],
[0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg],
'b')
ax4.plot([t], [value], yunits='deg', color='red')
ax4.fill([t, t, t + day, t + day],
[0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg],
facecolor="blue")
fig.autofmt_xdate()
def test_plot_format_kwarg_redundant():
with pytest.warns(UserWarning, match="marker .* redundantly defined"):
plt.plot([0], [0], 'o', marker='x')
with pytest.warns(UserWarning, match="linestyle .* redundantly defined"):
plt.plot([0], [0], '-', linestyle='--')
with pytest.warns(UserWarning, match="color .* redundantly defined"):
plt.plot([0], [0], 'r', color='blue')
# smoke-test: should not warn
plt.errorbar([0], [0], fmt='none', color='blue')
@check_figures_equal(extensions=["png"])
def test_errorbar_dashes(fig_test, fig_ref):
x = [1, 2, 3, 4]
y = np.sin(x)
ax_ref = fig_ref.gca()
ax_test = fig_test.gca()
line, *_ = ax_ref.errorbar(x, y, xerr=np.abs(y), yerr=np.abs(y))
line.set_dashes([2, 2])
ax_test.errorbar(x, y, xerr=np.abs(y), yerr=np.abs(y), dashes=[2, 2])
@image_comparison(['single_point', 'single_point'])
def test_single_point():
# Issue #1796: don't let lines.marker affect the grid
matplotlib.rcParams['lines.marker'] = 'o'
matplotlib.rcParams['axes.grid'] = True
fig, (ax1, ax2) = plt.subplots(2)
ax1.plot([0], [0], 'o')
ax2.plot([1], [1], 'o')
# Reuse testcase from above for a labeled data test
data = {'a': [0], 'b': [1]}
fig, (ax1, ax2) = plt.subplots(2)
ax1.plot('a', 'a', 'o', data=data)
ax2.plot('b', 'b', 'o', data=data)
@image_comparison(['single_date.png'], style='mpl20')
def test_single_date():
# use former defaults to match existing baseline image
plt.rcParams['axes.formatter.limits'] = -7, 7
dt = mdates.date2num(np.datetime64('0000-12-31'))
time1 = [721964.0]
data1 = [-65.54]
fig, ax = plt.subplots(2, 1)
ax[0].plot_date(time1 + dt, data1, 'o', color='r')
ax[1].plot(time1, data1, 'o', color='r')
@check_figures_equal(extensions=["png"])
def test_shaped_data(fig_test, fig_ref):
row = np.arange(10).reshape((1, -1))
col = np.arange(0, 100, 10).reshape((-1, 1))
axs = fig_test.subplots(2)
axs[0].plot(row) # Actually plots nothing (columns are single points).
axs[1].plot(col) # Same as plotting 1d.
axs = fig_ref.subplots(2)
# xlim from the implicit "x=0", ylim from the row datalim.
axs[0].set(xlim=(-.06, .06), ylim=(0, 9))
axs[1].plot(col.ravel())
def test_structured_data():
# support for structured data
pts = np.array([(1, 1), (2, 2)], dtype=[("ones", float), ("twos", float)])
# this should not read second name as a format and raise ValueError
axs = plt.figure().subplots(2)
axs[0].plot("ones", "twos", data=pts)
axs[1].plot("ones", "twos", "r", data=pts)
@image_comparison(['aitoff_proj'], extensions=["png"],
remove_text=True, style='mpl20')
def test_aitoff_proj():
"""
Test aitoff projection ref.:
https://github.com/matplotlib/matplotlib/pull/14451
"""
x = np.linspace(-np.pi, np.pi, 20)
y = np.linspace(-np.pi / 2, np.pi / 2, 20)
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(figsize=(8, 4.2),
subplot_kw=dict(projection="aitoff"))
ax.grid()
ax.plot(X.flat, Y.flat, 'o', markersize=4)
@image_comparison(['axvspan_epoch'])
def test_axvspan_epoch():
import matplotlib.testing.jpl_units as units
units.register()
# generate some data
t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
dt = units.Duration("ET", units.day.convert("sec"))
ax = plt.gca()
ax.axvspan(t0, tf, facecolor="blue", alpha=0.25)
ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt)
@image_comparison(['axhspan_epoch'], tol=0.02)
def test_axhspan_epoch():
import matplotlib.testing.jpl_units as units
units.register()
# generate some data
t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
dt = units.Duration("ET", units.day.convert("sec"))
ax = plt.gca()
ax.axhspan(t0, tf, facecolor="blue", alpha=0.25)
ax.set_ylim(t0 - 5.0*dt, tf + 5.0*dt)
@image_comparison(['hexbin_extent.png', 'hexbin_extent.png'], remove_text=True)
def test_hexbin_extent():
# this test exposes sf bug 2856228
fig, ax = plt.subplots()
data = (np.arange(2000) / 2000).reshape((2, 1000))
x, y = data
ax.hexbin(x, y, extent=[.1, .3, .6, .7])
# Reuse testcase from above for a labeled data test
data = {"x": x, "y": y}
fig, ax = plt.subplots()
ax.hexbin("x", "y", extent=[.1, .3, .6, .7], data=data)
@image_comparison(['hexbin_empty.png', 'hexbin_empty.png'], remove_text=True)
def test_hexbin_empty():
# From #3886: creating hexbin from empty dataset raises ValueError
fig, ax = plt.subplots()
ax.hexbin([], [])
fig, ax = plt.subplots()
# From #23922: creating hexbin with log scaling from empty
# dataset raises ValueError
ax.hexbin([], [], bins='log')
def test_hexbin_pickable():
# From #1973: Test that picking a hexbin collection works
fig, ax = plt.subplots()
data = (np.arange(200) / 200).reshape((2, 100))
x, y = data
hb = ax.hexbin(x, y, extent=[.1, .3, .6, .7], picker=-1)
mouse_event = SimpleNamespace(x=400, y=300)
assert hb.contains(mouse_event)[0]
@image_comparison(['hexbin_log.png'], style='mpl20')
def test_hexbin_log():
# Issue #1636 (and also test log scaled colorbar)
# Remove this line when this test image is regenerated.
plt.rcParams['pcolormesh.snap'] = False
np.random.seed(19680801)
n = 100000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
y = np.power(2, y * 0.5)
fig, ax = plt.subplots()
h = ax.hexbin(x, y, yscale='log', bins='log',
marginals=True, reduce_C_function=np.sum)
plt.colorbar(h)
@image_comparison(["hexbin_linear.png"], style="mpl20", remove_text=True)
def test_hexbin_linear():
# Issue #21165
np.random.seed(19680801)
n = 100000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
fig, ax = plt.subplots()
ax.hexbin(x, y, gridsize=(10, 5), marginals=True,
reduce_C_function=np.sum)
def test_hexbin_log_clim():
x, y = np.arange(200).reshape((2, 100))
fig, ax = plt.subplots()
h = ax.hexbin(x, y, bins='log', vmin=2, vmax=100)
assert h.get_clim() == (2, 100)
def test_inverted_limits():
# Test gh:1553
# Calling invert_xaxis prior to plotting should not disable autoscaling
# while still maintaining the inverted direction
fig, ax = plt.subplots()
ax.invert_xaxis()
ax.plot([-5, -3, 2, 4], [1, 2, -3, 5])
assert ax.get_xlim() == (4, -5)
assert ax.get_ylim() == (-3, 5)
plt.close()
fig, ax = plt.subplots()
ax.invert_yaxis()
ax.plot([-5, -3, 2, 4], [1, 2, -3, 5])
assert ax.get_xlim() == (-5, 4)
assert ax.get_ylim() == (5, -3)
# Test inverting nonlinear axes.
fig, ax = plt.subplots()
ax.set_yscale("log")
ax.set_ylim(10, 1)
assert ax.get_ylim() == (10, 1)
@image_comparison(['nonfinite_limits'])
def test_nonfinite_limits():
x = np.arange(0., np.e, 0.01)
# silence divide by zero warning from log(0)
with np.errstate(divide='ignore'):
y = np.log(x)
x[len(x)//2] = np.nan
fig, ax = plt.subplots()
ax.plot(x, y)
@mpl.style.context('default')
@pytest.mark.parametrize('plot_fun',
['scatter', 'plot', 'fill_between'])
@check_figures_equal(extensions=["png"])
def test_limits_empty_data(plot_fun, fig_test, fig_ref):