axis.py
90.5 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
"""
Classes for the ticks and x and y axis.
"""
import datetime
import functools
import logging
import numpy as np
import matplotlib as mpl
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
import matplotlib.scale as mscale
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.units as munits
_log = logging.getLogger(__name__)
GRIDLINE_INTERPOLATION_STEPS = 180
# This list is being used for compatibility with Axes.grid, which
# allows all Line2D kwargs.
_line_inspector = martist.ArtistInspector(mlines.Line2D)
_line_param_names = _line_inspector.get_setters()
_line_param_aliases = [list(d)[0] for d in _line_inspector.aliasd.values()]
_gridline_param_names = ['grid_' + name
for name in _line_param_names + _line_param_aliases]
class Tick(martist.Artist):
"""
Abstract base class for the axis ticks, grid lines and labels.
Ticks mark a position on an Axis. They contain two lines as markers and
two labels; one each for the bottom and top positions (in case of an
`.XAxis`) or for the left and right positions (in case of a `.YAxis`).
Attributes
----------
tick1line : `.Line2D`
The left/bottom tick marker.
tick2line : `.Line2D`
The right/top tick marker.
gridline : `.Line2D`
The grid line associated with the label position.
label1 : `.Text`
The left/bottom tick label.
label2 : `.Text`
The right/top tick label.
"""
@cbook._delete_parameter("3.3", "label")
def __init__(self, axes, loc, label=None,
size=None, # points
width=None,
color=None,
tickdir=None,
pad=None,
labelsize=None,
labelcolor=None,
zorder=None,
gridOn=None, # defaults to axes.grid depending on
# axes.grid.which
tick1On=True,
tick2On=True,
label1On=True,
label2On=False,
major=True,
labelrotation=0,
grid_color=None,
grid_linestyle=None,
grid_linewidth=None,
grid_alpha=None,
**kw # Other Line2D kwargs applied to gridlines.
):
"""
bbox is the Bound2D bounding box in display coords of the Axes
loc is the tick location in data coords
size is the tick size in points
"""
martist.Artist.__init__(self)
if gridOn is None:
if major and (mpl.rcParams['axes.grid.which']
in ('both', 'major')):
gridOn = mpl.rcParams['axes.grid']
elif (not major) and (mpl.rcParams['axes.grid.which']
in ('both', 'minor')):
gridOn = mpl.rcParams['axes.grid']
else:
gridOn = False
self.set_figure(axes.figure)
self.axes = axes
name = self.__name__.lower()
self._loc = loc
self._major = major
major_minor = "major" if major else "minor"
if size is None:
size = mpl.rcParams[f"{name}.{major_minor}.size"]
self._size = size
if width is None:
width = mpl.rcParams[f"{name}.{major_minor}.width"]
self._width = width
if color is None:
color = mpl.rcParams[f"{name}.color"]
if pad is None:
pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
self._base_pad = pad
if labelcolor is None:
labelcolor = mpl.rcParams[f"{name}.color"]
if labelsize is None:
labelsize = mpl.rcParams[f"{name}.labelsize"]
self._set_labelrotation(labelrotation)
if zorder is None:
if major:
zorder = mlines.Line2D.zorder + 0.01
else:
zorder = mlines.Line2D.zorder
self._zorder = zorder
if grid_color is None:
grid_color = mpl.rcParams["grid.color"]
if grid_linestyle is None:
grid_linestyle = mpl.rcParams["grid.linestyle"]
if grid_linewidth is None:
grid_linewidth = mpl.rcParams["grid.linewidth"]
if grid_alpha is None:
grid_alpha = mpl.rcParams["grid.alpha"]
grid_kw = {k[5:]: v for k, v in kw.items()}
self.apply_tickdir(tickdir)
self.tick1line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick1On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
)
self.tick2line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick2On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
)
self.gridline = mlines.Line2D(
[], [],
color=grid_color, alpha=grid_alpha, visible=gridOn,
linestyle=grid_linestyle, linewidth=grid_linewidth, marker="",
**grid_kw,
)
self.gridline.get_path()._interpolation_steps = \
GRIDLINE_INTERPOLATION_STEPS
self.label1 = mtext.Text(
np.nan, np.nan,
fontsize=labelsize, color=labelcolor, visible=label1On)
self.label2 = mtext.Text(
np.nan, np.nan,
fontsize=labelsize, color=labelcolor, visible=label2On)
for meth, attr in [("_get_tick1line", "tick1line"),
("_get_tick2line", "tick2line"),
("_get_gridline", "gridline"),
("_get_text1", "label1"),
("_get_text2", "label2")]:
overridden_method = cbook._deprecate_method_override(
getattr(__class__, meth), self, since="3.3", message="Relying "
f"on {meth} to initialize Tick.{attr} is deprecated since "
f"%(since)s and will not work %(removal)s; please directly "
f"set the attribute in the subclass' __init__ instead.")
if overridden_method:
setattr(self, attr, overridden_method())
for artist in [self.tick1line, self.tick2line, self.gridline,
self.label1, self.label2]:
self._set_artist_props(artist)
self.update_position(loc)
@property
@cbook.deprecated("3.1", alternative="Tick.label1", pending=True)
def label(self):
return self.label1
def _set_labelrotation(self, labelrotation):
if isinstance(labelrotation, str):
mode = labelrotation
angle = 0
elif isinstance(labelrotation, (tuple, list)):
mode, angle = labelrotation
else:
mode = 'default'
angle = labelrotation
cbook._check_in_list(['auto', 'default'], labelrotation=mode)
self._labelrotation = (mode, angle)
def apply_tickdir(self, tickdir):
"""Calculate ``self._pad`` and ``self._tickmarkers``."""
def get_tickdir(self):
return self._tickdir
def get_tick_padding(self):
"""Get the length of the tick outside of the axes."""
padding = {
'in': 0.0,
'inout': 0.5,
'out': 1.0
}
return self._size * padding[self._tickdir]
def get_children(self):
children = [self.tick1line, self.tick2line,
self.gridline, self.label1, self.label2]
return children
def set_clip_path(self, clippath, transform=None):
# docstring inherited
martist.Artist.set_clip_path(self, clippath, transform)
self.gridline.set_clip_path(clippath, transform)
self.stale = True
def get_pad_pixels(self):
return self.figure.dpi * self._base_pad / 72
def contains(self, mouseevent):
"""
Test whether the mouse event occurred in the Tick marks.
This function always returns false. It is more useful to test if the
axis as a whole contains the mouse rather than the set of tick marks.
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
return False, {}
def set_pad(self, val):
"""
Set the tick label pad in points
Parameters
----------
val : float
"""
self._apply_params(pad=val)
self.stale = True
def get_pad(self):
"""Get the value of the tick label pad in points."""
return self._base_pad
def _get_text1(self):
"""Get the default Text 1 instance."""
def _get_text2(self):
"""Get the default Text 2 instance."""
def _get_tick1line(self):
"""Get the default line2D instance for tick1."""
def _get_tick2line(self):
"""Get the default line2D instance for tick2."""
def _get_gridline(self):
"""Get the default grid Line2d instance for this tick."""
def get_loc(self):
"""Return the tick location (data coords) as a scalar."""
return self._loc
@martist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
self.stale = False
return
renderer.open_group(self.__name__, gid=self.get_gid())
for artist in [self.gridline, self.tick1line, self.tick2line,
self.label1, self.label2]:
artist.draw(renderer)
renderer.close_group(self.__name__)
self.stale = False
def set_label1(self, s):
"""
Set the label1 text.
Parameters
----------
s : str
"""
self.label1.set_text(s)
self.stale = True
set_label = set_label1
def set_label2(self, s):
"""
Set the label2 text.
Parameters
----------
s : str
"""
self.label2.set_text(s)
self.stale = True
def set_url(self, url):
"""
Set the url of label1 and label2.
Parameters
----------
url : str
"""
super().set_url(url)
self.label1.set_url(url)
self.label2.set_url(url)
self.stale = True
def _set_artist_props(self, a):
a.set_figure(self.figure)
def get_view_interval(self):
"""
Return the view limits ``(min, max)`` of the axis the tick belongs to.
"""
raise NotImplementedError('Derived must override')
def _apply_params(self, **kw):
for name, target in [("gridOn", self.gridline),
("tick1On", self.tick1line),
("tick2On", self.tick2line),
("label1On", self.label1),
("label2On", self.label2)]:
if name in kw:
target.set_visible(kw.pop(name))
if any(k in kw for k in ['size', 'width', 'pad', 'tickdir']):
self._size = kw.pop('size', self._size)
# Width could be handled outside this block, but it is
# convenient to leave it here.
self._width = kw.pop('width', self._width)
self._base_pad = kw.pop('pad', self._base_pad)
# apply_tickdir uses _size and _base_pad to make _pad,
# and also makes _tickmarkers.
self.apply_tickdir(kw.pop('tickdir', self._tickdir))
self.tick1line.set_marker(self._tickmarkers[0])
self.tick2line.set_marker(self._tickmarkers[1])
for line in (self.tick1line, self.tick2line):
line.set_markersize(self._size)
line.set_markeredgewidth(self._width)
# _get_text1_transform uses _pad from apply_tickdir.
trans = self._get_text1_transform()[0]
self.label1.set_transform(trans)
trans = self._get_text2_transform()[0]
self.label2.set_transform(trans)
tick_kw = {k: v for k, v in kw.items() if k in ['color', 'zorder']}
if 'color' in kw:
tick_kw['markeredgecolor'] = kw['color']
self.tick1line.set(**tick_kw)
self.tick2line.set(**tick_kw)
for k, v in tick_kw.items():
setattr(self, '_' + k, v)
if 'labelrotation' in kw:
self._set_labelrotation(kw.pop('labelrotation'))
self.label1.set(rotation=self._labelrotation[1])
self.label2.set(rotation=self._labelrotation[1])
label_kw = {k[5:]: v for k, v in kw.items()
if k in ['labelsize', 'labelcolor']}
self.label1.set(**label_kw)
self.label2.set(**label_kw)
for k, v in label_kw.items():
# for labelsize the text objects covert str ('small')
# -> points. grab the integer from the `Text` object
# instead of saving the string representation
v = getattr(self.label1, 'get_' + k)()
setattr(self, '_label' + k, v)
grid_kw = {k[5:]: v for k, v in kw.items()
if k in _gridline_param_names}
self.gridline.set(**grid_kw)
for k, v in grid_kw.items():
setattr(self, '_grid_' + k, v)
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
raise NotImplementedError('Derived must override')
def _get_text1_transform(self):
raise NotImplementedError('Derived must override')
def _get_text2_transform(self):
raise NotImplementedError('Derived must override')
class XTick(Tick):
"""
Contains all the Artists needed to make an x tick - the tick line,
the label text and the grid line
"""
__name__ = 'xtick'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in data coords, y in axes coords
self.tick1line.set(
xdata=[0], ydata=[0],
transform=self.axes.get_xaxis_transform(which="tick1"),
marker=self._tickmarkers[0],
)
self.tick2line.set(
xdata=[0], ydata=[1],
transform=self.axes.get_xaxis_transform(which="tick2"),
marker=self._tickmarkers[1],
)
self.gridline.set(
xdata=[0, 0], ydata=[0, 1],
transform=self.axes.get_xaxis_transform(which="grid"),
)
# the y loc is 3 points below the min of y axis
trans, va, ha = self._get_text1_transform()
self.label1.set(
x=0, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
trans, va, ha = self._get_text2_transform()
self.label2.set(
x=0, y=1,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
def _get_text1_transform(self):
return self.axes.get_xaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_xaxis_text2_transform(self._pad)
def apply_tickdir(self, tickdir):
"""Set tick direction. Valid values are 'in', 'out', 'inout'."""
if tickdir is None:
tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()]
cbook._check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
self._tickdir = tickdir
if self._tickdir == 'in':
self._tickmarkers = (mlines.TICKUP, mlines.TICKDOWN)
elif self._tickdir == 'inout':
self._tickmarkers = ('|', '|')
else:
self._tickmarkers = (mlines.TICKDOWN, mlines.TICKUP)
self._pad = self._base_pad + self.get_tick_padding()
self.stale = True
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_xdata((loc,))
self.tick2line.set_xdata((loc,))
self.gridline.set_xdata((loc,))
self.label1.set_x(loc)
self.label2.set_x(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervalx
class YTick(Tick):
"""
Contains all the Artists needed to make a Y tick - the tick line,
the label text and the grid line
"""
__name__ = 'ytick'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in axes coords, y in data coords
self.tick1line.set(
xdata=[0], ydata=[0],
transform=self.axes.get_yaxis_transform(which="tick1"),
marker=self._tickmarkers[0],
)
self.tick2line.set(
xdata=[1], ydata=[0],
transform=self.axes.get_yaxis_transform(which="tick2"),
marker=self._tickmarkers[1],
)
self.gridline.set(
xdata=[0, 1], ydata=[0, 0],
transform=self.axes.get_yaxis_transform(which="grid"),
)
# the y loc is 3 points below the min of y axis
trans, va, ha = self._get_text1_transform()
self.label1.set(
x=0, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
trans, va, ha = self._get_text2_transform()
self.label2.set(
x=1, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
def _get_text1_transform(self):
return self.axes.get_yaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_yaxis_text2_transform(self._pad)
def apply_tickdir(self, tickdir):
if tickdir is None:
tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()]
self._tickdir = tickdir
if self._tickdir == 'in':
self._tickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)
elif self._tickdir == 'inout':
self._tickmarkers = ('_', '_')
else:
self._tickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)
self._pad = self._base_pad + self.get_tick_padding()
self.stale = True
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_ydata((loc,))
self.tick2line.set_ydata((loc,))
self.gridline.set_ydata((loc,))
self.label1.set_y(loc)
self.label2.set_y(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervaly
class Ticker:
"""
A container for the objects defining tick position and format.
Attributes
----------
locator : `matplotlib.ticker.Locator` subclass
Determines the positions of the ticks.
formatter : `matplotlib.ticker.Formatter` subclass
Determines the format of the tick labels.
"""
def __init__(self):
self._locator = None
self._formatter = None
@property
def locator(self):
return self._locator
@locator.setter
def locator(self, locator):
if not isinstance(locator, mticker.Locator):
cbook.warn_deprecated(
"3.2", message="Support for locators that do not subclass "
"matplotlib.ticker.Locator is deprecated since %(since)s and "
"support for them will be removed %(removal)s.")
self._locator = locator
@property
def formatter(self):
return self._formatter
@formatter.setter
def formatter(self, formatter):
if not isinstance(formatter, mticker.Formatter):
cbook.warn_deprecated(
"3.2", message="Support for formatters that do not subclass "
"matplotlib.ticker.Formatter is deprecated since %(since)s "
"and support for them will be removed %(removal)s.")
self._formatter = formatter
class _LazyTickList:
"""
A descriptor for lazy instantiation of tick lists.
See comment above definition of the ``majorTicks`` and ``minorTicks``
attributes.
"""
def __init__(self, major):
self._major = major
def __get__(self, instance, cls):
if instance is None:
return self
else:
# instance._get_tick() can itself try to access the majorTicks
# attribute (e.g. in certain projection classes which override
# e.g. get_xaxis_text1_transform). In order to avoid infinite
# recursion, first set the majorTicks on the instance to an empty
# list, then create the tick and append it.
if self._major:
instance.majorTicks = []
tick = instance._get_tick(major=True)
instance.majorTicks.append(tick)
return instance.majorTicks
else:
instance.minorTicks = []
tick = instance._get_tick(major=False)
instance.minorTicks.append(tick)
return instance.minorTicks
class Axis(martist.Artist):
"""
Base class for `.XAxis` and `.YAxis`.
Attributes
----------
isDefault_label : bool
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the Axis belongs.
major : `matplotlib.axis.Ticker`
Determines the major tick positions and their label format.
minor : `matplotlib.axis.Ticker`
Determines the minor tick positions and their label format.
callbacks : `matplotlib.cbook.CallbackRegistry`
label : `.Text`
The axis label.
labelpad : float
The distance between the axis label and the tick labels.
Defaults to :rc:`axes.labelpad` = 4.
offsetText : `.Text`
A `.Text` object containing the data offset of the ticks (if any).
pickradius : float
The acceptance radius for containment tests. See also `.Axis.contains`.
majorTicks : list of `.Tick`
The major ticks.
minorTicks : list of `.Tick`
The minor ticks.
"""
OFFSETTEXTPAD = 3
def __str__(self):
return "{}({},{})".format(
type(self).__name__, *self.axes.transAxes.transform((0, 0)))
def __init__(self, axes, pickradius=15):
"""
Parameters
----------
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the created Axis belongs.
pickradius : float
The acceptance radius for containment tests. See also
`.Axis.contains`.
"""
martist.Artist.__init__(self)
self._remove_overlapping_locs = True
self.set_figure(axes.figure)
self.isDefault_label = True
self.axes = axes
self.major = Ticker()
self.minor = Ticker()
self.callbacks = cbook.CallbackRegistry()
self._autolabelpos = True
self._smart_bounds = False # Deprecated in 3.2
self.label = mtext.Text(
np.nan, np.nan,
fontsize=mpl.rcParams['axes.labelsize'],
fontweight=mpl.rcParams['axes.labelweight'],
color=mpl.rcParams['axes.labelcolor'],
)
self._set_artist_props(self.label)
self.offsetText = mtext.Text(np.nan, np.nan)
self._set_artist_props(self.offsetText)
self.labelpad = mpl.rcParams['axes.labelpad']
self.pickradius = pickradius
# Initialize here for testing; later add API
self._major_tick_kw = dict()
self._minor_tick_kw = dict()
self.cla()
self._set_scale('linear')
# During initialization, Axis objects often create ticks that are later
# unused; this turns out to be a very slow step. Instead, use a custom
# descriptor to make the tick lists lazy and instantiate them as needed.
majorTicks = _LazyTickList(major=True)
minorTicks = _LazyTickList(major=False)
def get_remove_overlapping_locs(self):
return self._remove_overlapping_locs
def set_remove_overlapping_locs(self, val):
self._remove_overlapping_locs = bool(val)
remove_overlapping_locs = property(
get_remove_overlapping_locs, set_remove_overlapping_locs,
doc=('If minor ticker locations that overlap with major '
'ticker locations should be trimmed.'))
def set_label_coords(self, x, y, transform=None):
"""
Set the coordinates of the label.
By default, the x coordinate of the y label and the y coordinate of the
x label are determined by the tick label bounding boxes, but this can
lead to poor alignment of multiple labels if there are multiple axes.
You can also specify the coordinate system of the label with the
transform. If None, the default coordinate system will be the axes
coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc.
"""
self._autolabelpos = False
if transform is None:
transform = self.axes.transAxes
self.label.set_transform(transform)
self.label.set_position((x, y))
self.stale = True
def get_transform(self):
return self._scale.get_transform()
def get_scale(self):
"""Return this Axis' scale (as a str)."""
return self._scale.name
def _set_scale(self, value, **kwargs):
self._scale = mscale.scale_factory(value, self, **kwargs)
self._scale.set_default_locators_and_formatters(self)
self.isDefault_majloc = True
self.isDefault_minloc = True
self.isDefault_majfmt = True
self.isDefault_minfmt = True
def limit_range_for_scale(self, vmin, vmax):
return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos())
def get_children(self):
return [self.label, self.offsetText,
*self.get_major_ticks(), *self.get_minor_ticks()]
def cla(self):
"""Clear this axis."""
self.label.set_text('') # self.set_label_text would change isDefault_
self._set_scale('linear')
# Clear the callback registry for this axis, or it may "leak"
self.callbacks = cbook.CallbackRegistry()
# whether the grids are on
self._major_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'major'))
self._minor_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
self.reset_ticks()
self.converter = None
self.units = None
self.set_units(None)
self.stale = True
def reset_ticks(self):
"""
Re-initialize the major and minor Tick lists.
Each list starts with a single fresh Tick.
"""
# Restore the lazy tick lists.
try:
del self.majorTicks
except AttributeError:
pass
try:
del self.minorTicks
except AttributeError:
pass
try:
self.set_clip_path(self.axes.patch)
except AttributeError:
pass
def set_tick_params(self, which='major', reset=False, **kw):
"""
Set appearance parameters for ticks, ticklabels, and gridlines.
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
cbook._check_in_list(['major', 'minor', 'both'], which=which)
kwtrans = self._translate_tick_kw(kw)
# the kwargs are stored in self._major/minor_tick_kw so that any
# future new ticks will automatically get them
if reset:
if which in ['major', 'both']:
self._major_tick_kw.clear()
self._major_tick_kw.update(kwtrans)
if which in ['minor', 'both']:
self._minor_tick_kw.clear()
self._minor_tick_kw.update(kwtrans)
self.reset_ticks()
else:
if which in ['major', 'both']:
self._major_tick_kw.update(kwtrans)
for tick in self.majorTicks:
tick._apply_params(**kwtrans)
if which in ['minor', 'both']:
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# labelOn and labelcolor also apply to the offset text.
if 'label1On' in kwtrans or 'label2On' in kwtrans:
self.offsetText.set_visible(
self._major_tick_kw.get('label1On', False)
or self._major_tick_kw.get('label2On', False))
if 'labelcolor' in kwtrans:
self.offsetText.set_color(kwtrans['labelcolor'])
self.stale = True
@staticmethod
def _translate_tick_kw(kw):
# The following lists may be moved to a more accessible location.
kwkeys = ['size', 'width', 'color', 'tickdir', 'pad',
'labelsize', 'labelcolor', 'zorder', 'gridOn',
'tick1On', 'tick2On', 'label1On', 'label2On',
'length', 'direction', 'left', 'bottom', 'right', 'top',
'labelleft', 'labelbottom', 'labelright', 'labeltop',
'labelrotation'] + _gridline_param_names
kwtrans = {}
if 'length' in kw:
kwtrans['size'] = kw.pop('length')
if 'direction' in kw:
kwtrans['tickdir'] = kw.pop('direction')
if 'rotation' in kw:
kwtrans['labelrotation'] = kw.pop('rotation')
if 'left' in kw:
kwtrans['tick1On'] = kw.pop('left')
if 'bottom' in kw:
kwtrans['tick1On'] = kw.pop('bottom')
if 'right' in kw:
kwtrans['tick2On'] = kw.pop('right')
if 'top' in kw:
kwtrans['tick2On'] = kw.pop('top')
if 'labelleft' in kw:
kwtrans['label1On'] = kw.pop('labelleft')
if 'labelbottom' in kw:
kwtrans['label1On'] = kw.pop('labelbottom')
if 'labelright' in kw:
kwtrans['label2On'] = kw.pop('labelright')
if 'labeltop' in kw:
kwtrans['label2On'] = kw.pop('labeltop')
if 'colors' in kw:
c = kw.pop('colors')
kwtrans['color'] = c
kwtrans['labelcolor'] = c
# Maybe move the checking up to the caller of this method.
for key in kw:
if key not in kwkeys:
raise ValueError(
"keyword %s is not recognized; valid keywords are %s"
% (key, kwkeys))
kwtrans.update(kw)
return kwtrans
def set_clip_path(self, clippath, transform=None):
martist.Artist.set_clip_path(self, clippath, transform)
for child in self.majorTicks + self.minorTicks:
child.set_clip_path(clippath, transform)
self.stale = True
def get_view_interval(self):
"""Return the view limits ``(min, max)`` of this axis."""
raise NotImplementedError('Derived must override')
def set_view_interval(self, vmin, vmax, ignore=False):
"""
Set the axis view limits. This method is for internal use; Matplotlib
users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`.
If *ignore* is False (the default), this method will never reduce the
preexisting view limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the view limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_data_interval(self):
"""Return the Interval instance for this axis data limits."""
raise NotImplementedError('Derived must override')
def set_data_interval(self, vmin, vmax, ignore=False):
"""
Set the axis data limits. This method is for internal use.
If *ignore* is False (the default), this method will never reduce the
preexisting data limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the data limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_inverted(self):
"""
Return whether this Axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
low, high = self.get_view_interval()
return high < low
def set_inverted(self, inverted):
"""
Set whether this Axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
# Currently, must be implemented in subclasses using set_xlim/set_ylim
# rather than generically using set_view_interval, so that shared
# axes get updated as well.
raise NotImplementedError('Derived must override')
def set_default_intervals(self):
"""
Set the default limits for the axis data and view interval if they
have not been not mutated yet.
"""
# this is mainly in support of custom object plotting. For
# example, if someone passes in a datetime object, we do not
# know automagically how to set the default min/max of the
# data and view limits. The unit conversion AxisInfo
# interface provides a hook for custom types to register
# default limits through the AxisInfo.default_limits
# attribute, and the derived code below will check for that
# and use it if is available (else just use 0..1)
def _set_artist_props(self, a):
if a is None:
return
a.set_figure(self.figure)
def get_ticklabel_extents(self, renderer):
"""
Get the extents of the tick labels on either side
of the axes.
"""
ticks_to_draw = self._update_ticks()
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
renderer)
if len(ticklabelBoxes):
bbox = mtransforms.Bbox.union(ticklabelBoxes)
else:
bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0)
if len(ticklabelBoxes2):
bbox2 = mtransforms.Bbox.union(ticklabelBoxes2)
else:
bbox2 = mtransforms.Bbox.from_extents(0, 0, 0, 0)
return bbox, bbox2
@cbook.deprecated("3.2")
def set_smart_bounds(self, value):
"""Set the axis to have smart bounds."""
self._smart_bounds = value
self.stale = True
@cbook.deprecated("3.2")
def get_smart_bounds(self):
"""Return whether the axis has smart bounds."""
return self._smart_bounds
def _update_ticks(self):
"""
Update ticks (position and labels) using the current data interval of
the axes. Return the list of ticks that will be drawn.
"""
major_locs = self.get_majorticklocs()
major_labels = self.major.formatter.format_ticks(major_locs)
major_ticks = self.get_major_ticks(len(major_locs))
self.major.formatter.set_locs(major_locs)
for tick, loc, label in zip(major_ticks, major_locs, major_labels):
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
minor_locs = self.get_minorticklocs()
minor_labels = self.minor.formatter.format_ticks(minor_locs)
minor_ticks = self.get_minor_ticks(len(minor_locs))
self.minor.formatter.set_locs(minor_locs)
for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels):
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
ticks = [*major_ticks, *minor_ticks]
view_low, view_high = self.get_view_interval()
if view_low > view_high:
view_low, view_high = view_high, view_low
if self._smart_bounds and ticks: # _smart_bounds is deprecated in 3.2
# handle inverted limits
data_low, data_high = sorted(self.get_data_interval())
locs = np.sort([tick.get_loc() for tick in ticks])
if data_low <= view_low:
# data extends beyond view, take view as limit
ilow = view_low
else:
# data stops within view, take best tick
good_locs = locs[locs <= data_low]
if len(good_locs):
# last tick prior or equal to first data point
ilow = good_locs[-1]
else:
# No ticks (why not?), take first tick
ilow = locs[0]
if data_high >= view_high:
# data extends beyond view, take view as limit
ihigh = view_high
else:
# data stops within view, take best tick
good_locs = locs[locs >= data_high]
if len(good_locs):
# first tick after or equal to last data point
ihigh = good_locs[0]
else:
# No ticks (why not?), take last tick
ihigh = locs[-1]
ticks = [tick for tick in ticks if ilow <= tick.get_loc() <= ihigh]
interval_t = self.get_transform().transform([view_low, view_high])
ticks_to_draw = []
for tick in ticks:
try:
loc_t = self.get_transform().transform(tick.get_loc())
except AssertionError:
# transforms.transform doesn't allow masked values but
# some scales might make them, so we need this try/except.
pass
else:
if mtransforms._interval_contains_close(interval_t, loc_t):
ticks_to_draw.append(tick)
return ticks_to_draw
def _get_tick_bboxes(self, ticks, renderer):
"""Return lists of bboxes for ticks' label1's and label2's."""
return ([tick.label1.get_window_extent(renderer)
for tick in ticks if tick.label1.get_visible()],
[tick.label2.get_window_extent(renderer)
for tick in ticks if tick.label2.get_visible()])
def get_tightbbox(self, renderer, *, for_layout_only=False):
"""
Return a bounding box that encloses the axis. It only accounts
tick labels, axis label, and offsetText.
If *for_layout_only* is True, then the width of the label (if this
is an x-axis) or the height of the label (if this is a y-axis) is
collapsed to near zero. This allows tight/constrained_layout to ignore
too-long labels when doing their layout.
"""
if not self.get_visible():
return
ticks_to_draw = self._update_ticks()
self._update_label_position(renderer)
# go back to just this axis's tick labels
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(
ticks_to_draw, renderer)
self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)
self.offsetText.set_text(self.major.formatter.get_offset())
bboxes = [
*(a.get_window_extent(renderer)
for a in [self.offsetText]
if a.get_visible()),
*ticklabelBoxes,
*ticklabelBoxes2,
]
# take care of label
if self.label.get_visible():
bb = self.label.get_window_extent(renderer)
# for constrained/tight_layout, we want to ignore the label's
# width/height because the adjustments they make can't be improved.
# this code collapses the relevant direction
if for_layout_only:
if self.axis_name == "x" and bb.width > 0:
bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5
bb.x1 = bb.x0 + 1.0
if self.axis_name == "y" and bb.height > 0:
bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5
bb.y1 = bb.y0 + 1.0
bboxes.append(bb)
bboxes = [b for b in bboxes
if 0 < b.width < np.inf and 0 < b.height < np.inf]
if bboxes:
return mtransforms.Bbox.union(bboxes)
else:
return None
def get_tick_padding(self):
values = []
if len(self.majorTicks):
values.append(self.majorTicks[0].get_tick_padding())
if len(self.minorTicks):
values.append(self.minorTicks[0].get_tick_padding())
return max(values, default=0)
@martist.allow_rasterization
def draw(self, renderer, *args, **kwargs):
# docstring inherited
if not self.get_visible():
return
renderer.open_group(__name__, gid=self.get_gid())
ticks_to_draw = self._update_ticks()
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
renderer)
for tick in ticks_to_draw:
tick.draw(renderer)
# scale up the axis label box to also find the neighbors, not
# just the tick labels that actually overlap note we need a
# *copy* of the axis label box because we don't want to scale
# the actual bbox
self._update_label_position(renderer)
self.label.draw(renderer)
self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)
self.offsetText.set_text(self.major.formatter.get_offset())
self.offsetText.draw(renderer)
renderer.close_group(__name__)
self.stale = False
def get_gridlines(self):
r"""Return this Axis' grid lines as a list of `.Line2D`\s."""
ticks = self.get_major_ticks()
return cbook.silent_list('Line2D gridline',
[tick.gridline for tick in ticks])
def get_label(self):
"""Return the axis label as a Text instance."""
return self.label
def get_offset_text(self):
"""Return the axis offsetText as a Text instance."""
return self.offsetText
def get_pickradius(self):
"""Return the depth of the axis used by the picker."""
return self.pickradius
def get_majorticklabels(self):
"""Return this Axis' major tick labels, as a list of `~.text.Text`."""
ticks = self.get_major_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
return labels1 + labels2
def get_minorticklabels(self):
"""Return this Axis' minor tick labels, as a list of `~.text.Text`."""
ticks = self.get_minor_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
return labels1 + labels2
def get_ticklabels(self, minor=False, which=None):
"""
Get this Axis' tick labels.
Parameters
----------
minor : bool
Whether to return the minor or the major ticklabels.
which : None, ('minor', 'major', 'both')
Overrides *minor*.
Selects which ticklabels to return
Returns
-------
list of `~matplotlib.text.Text`
Notes
-----
The tick label strings are not populated until a ``draw`` method has
been called.
See also: `~.pyplot.draw` and `~.FigureCanvasBase.draw`.
"""
if which is not None:
if which == 'minor':
return self.get_minorticklabels()
elif which == 'major':
return self.get_majorticklabels()
elif which == 'both':
return self.get_majorticklabels() + self.get_minorticklabels()
else:
cbook._check_in_list(['major', 'minor', 'both'], which=which)
if minor:
return self.get_minorticklabels()
return self.get_majorticklabels()
def get_majorticklines(self):
r"""Return this Axis' major tick lines as a list of `.Line2D`\s."""
lines = []
ticks = self.get_major_ticks()
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
return cbook.silent_list('Line2D ticklines', lines)
def get_minorticklines(self):
r"""Return this Axis' minor tick lines as a list of `.Line2D`\s."""
lines = []
ticks = self.get_minor_ticks()
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
return cbook.silent_list('Line2D ticklines', lines)
def get_ticklines(self, minor=False):
r"""Return this Axis' tick lines as a list of `.Line2D`\s."""
if minor:
return self.get_minorticklines()
return self.get_majorticklines()
def get_majorticklocs(self):
"""Return this Axis' major tick locations in data coordinates."""
return self.major.locator()
def get_minorticklocs(self):
"""Return this Axis' minor tick locations in data coordinates."""
# Remove minor ticks duplicating major ticks.
major_locs = self.major.locator()
minor_locs = self.minor.locator()
transform = self._scale.get_transform()
tr_minor_locs = transform.transform(minor_locs)
tr_major_locs = transform.transform(major_locs)
lo, hi = sorted(transform.transform(self.get_view_interval()))
# Use the transformed view limits as scale. 1e-5 is the default rtol
# for np.isclose.
tol = (hi - lo) * 1e-5
if self.remove_overlapping_locs:
minor_locs = [
loc for loc, tr_loc in zip(minor_locs, tr_minor_locs)
if ~np.isclose(tr_loc, tr_major_locs, atol=tol, rtol=0).any()]
return minor_locs
@cbook._make_keyword_only("3.3", "minor")
def get_ticklocs(self, minor=False):
"""Return this Axis' tick locations in data coordinates."""
return self.get_minorticklocs() if minor else self.get_majorticklocs()
def get_ticks_direction(self, minor=False):
"""
Get the tick directions as a numpy array
Parameters
----------
minor : bool, default: False
True to return the minor tick directions,
False to return the major tick directions.
Returns
-------
numpy array of tick directions
"""
if minor:
return np.array(
[tick._tickdir for tick in self.get_minor_ticks()])
else:
return np.array(
[tick._tickdir for tick in self.get_major_ticks()])
def _get_tick(self, major):
"""Return the default tick instance."""
raise NotImplementedError('derived must override')
def _get_tick_label_size(self, axis_name):
"""
Return the text size of tick labels for this Axis.
This is a convenience function to avoid having to create a `Tick` in
`.get_tick_space`, since it is expensive.
"""
tick_kw = self._major_tick_kw
size = tick_kw.get('labelsize',
mpl.rcParams[f'{axis_name}tick.labelsize'])
return mtext.FontProperties(size=size).get_size_in_points()
def _copy_tick_props(self, src, dest):
"""Copy the properties from *src* tick to *dest* tick."""
if src is None or dest is None:
return
dest.label1.update_from(src.label1)
dest.label2.update_from(src.label2)
dest.tick1line.update_from(src.tick1line)
dest.tick2line.update_from(src.tick2line)
dest.gridline.update_from(src.gridline)
def get_label_text(self):
"""Get the text of the label."""
return self.label.get_text()
def get_major_locator(self):
"""Get the locator of the major ticker."""
return self.major.locator
def get_minor_locator(self):
"""Get the locator of the minor ticker."""
return self.minor.locator
def get_major_formatter(self):
"""Get the formatter of the major ticker."""
return self.major.formatter
def get_minor_formatter(self):
"""Get the formatter of the minor ticker."""
return self.minor.formatter
def get_major_ticks(self, numticks=None):
r"""Return the list of major `.Tick`\s."""
if numticks is None:
numticks = len(self.get_majorticklocs())
while len(self.majorTicks) < numticks:
# Update the new tick label properties from the old.
tick = self._get_tick(major=True)
self.majorTicks.append(tick)
self._copy_tick_props(self.majorTicks[0], tick)
return self.majorTicks[:numticks]
def get_minor_ticks(self, numticks=None):
r"""Return the list of minor `.Tick`\s."""
if numticks is None:
numticks = len(self.get_minorticklocs())
while len(self.minorTicks) < numticks:
# Update the new tick label properties from the old.
tick = self._get_tick(major=False)
self.minorTicks.append(tick)
self._copy_tick_props(self.minorTicks[0], tick)
return self.minorTicks[:numticks]
def grid(self, b=None, which='major', **kwargs):
"""
Configure the grid lines.
Parameters
----------
b : bool or None
Whether to show the grid lines. If any *kwargs* are supplied,
it is assumed you want the grid on and *b* will be set to True.
If *b* is *None* and there are no *kwargs*, this toggles the
visibility of the lines.
which : {'major', 'minor', 'both'}
The grid lines to apply the changes on.
**kwargs : `.Line2D` properties
Define the line properties of the grid, e.g.::
grid(color='r', linestyle='-', linewidth=2)
"""
if b is not None:
if 'visible' in kwargs and bool(b) != bool(kwargs['visible']):
raise ValueError(
"'b' and 'visible' specify inconsistent grid visibilities")
if kwargs and not b: # something false-like but not None
cbook._warn_external('First parameter to grid() is false, '
'but line properties are supplied. The '
'grid will be enabled.')
b = True
which = which.lower()
cbook._check_in_list(['major', 'minor', 'both'], which=which)
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
if 'grid_visible' in gridkw:
forced_visibility = True
gridkw['gridOn'] = gridkw.pop('grid_visible')
else:
forced_visibility = False
if which in ['minor', 'both']:
if b is None and not forced_visibility:
gridkw['gridOn'] = not self._minor_tick_kw['gridOn']
elif b is not None:
gridkw['gridOn'] = b
self.set_tick_params(which='minor', **gridkw)
if which in ['major', 'both']:
if b is None and not forced_visibility:
gridkw['gridOn'] = not self._major_tick_kw['gridOn']
elif b is not None:
gridkw['gridOn'] = b
self.set_tick_params(which='major', **gridkw)
self.stale = True
def update_units(self, data):
"""
Introspect *data* for units converter and update the
axis.converter instance if necessary. Return *True*
if *data* is registered for unit conversion.
"""
converter = munits.registry.get_converter(data)
if converter is None:
return False
neednew = self.converter != converter
self.converter = converter
default = self.converter.default_units(data, self)
if default is not None and self.units is None:
self.set_units(default)
if neednew:
self._update_axisinfo()
self.stale = True
return True
def _update_axisinfo(self):
"""
Check the axis converter for the stored units to see if the
axis info needs to be updated.
"""
if self.converter is None:
return
info = self.converter.axisinfo(self.units, self)
if info is None:
return
if info.majloc is not None and \
self.major.locator != info.majloc and self.isDefault_majloc:
self.set_major_locator(info.majloc)
self.isDefault_majloc = True
if info.minloc is not None and \
self.minor.locator != info.minloc and self.isDefault_minloc:
self.set_minor_locator(info.minloc)
self.isDefault_minloc = True
if info.majfmt is not None and \
self.major.formatter != info.majfmt and self.isDefault_majfmt:
self.set_major_formatter(info.majfmt)
self.isDefault_majfmt = True
if info.minfmt is not None and \
self.minor.formatter != info.minfmt and self.isDefault_minfmt:
self.set_minor_formatter(info.minfmt)
self.isDefault_minfmt = True
if info.label is not None and self.isDefault_label:
self.set_label_text(info.label)
self.isDefault_label = True
self.set_default_intervals()
def have_units(self):
return self.converter is not None or self.units is not None
def convert_units(self, x):
# If x is natively supported by Matplotlib, doesn't need converting
if munits._is_natively_supported(x):
return x
if self.converter is None:
self.converter = munits.registry.get_converter(x)
if self.converter is None:
return x
try:
ret = self.converter.convert(x, self.units, self)
except Exception as e:
raise munits.ConversionError('Failed to convert value(s) to axis '
f'units: {x!r}') from e
return ret
def set_units(self, u):
"""
Set the units for axis.
Parameters
----------
u : units tag
"""
if u == self.units:
return
self.units = u
self._update_axisinfo()
self.callbacks.process('units')
self.callbacks.process('units finalize')
self.stale = True
def get_units(self):
"""Return the units for axis."""
return self.units
def set_label_text(self, label, fontdict=None, **kwargs):
"""
Set the text value of the axis label.
Parameters
----------
label : str
Text string.
fontdict : dict
Text properties.
**kwargs
Merged into fontdict.
"""
self.isDefault_label = False
self.label.set_text(label)
if fontdict is not None:
self.label.update(fontdict)
self.label.update(kwargs)
self.stale = True
return self.label
def set_major_formatter(self, formatter):
"""
Set the formatter of the major ticker.
In addition to a `~matplotlib.ticker.Formatter` instance,
this also accepts a ``str`` or function.
For a ``str`` a `~matplotlib.ticker.StrMethodFormatter` is used.
The field used for the value must be labeled ``'x'`` and the field used
for the position must be labeled ``'pos'``.
See the `~matplotlib.ticker.StrMethodFormatter` documentation for
more information.
For a function, a `~matplotlib.ticker.FuncFormatter` is used.
The function must take two inputs (a tick value ``x`` and a
position ``pos``), and return a string containing the corresponding
tick label.
See the `~matplotlib.ticker.FuncFormatter` documentation for
more information.
Parameters
----------
formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
"""
self._set_formatter(formatter, self.major)
def set_minor_formatter(self, formatter):
"""
Set the formatter of the minor ticker.
In addition to a `~matplotlib.ticker.Formatter` instance,
this also accepts a ``str`` or function.
See `.Axis.set_major_formatter` for more information.
Parameters
----------
formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
"""
self._set_formatter(formatter, self.minor)
def _set_formatter(self, formatter, level):
if isinstance(formatter, str):
formatter = mticker.StrMethodFormatter(formatter)
# Don't allow any other TickHelper to avoid easy-to-make errors,
# like using a Locator instead of a Formatter.
elif (callable(formatter) and
not isinstance(formatter, mticker.TickHelper)):
formatter = mticker.FuncFormatter(formatter)
else:
cbook._check_isinstance(mticker.Formatter, formatter=formatter)
if (isinstance(formatter, mticker.FixedFormatter)
and len(formatter.seq) > 0
and not isinstance(level.locator, mticker.FixedLocator)):
cbook._warn_external('FixedFormatter should only be used together '
'with FixedLocator')
if level == self.major:
self.isDefault_majfmt = False
else:
self.isDefault_minfmt = False
level.formatter = formatter
formatter.set_axis(self)
self.stale = True
def set_major_locator(self, locator):
"""
Set the locator of the major ticker.
Parameters
----------
locator : `~matplotlib.ticker.Locator`
"""
cbook._check_isinstance(mticker.Locator, locator=locator)
self.isDefault_majloc = False
self.major.locator = locator
if self.major.formatter:
self.major.formatter._set_locator(locator)
locator.set_axis(self)
self.stale = True
def set_minor_locator(self, locator):
"""
Set the locator of the minor ticker.
Parameters
----------
locator : `~matplotlib.ticker.Locator`
"""
cbook._check_isinstance(mticker.Locator, locator=locator)
self.isDefault_minloc = False
self.minor.locator = locator
if self.minor.formatter:
self.minor.formatter._set_locator(locator)
locator.set_axis(self)
self.stale = True
def set_pickradius(self, pickradius):
"""
Set the depth of the axis used by the picker.
Parameters
----------
pickradius : float
"""
self.pickradius = pickradius
# Helper for set_ticklabels. Defining it here makes it pickleable.
@staticmethod
def _format_with_dict(tickd, x, pos):
return tickd.get(x, "")
def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
r"""
Set the text values of the tick labels.
.. warning::
This method should only be used after fixing the tick positions
using `.Axis.set_ticks`. Otherwise, the labels may end up in
unexpected positions.
Parameters
----------
ticklabels : sequence of str or of `.Text`\s
Texts for labeling each tick location in the sequence set by
`.Axis.set_ticks`; the number of labels must match the number of
locations.
minor : bool
If True, set minor ticks instead of major ticks.
**kwargs
Text properties.
Returns
-------
list of `.Text`\s
For each tick, includes ``tick.label1`` if it is visible, then
``tick.label2`` if it is visible, in that order.
"""
ticklabels = [t.get_text() if hasattr(t, 'get_text') else t
for t in ticklabels]
locator = (self.get_minor_locator() if minor
else self.get_major_locator())
if isinstance(locator, mticker.FixedLocator):
# Passing [] as a list of ticklabels is often used as a way to
# remove all tick labels, so only error for > 0 ticklabels
if len(locator.locs) != len(ticklabels) and len(ticklabels) != 0:
raise ValueError(
"The number of FixedLocator locations"
f" ({len(locator.locs)}), usually from a call to"
" set_ticks, does not match"
f" the number of ticklabels ({len(ticklabels)}).")
tickd = {loc: lab for loc, lab in zip(locator.locs, ticklabels)}
func = functools.partial(self._format_with_dict, tickd)
formatter = mticker.FuncFormatter(func)
else:
formatter = mticker.FixedFormatter(ticklabels)
if minor:
self.set_minor_formatter(formatter)
locs = self.get_minorticklocs()
ticks = self.get_minor_ticks(len(locs))
else:
self.set_major_formatter(formatter)
locs = self.get_majorticklocs()
ticks = self.get_major_ticks(len(locs))
ret = []
for pos, (loc, tick) in enumerate(zip(locs, ticks)):
tick.update_position(loc)
tick_label = formatter(loc, pos)
# deal with label1
tick.label1.set_text(tick_label)
tick.label1.update(kwargs)
# deal with label2
tick.label2.set_text(tick_label)
tick.label2.update(kwargs)
# only return visible tick labels
if tick.label1.get_visible():
ret.append(tick.label1)
if tick.label2.get_visible():
ret.append(tick.label2)
self.stale = True
return ret
# Wrapper around set_ticklabels used to generate Axes.set_x/ytickabels; can
# go away once the API of Axes.set_x/yticklabels becomes consistent.
@cbook._make_keyword_only("3.3", "fontdict")
def _set_ticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
Set this Axis' labels with list of string labels.
.. warning::
This method should only be used after fixing the tick positions
using `.Axis.set_ticks`. Otherwise, the labels may end up in
unexpected positions.
Parameters
----------
labels : list of str
The label texts.
fontdict : dict, optional
A dictionary controlling the appearance of the ticklabels.
The default *fontdict* is::
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
minor : bool, default: False
Whether to set the minor ticklabels rather than the major ones.
Returns
-------
list of `~.Text`
The labels.
Other Parameters
----------------
**kwargs : `~.text.Text` properties.
"""
if fontdict is not None:
kwargs.update(fontdict)
return self.set_ticklabels(labels, minor=minor, **kwargs)
@cbook._make_keyword_only("3.2", "minor")
def set_ticks(self, ticks, minor=False):
"""
Set this Axis' tick locations.
Parameters
----------
ticks : list of floats
List of tick locations.
minor : bool, default: False
If ``False``, set the major ticks; if ``True``, the minor ticks.
"""
# XXX if the user changes units, the information will be lost here
ticks = self.convert_units(ticks)
if len(ticks) > 1:
xleft, xright = self.get_view_interval()
if xright > xleft:
self.set_view_interval(min(ticks), max(ticks))
else:
self.set_view_interval(max(ticks), min(ticks))
self.axes.stale = True
if minor:
self.set_minor_locator(mticker.FixedLocator(ticks))
return self.get_minor_ticks(len(ticks))
else:
self.set_major_locator(mticker.FixedLocator(ticks))
return self.get_major_ticks(len(ticks))
def _get_tick_boxes_siblings(self, xdir, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
raise NotImplementedError('Derived must override')
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine.
"""
raise NotImplementedError('Derived must override')
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the offset text position based on the sequence of bounding
boxes of all the ticklabels.
"""
raise NotImplementedError('Derived must override')
@cbook.deprecated("3.3")
def pan(self, numsteps):
"""Pan by *numsteps* (can be positive or negative)."""
self.major.locator.pan(numsteps)
@cbook.deprecated("3.3")
def zoom(self, direction):
"""Zoom in/out on axis; if *direction* is >0 zoom in, else zoom out."""
self.major.locator.zoom(direction)
def axis_date(self, tz=None):
"""
Sets up axis ticks and labels to treat data along this Axis as dates.
Parameters
----------
tz : str or `datetime.tzinfo`, default: :rc:`timezone`
The timezone used to create date labels.
"""
# By providing a sample datetime instance with the desired timezone,
# the registered converter can be selected, and the "units" attribute,
# which is the timezone, can be set.
if isinstance(tz, str):
import dateutil.tz
tz = dateutil.tz.gettz(tz)
self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz))
def get_tick_space(self):
"""Return the estimated number of ticks that can fit on the axis."""
# Must be overridden in the subclass
raise NotImplementedError()
def _get_ticks_position(self):
"""
Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`.
Check the visibility of tick1line, label1, tick2line, and label2 on
the first major and the first minor ticks, and return
- 1 if only tick1line and label1 are visible (which corresponds to
"bottom" for the x-axis and "left" for the y-axis);
- 2 if only tick2line and label2 are visible (which corresponds to
"top" for the x-axis and "right" for the y-axis);
- "default" if only tick1line, tick2line and label1 are visible;
- "unknown" otherwise.
"""
major = self.majorTicks[0]
minor = self.minorTicks[0]
if all(tick.tick1line.get_visible()
and not tick.tick2line.get_visible()
and tick.label1.get_visible()
and not tick.label2.get_visible()
for tick in [major, minor]):
return 1
elif all(tick.tick2line.get_visible()
and not tick.tick1line.get_visible()
and tick.label2.get_visible()
and not tick.label1.get_visible()
for tick in [major, minor]):
return 2
elif all(tick.tick1line.get_visible()
and tick.tick2line.get_visible()
and tick.label1.get_visible()
and not tick.label2.get_visible()
for tick in [major, minor]):
return "default"
else:
return "unknown"
def get_label_position(self):
"""
Return the label position (top or bottom)
"""
return self.label_position
def set_label_position(self, position):
"""
Set the label position (top or bottom)
Parameters
----------
position : {'top', 'bottom'}
"""
raise NotImplementedError()
def get_minpos(self):
raise NotImplementedError()
def _make_getset_interval(method_name, lim_name, attr_name):
"""
Helper to generate ``get_{data,view}_interval`` and
``set_{data,view}_interval`` implementations.
"""
def getter(self):
# docstring inherited.
return getattr(getattr(self.axes, lim_name), attr_name)
def setter(self, vmin, vmax, ignore=False):
# docstring inherited.
if ignore:
setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
else:
oldmin, oldmax = getter(self)
if oldmin < oldmax:
setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax),
ignore=True)
else:
setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
ignore=True)
self.stale = True
getter.__name__ = f"get_{method_name}_interval"
setter.__name__ = f"set_{method_name}_interval"
return getter, setter
class XAxis(Axis):
__name__ = 'xaxis'
axis_name = 'x' #: Read-only name identifying the axis.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in axes coords, y in display coords (to be updated at draw time by
# _update_label_positions and _update_offset_text_position).
self.label.set(
x=0.5, y=0,
verticalalignment='top', horizontalalignment='center',
transform=mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform()),
)
self.label_position = 'bottom'
self.offsetText.set(
x=1, y=0,
verticalalignment='top', horizontalalignment='right',
transform=mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform()),
fontsize=mpl.rcParams['xtick.labelsize'],
color=mpl.rcParams['xtick.color'],
)
self.offset_text_position = 'bottom'
def contains(self, mouseevent):
"""Test whether the mouse event occurred in the x axis."""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
x, y = mouseevent.x, mouseevent.y
try:
trans = self.axes.transAxes.inverted()
xaxes, yaxes = trans.transform((x, y))
except ValueError:
return False, {}
(l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
inaxis = 0 <= xaxes <= 1 and (
b - self.pickradius < y < b or
t < y < t + self.pickradius)
return inaxis, {}
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return XTick(self.axes, 0, major=major, **tick_kw)
def set_label_position(self, position):
"""
Set the label position (top or bottom)
Parameters
----------
position : {'top', 'bottom'}
"""
self.label.set_verticalalignment(cbook._check_getitem({
'top': 'baseline', 'bottom': 'top',
}, position=position))
self.label_position = position
self.stale = True
def _get_tick_boxes_siblings(self, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
bboxes = []
bboxes2 = []
# get the Grouper that keeps track of x-label groups for this figure
grp = self.figure._align_xlabel_grp
# if we want to align labels from other axes:
for nn, axx in enumerate(grp.get_siblings(self.axes)):
ticks_to_draw = axx.xaxis._update_ticks()
tlb, tlb2 = axx.xaxis._get_tick_bboxes(ticks_to_draw, renderer)
bboxes.extend(tlb)
bboxes2.extend(tlb2)
return bboxes, bboxes2
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine
"""
if not self._autolabelpos:
return
# get bounding boxes for this axis and any siblings
# that have been set by `fig.align_xlabels()`
bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
x, y = self.label.get_position()
if self.label_position == 'bottom':
try:
spine = self.axes.spines['bottom']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
bottom = bbox.y0
self.label.set_position(
(x, bottom - self.labelpad * self.figure.dpi / 72)
)
else:
try:
spine = self.axes.spines['top']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
top = bbox.y1
self.label.set_position(
(x, top + self.labelpad * self.figure.dpi / 72)
)
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels
"""
x, y = self.offsetText.get_position()
if not hasattr(self, '_tick_position'):
self._tick_position = 'bottom'
if self._tick_position == 'bottom':
if not len(bboxes):
bottom = self.axes.bbox.ymin
else:
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
y = bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72
else:
if not len(bboxes2):
top = self.axes.bbox.ymax
else:
bbox = mtransforms.Bbox.union(bboxes2)
top = bbox.y1
y = top + self.OFFSETTEXTPAD * self.figure.dpi / 72
self.offsetText.set_position((x, y))
def get_text_heights(self, renderer):
"""
Return how much space should be reserved for text above and below the
axes, as a pair of floats.
"""
bbox, bbox2 = self.get_ticklabel_extents(renderer)
# MGDTODO: Need a better way to get the pad
padPixels = self.majorTicks[0].get_pad_pixels()
above = 0.0
if bbox2.height:
above += bbox2.height + padPixels
below = 0.0
if bbox.height:
below += bbox.height + padPixels
if self.get_label_position() == 'top':
above += self.label.get_window_extent(renderer).height + padPixels
else:
below += self.label.get_window_extent(renderer).height + padPixels
return above, below
def set_ticks_position(self, position):
"""
Set the ticks position.
Parameters
----------
position : {'top', 'bottom', 'both', 'default', 'none'}
'both' sets the ticks to appear on both positions, but does not
change the tick labels. 'default' resets the tick positions to
the default: ticks on both positions, labels at bottom. 'none'
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
"""
cbook._check_in_list(['top', 'bottom', 'both', 'default', 'none'],
position=position)
if position == 'top':
self.set_tick_params(which='both', top=True, labeltop=True,
bottom=False, labelbottom=False)
self._tick_position = 'top'
self.offsetText.set_verticalalignment('bottom')
elif position == 'bottom':
self.set_tick_params(which='both', top=False, labeltop=False,
bottom=True, labelbottom=True)
self._tick_position = 'bottom'
self.offsetText.set_verticalalignment('top')
elif position == 'both':
self.set_tick_params(which='both', top=True,
bottom=True)
elif position == 'none':
self.set_tick_params(which='both', top=False,
bottom=False)
elif position == 'default':
self.set_tick_params(which='both', top=True, labeltop=False,
bottom=True, labelbottom=True)
self._tick_position = 'bottom'
self.offsetText.set_verticalalignment('top')
else:
assert False, "unhandled parameter not caught by _check_in_list"
self.stale = True
def tick_top(self):
"""
Move ticks and ticklabels (if present) to the top of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('top')
# If labels were turned off before this was called, leave them off.
self.set_tick_params(which='both', labeltop=label)
def tick_bottom(self):
"""
Move ticks and ticklabels (if present) to the bottom of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('bottom')
# If labels were turned off before this was called, leave them off.
self.set_tick_params(which='both', labelbottom=label)
def get_ticks_position(self):
"""
Return the ticks position ("top", "bottom", "default", or "unknown").
"""
return {1: "bottom", 2: "top",
"default": "default", "unknown": "unknown"}[
self._get_ticks_position()]
get_view_interval, set_view_interval = _make_getset_interval(
"view", "viewLim", "intervalx")
get_data_interval, set_data_interval = _make_getset_interval(
"data", "dataLim", "intervalx")
def get_minpos(self):
return self.axes.dataLim.minposx
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
# cast to bool to avoid bad interaction between python 3.8 and np.bool_
self.axes.set_xlim(sorted((a, b), reverse=bool(inverted)), auto=None)
def set_default_intervals(self):
# docstring inherited
xmin, xmax = 0., 1.
dataMutated = self.axes.dataLim.mutatedx()
viewMutated = self.axes.viewLim.mutatedx()
if not dataMutated or not viewMutated:
if self.converter is not None:
info = self.converter.axisinfo(self.units, self)
if info.default_limits is not None:
valmin, valmax = info.default_limits
xmin = self.converter.convert(valmin, self.units, self)
xmax = self.converter.convert(valmax, self.units, self)
if not dataMutated:
self.axes.dataLim.intervalx = xmin, xmax
if not viewMutated:
self.axes.viewLim.intervalx = xmin, xmax
self.stale = True
def get_tick_space(self):
ends = self.axes.transAxes.transform([[0, 0], [1, 0]])
length = ((ends[1][0] - ends[0][0]) / self.axes.figure.dpi) * 72
# There is a heuristic here that the aspect ratio of tick text
# is no more than 3:1
size = self._get_tick_label_size('x') * 3
if size > 0:
return int(np.floor(length / size))
else:
return 2**31 - 1
class YAxis(Axis):
__name__ = 'yaxis'
axis_name = 'y' #: Read-only name identifying the axis.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in display coords, y in axes coords (to be updated at draw time by
# _update_label_positions and _update_offset_text_position).
self.label.set(
x=0, y=0.5,
verticalalignment='bottom', horizontalalignment='center',
rotation='vertical', rotation_mode='anchor',
transform=mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), self.axes.transAxes),
)
self.label_position = 'left'
# x in axes coords, y in display coords(!).
self.offsetText.set(
x=0, y=0.5,
verticalalignment='baseline', horizontalalignment='left',
transform=mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform()),
fontsize=mpl.rcParams['ytick.labelsize'],
color=mpl.rcParams['ytick.color'],
)
self.offset_text_position = 'left'
def contains(self, mouseevent):
# docstring inherited
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
x, y = mouseevent.x, mouseevent.y
try:
trans = self.axes.transAxes.inverted()
xaxes, yaxes = trans.transform((x, y))
except ValueError:
return False, {}
(l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
inaxis = 0 <= yaxes <= 1 and (
l - self.pickradius < x < l or
r < x < r + self.pickradius)
return inaxis, {}
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return YTick(self.axes, 0, major=major, **tick_kw)
def set_label_position(self, position):
"""
Set the label position (left or right)
Parameters
----------
position : {'left', 'right'}
"""
self.label.set_rotation_mode('anchor')
self.label.set_horizontalalignment('center')
self.label.set_verticalalignment(cbook._check_getitem({
'left': 'bottom', 'right': 'top',
}, position=position))
self.label_position = position
self.stale = True
def _get_tick_boxes_siblings(self, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
bboxes = []
bboxes2 = []
# get the Grouper that keeps track of y-label groups for this figure
grp = self.figure._align_ylabel_grp
# if we want to align labels from other axes:
for axx in grp.get_siblings(self.axes):
ticks_to_draw = axx.yaxis._update_ticks()
tlb, tlb2 = axx.yaxis._get_tick_bboxes(ticks_to_draw, renderer)
bboxes.extend(tlb)
bboxes2.extend(tlb2)
return bboxes, bboxes2
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine
"""
if not self._autolabelpos:
return
# get bounding boxes for this axis and any siblings
# that have been set by `fig.align_ylabels()`
bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
x, y = self.label.get_position()
if self.label_position == 'left':
try:
spine = self.axes.spines['left']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
left = bbox.x0
self.label.set_position(
(left - self.labelpad * self.figure.dpi / 72, y)
)
else:
try:
spine = self.axes.spines['right']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
right = bbox.x1
self.label.set_position(
(right + self.labelpad * self.figure.dpi / 72, y)
)
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels
"""
x, y = self.offsetText.get_position()
top = self.axes.bbox.ymax
self.offsetText.set_position(
(x, top + self.OFFSETTEXTPAD * self.figure.dpi / 72)
)
def set_offset_position(self, position):
"""
Parameters
----------
position : {'left', 'right'}
"""
x, y = self.offsetText.get_position()
x = cbook._check_getitem({'left': 0, 'right': 1}, position=position)
self.offsetText.set_ha(position)
self.offsetText.set_position((x, y))
self.stale = True
def get_text_widths(self, renderer):
bbox, bbox2 = self.get_ticklabel_extents(renderer)
# MGDTODO: Need a better way to get the pad
padPixels = self.majorTicks[0].get_pad_pixels()
left = 0.0
if bbox.width:
left += bbox.width + padPixels
right = 0.0
if bbox2.width:
right += bbox2.width + padPixels
if self.get_label_position() == 'left':
left += self.label.get_window_extent(renderer).width + padPixels
else:
right += self.label.get_window_extent(renderer).width + padPixels
return left, right
def set_ticks_position(self, position):
"""
Set the ticks position.
Parameters
----------
position : {'left', 'right', 'both', 'default', 'none'}
'both' sets the ticks to appear on both positions, but does not
change the tick labels. 'default' resets the tick positions to
the default: ticks on both positions, labels at left. 'none'
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
"""
cbook._check_in_list(['left', 'right', 'both', 'default', 'none'],
position=position)
if position == 'right':
self.set_tick_params(which='both', right=True, labelright=True,
left=False, labelleft=False)
self.set_offset_position(position)
elif position == 'left':
self.set_tick_params(which='both', right=False, labelright=False,
left=True, labelleft=True)
self.set_offset_position(position)
elif position == 'both':
self.set_tick_params(which='both', right=True,
left=True)
elif position == 'none':
self.set_tick_params(which='both', right=False,
left=False)
elif position == 'default':
self.set_tick_params(which='both', right=True, labelright=False,
left=True, labelleft=True)
else:
assert False, "unhandled parameter not caught by _check_in_list"
self.stale = True
def tick_right(self):
"""
Move ticks and ticklabels (if present) to the right of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('right')
# if labels were turned off before this was called
# leave them off
self.set_tick_params(which='both', labelright=label)
def tick_left(self):
"""
Move ticks and ticklabels (if present) to the left of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('left')
# if labels were turned off before this was called
# leave them off
self.set_tick_params(which='both', labelleft=label)
def get_ticks_position(self):
"""
Return the ticks position ("left", "right", "default", or "unknown").
"""
return {1: "left", 2: "right",
"default": "default", "unknown": "unknown"}[
self._get_ticks_position()]
get_view_interval, set_view_interval = _make_getset_interval(
"view", "viewLim", "intervaly")
get_data_interval, set_data_interval = _make_getset_interval(
"data", "dataLim", "intervaly")
def get_minpos(self):
return self.axes.dataLim.minposy
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
# cast to bool to avoid bad interaction between python 3.8 and np.bool_
self.axes.set_ylim(sorted((a, b), reverse=bool(inverted)), auto=None)
def set_default_intervals(self):
# docstring inherited
ymin, ymax = 0., 1.
dataMutated = self.axes.dataLim.mutatedy()
viewMutated = self.axes.viewLim.mutatedy()
if not dataMutated or not viewMutated:
if self.converter is not None:
info = self.converter.axisinfo(self.units, self)
if info.default_limits is not None:
valmin, valmax = info.default_limits
ymin = self.converter.convert(valmin, self.units, self)
ymax = self.converter.convert(valmax, self.units, self)
if not dataMutated:
self.axes.dataLim.intervaly = ymin, ymax
if not viewMutated:
self.axes.viewLim.intervaly = ymin, ymax
self.stale = True
def get_tick_space(self):
ends = self.axes.transAxes.transform([[0, 0], [0, 1]])
length = ((ends[1][1] - ends[0][1]) / self.axes.figure.dpi) * 72
# Having a spacing of at least 2 just looks good.
size = self._get_tick_label_size('y') * 2
if size > 0:
return int(np.floor(length / size))
else:
return 2**31 - 1