rizzma 1.6.1

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
Documentation
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
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
//! Tick locators and formatters, ported from matplotlib's `ticker.py`.
//!
//! This module implements the tick-location and label-formatting engine used by
//! axes. The algorithms are faithful ports of matplotlib's reference
//! implementation (`lib/matplotlib/ticker.py`), in particular the nice-number
//! [`MaxNLocator`]. The intent is bit-for-bit parity with matplotlib's tick
//! vectors, including matplotlib's reliance on floating-point floor division and
//! the inclusive-edge epsilon fudges.
//!
//! Everything is pure `f64`; there are no external dependencies and no `unsafe`.
//! Unicode-minus handling is out of scope, so negative numbers use an ASCII
//! hyphen-minus.
//!
//! # Locators
//!
//! A [`Locator`] maps a `(vmin, vmax)` view interval to a vector of tick
//! positions. Implemented locators:
//!
//! - [`MaxNLocator`] — the nice-number locator (default of most axes).
//! - [`AutoLocator`] — a [`MaxNLocator`] preset (`nbins = auto`,
//!   `steps = [1, 2, 2.5, 5, 10]`).
//! - [`AutoMinorLocator`] — automatic minor ticks between linear major ticks.
//! - [`MultipleLocator`] — ticks at integer multiples of a base.
//! - [`LinearLocator`] — evenly spaced ticks via linspace.
//! - [`FixedLocator`] — a fixed set of positions (optionally subsampled).
//! - [`IndexLocator`] — ticks on regularly spaced index positions.
//! - [`LogLocator`] — logarithmic ticks at powers of a base, optionally with
//!   subticks.
//! - [`SymlogLocator`] — symmetric-log ticks with a linear region around zero.
//! - [`AsinhLocator`] — inverse-hyperbolic-sine ticks across zero.
//! - [`LogitLocator`] — probability ticks clustered toward zero and one.
//! - [`NullLocator`] — no ticks.
//!
//! # Formatters
//!
//! A [`Formatter`] turns a tick value (and optional position index) into a
//! label string. Implemented formatters:
//!
//! - [`ScalarFormatter`] — picks significant figures from the tick spacing.
//! - [`LogFormatter`] — labels logarithmic major ticks.
//! - [`LogFormatterMathtext`] — labels large logarithmic powers as mathtext.
//! - [`SymlogFormatter`] — labels symmetric-log ticks across zero.
//! - [`SymlogFormatterMathtext`] — labels large symmetric-log powers as mathtext.
//! - [`AsinhFormatter`] — labels inverse-hyperbolic-sine ticks across zero.
//! - [`AsinhFormatterMathtext`] — labels large asinh tail powers as mathtext.
//! - [`LogitFormatter`] — labels probability ticks on a logit scale.
//! - [`LogitFormatterMathtext`] — labels logit probability tails as mathtext.
//! - [`EngFormatter`] — labels values with SI engineering prefixes.
//! - [`PercentFormatter`] — labels values as percentages.
//! - [`NullFormatter`] — always the empty string.
//! - [`FixedFormatter`] — fixed strings indexed by position.
//! - [`IndexFormatter`] — fixed strings indexed by rounded tick value.
//! - [`FuncFormatter`] — a user-supplied boxed closure.
//! - [`FormatStrFormatter`] — a `%`-style numeric format string.
//! - [`StrMethodFormatter`] — a `{x}`/`{pos}` template string.

/// Determine tick locations for an axis.
///
/// This is the Rust analogue of matplotlib's `Locator` base class. The core
/// method is [`Locator::tick_values`]; [`Locator::view_limits`] optionally
/// adjusts the view interval and defaults to the identity.
pub trait Locator: Send + Sync {
    /// Return the tick positions for the closed view interval `[vmin, vmax]`.
    ///
    /// Locations slightly beyond the limits may be included to support
    /// autoscaling, matching matplotlib's behaviour.
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64>;

    /// Select a view interval for the data range `[vmin, vmax]`.
    ///
    /// The default implementation returns the range unchanged.
    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        (vmin, vmax)
    }
}

/// Format a tick value into a label string.
///
/// This is the Rust analogue of matplotlib's `Formatter` base class. `pos` is
/// the index of the tick among the visible ticks (matplotlib passes `None` in
/// some contexts), and is used by position-based formatters such as
/// [`FixedFormatter`].
pub trait Formatter: Send + Sync {
    /// Return the label for `value` at the optional position index `pos`.
    fn format(&self, value: f64, pos: Option<usize>) -> String;

    /// Return labels for a whole tick vector.
    ///
    /// Most formatters can format each value independently. Context-aware
    /// formatters, such as concise date labels, override this method.
    fn format_ticks(&self, values: &[f64]) -> Vec<String> {
        values
            .iter()
            .enumerate()
            .map(|(i, &value)| self.format(value, Some(i)))
            .collect()
    }
}

/// Python-style floor division (`a // b`).
///
/// Rust's `/` on `f64` truncates toward zero only after the fact via `floor`;
/// Python's `//` floors the quotient. Matplotlib relies on floor semantics
/// (e.g. for negative `vmin`), so we replicate it explicitly.
fn floordiv(a: f64, b: f64) -> f64 {
    (a / b).floor()
}

/// Python-style `divmod(x, step)` returning `(floor(x/step), x - floor*step)`.
fn divmod(x: f64, step: f64) -> (f64, f64) {
    let d = floordiv(x, step);
    (d, x - d * step)
}

/// matplotlib `transforms._nonsingular`: expand/swap a range to avoid
/// singularities.
///
/// Mirrors the reference logic: non-finite inputs collapse to
/// `(-expander, expander)`; reversed inputs are swapped (when `increasing`);
/// and intervals that are too small relative to their magnitude are expanded.
fn nonsingular(
    mut vmin: f64,
    mut vmax: f64,
    expander: f64,
    tiny: f64,
    increasing: bool,
) -> (f64, f64) {
    if !vmin.is_finite() || !vmax.is_finite() {
        return (-expander, expander);
    }

    let mut swapped = false;
    if vmax < vmin {
        std::mem::swap(&mut vmin, &mut vmax);
        swapped = true;
    }

    let maxabsvalue = vmin.abs().max(vmax.abs());
    // `(1e6 / tiny) * f64::MIN_POSITIVE` reproduces matplotlib's
    // `(1e6 / tiny) * np.finfo(float).tiny`.
    if maxabsvalue < (1e6 / tiny) * f64::MIN_POSITIVE {
        vmin = -expander;
        vmax = expander;
    } else if vmax - vmin <= maxabsvalue * tiny {
        vmin -= expander * maxabsvalue;
        vmax += expander * maxabsvalue;
    }

    if swapped && !increasing {
        std::mem::swap(&mut vmin, &mut vmax);
    }
    (vmin, vmax)
}

/// matplotlib `ticker.scale_range`: pick a power-of-ten scale and offset.
///
/// Returns `(scale, offset)` where `scale` is `10**floor(log10(dv / n))` and
/// `offset` is a power-of-ten offset used when the mean dwarfs the span.
fn scale_range(vmin: f64, vmax: f64, n: f64, threshold: f64) -> (f64, f64) {
    let dv = (vmax - vmin).abs();
    let meanv = (vmax + vmin) / 2.0;
    let offset = if dv == 0.0 || meanv.abs() / dv < threshold {
        0.0
    } else {
        (10f64.powf(floordiv(meanv.abs().log10(), 1.0))).copysign(meanv)
    };
    let scale = 10f64.powf(floordiv((dv / n).log10(), 1.0));
    (scale, offset)
}

/// Helper that computes integer multiples of a step with float-precision slop.
///
/// Port of matplotlib's `_Edge_integer`. Used by [`MaxNLocator`] and
/// [`MultipleLocator`] to find the smallest/largest integer `n` such that
/// `n * step` brackets a value, accounting for floating-point error.
#[derive(Clone, Copy, Debug)]
struct EdgeInteger {
    step: f64,
    offset: f64,
}

impl EdgeInteger {
    /// Create an edge helper for `step` with an absolute `offset`.
    ///
    /// `step` must be positive (matplotlib raises otherwise).
    fn new(step: f64, offset: f64) -> Self {
        debug_assert!(step > 0.0, "'step' must be positive");
        EdgeInteger {
            step,
            offset: offset.abs(),
        }
    }

    /// Whether `ms` is within tolerance of the integer `edge`.
    ///
    /// Tolerance widens when the offset is large relative to the step, exactly
    /// as in matplotlib.
    fn closeto(&self, ms: f64, edge: f64) -> bool {
        let tol = if self.offset > 0.0 {
            let digits = (self.offset / self.step).log10();
            (10f64.powf(digits - 12.0)).clamp(1e-10, 0.4999)
        } else {
            1e-10
        };
        (ms - edge).abs() < tol
    }

    /// Largest `n` such that `n * step <= x`.
    fn le(&self, x: f64) -> f64 {
        let (d, m) = divmod(x, self.step);
        if self.closeto(m / self.step, 1.0) {
            d + 1.0
        } else {
            d
        }
    }

    /// Smallest `n` such that `n * step >= x`.
    fn ge(&self, x: f64) -> f64 {
        let (d, m) = divmod(x, self.step);
        if self.closeto(m / self.step, 0.0) {
            d
        } else {
            d + 1.0
        }
    }
}

/// How many bins (intervals) a [`MaxNLocator`] should use.
///
/// `Auto` mirrors matplotlib's `nbins='auto'`; with no axis attached it
/// resolves to 9, matching the reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NBins {
    /// A fixed maximum number of intervals (one fewer than the max tick count).
    Fixed(usize),
    /// Automatic: resolves to 9 in the axis-less case used here.
    Auto,
}

/// Edge-tick pruning mode for [`MaxNLocator`].
///
/// This mirrors matplotlib's `prune` option: when an edge tick lands exactly on
/// the view limit, it can be suppressed to avoid duplicate labels on stacked or
/// shared axes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TickPrune {
    /// Keep all ticks.
    #[default]
    None,
    /// Drop a tick that coincides with the lower view limit.
    Lower,
    /// Drop a tick that coincides with the upper view limit.
    Upper,
    /// Drop ticks that coincide with either view limit.
    Both,
}

/// Nice-number tick locator: evenly spaced ticks capped at `nbins + 1` ticks.
///
/// Faithful port of matplotlib's `MaxNLocator`. It finds "nice" tick locations
/// (integer multiples of `1, 2, 2.5, 5, ...` scaled by a power of ten) with no
/// more than `nbins + 1` ticks within the view limits, adding edge ticks beyond
/// the limits to support autoscaling.
pub struct MaxNLocator {
    nbins: NBins,
    /// The extended staircase of candidate step mantissas, already including the
    /// 0.1× and 10× wrap-around entries.
    extended_steps: Vec<f64>,
    integer: bool,
    symmetric: bool,
    min_n_ticks: usize,
    prune: TickPrune,
}

impl MaxNLocator {
    /// matplotlib's default `steps=None` expands to this mantissa sequence.
    const DEFAULT_STEPS: [f64; 10] = [1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0];

    /// Construct a `MaxNLocator` with the given bin count and default steps.
    ///
    /// Equivalent to matplotlib's `MaxNLocator(nbins=...)` with `steps=None`,
    /// `integer=False`, `symmetric=False`, `min_n_ticks=2`.
    pub fn new(nbins: NBins) -> Self {
        Self::with_steps(nbins, &Self::DEFAULT_STEPS, false, false, 2)
    }

    /// Construct a `MaxNLocator` with full control over its parameters.
    ///
    /// `steps` is validated and normalised (prepending `1` / appending `10`)
    /// just like matplotlib's `_validate_steps`, then expanded into the
    /// extended staircase used during location.
    pub fn with_steps(
        nbins: NBins,
        steps: &[f64],
        integer: bool,
        symmetric: bool,
        min_n_ticks: usize,
    ) -> Self {
        let steps = Self::validate_steps(steps);
        let extended_steps = Self::staircase(&steps);
        MaxNLocator {
            nbins,
            extended_steps,
            integer,
            symmetric,
            min_n_ticks: min_n_ticks.max(1),
            prune: TickPrune::None,
        }
    }

    /// Return a copy of this locator with edge pruning enabled.
    ///
    /// Pruning is opt-in and leaves the default matplotlib-style tick vectors
    /// unchanged.
    #[must_use]
    pub fn with_prune(mut self, prune: TickPrune) -> Self {
        self.prune = prune;
        self
    }

    /// Return a copy of this locator constrained to integer tick steps when
    /// enough integer values are visible.
    #[must_use]
    pub fn with_integer(mut self, integer: bool) -> Self {
        self.integer = integer;
        self
    }

    /// Return a copy of this locator whose view limits and ticks are symmetric
    /// about zero.
    #[must_use]
    pub fn with_symmetric(mut self, symmetric: bool) -> Self {
        self.symmetric = symmetric;
        self
    }

    /// Return a copy of this locator with a minimum visible tick count.
    ///
    /// Values below one are clamped to one, matching [`MaxNLocator::with_steps`].
    #[must_use]
    pub fn with_min_n_ticks(mut self, min_n_ticks: usize) -> Self {
        self.min_n_ticks = min_n_ticks.max(1);
        self
    }

    /// Return the configured bin-count policy.
    #[must_use]
    pub fn nbins(&self) -> NBins {
        self.nbins
    }

    /// Return whether this locator is constrained to integer tick steps when
    /// enough integer values are visible.
    #[must_use]
    pub fn integer(&self) -> bool {
        self.integer
    }

    /// Return whether this locator mirrors view limits and ticks about zero.
    #[must_use]
    pub fn symmetric(&self) -> bool {
        self.symmetric
    }

    /// Return the configured minimum visible tick count.
    #[must_use]
    pub fn min_n_ticks(&self) -> usize {
        self.min_n_ticks
    }

    /// Return the configured edge-pruning mode.
    #[must_use]
    pub fn prune(&self) -> TickPrune {
        self.prune
    }

    /// Validate and normalise a `steps` sequence (port of `_validate_steps`).
    ///
    /// Requires a strictly increasing sequence within `[1, 10]`; prepends `1`
    /// and/or appends `10` if missing.
    fn validate_steps(steps: &[f64]) -> Vec<f64> {
        assert!(!steps.is_empty(), "steps must be non-empty");
        for w in steps.windows(2) {
            assert!(
                w[1] - w[0] > 0.0,
                "steps argument must be an increasing sequence between 1 and 10"
            );
        }
        assert!(
            *steps.last().unwrap() <= 10.0 && steps[0] >= 1.0,
            "steps argument must be an increasing sequence between 1 and 10"
        );
        let mut v: Vec<f64> = Vec::with_capacity(steps.len() + 2);
        if steps[0] != 1.0 {
            v.push(1.0);
        }
        v.extend_from_slice(steps);
        if *steps.last().unwrap() != 10.0 {
            v.push(10.0);
        }
        v
    }

    /// Build the extended staircase (port of `_staircase`).
    ///
    /// `concat(0.1 * steps[:-1], steps, [10 * steps[1]])`.
    fn staircase(steps: &[f64]) -> Vec<f64> {
        let mut out = Vec::with_capacity(steps.len() * 2);
        for &s in &steps[..steps.len() - 1] {
            out.push(0.1 * s);
        }
        out.extend_from_slice(steps);
        out.push(10.0 * steps[1]);
        out
    }

    /// Resolve `nbins` to a concrete count (axis-less case: `Auto` -> 9).
    fn resolved_nbins(&self) -> f64 {
        match self.nbins {
            NBins::Fixed(n) => n as f64,
            NBins::Auto => 9.0,
        }
    }

    /// Generate raw tick locations spanning `[vmin, vmax]` (port of `_raw_ticks`).
    ///
    /// May include one tick on either side of the range; those are trimmed by
    /// `tick_values` only via pruning (not implemented here, matching the
    /// default `prune=None`).
    fn raw_ticks(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        let nbins = self.resolved_nbins();
        let (scale, offset) = scale_range(vmin, vmax, nbins, 100.0);
        let vmin_o = vmin - offset;
        let vmax_o = vmax - offset;

        let mut steps: Vec<f64> = self.extended_steps.iter().map(|&s| s * scale).collect();
        if self.integer {
            // Keep steps < 1 or steps that are (near) integers.
            steps.retain(|&s| s < 1.0 || (s - s.round()).abs() < 0.001);
        }

        let raw_step = (vmax_o - vmin_o) / nbins;
        let large_steps: Vec<bool> = steps.iter().map(|&s| s >= raw_step).collect();

        // Index of the smallest "large" step (>= raw_step), or the last step.
        let istep = large_steps
            .iter()
            .position(|&b| b)
            .unwrap_or(steps.len() - 1);

        // Start at the smallest of the large steps and walk backwards until a
        // step yields at least `min_n_ticks` displayed ticks.
        let mut ticks: Vec<f64> = Vec::new();
        for &step0 in steps[..=istep].iter().rev() {
            let mut step = step0;
            if self.integer && (vmax_o.floor() - vmin_o.ceil()) >= (self.min_n_ticks as f64 - 1.0) {
                step = step.max(1.0);
            }
            let best_vmin = floordiv(vmin_o, step) * step;

            let edge = EdgeInteger::new(step, offset);
            let low = edge.le(vmin_o - best_vmin);
            let high = edge.ge(vmax_o - best_vmin);

            let n = (high - low) as i64;
            ticks = (0..=n)
                .map(|i| (low + i as f64) * step + best_vmin)
                .collect();

            let nticks = ticks
                .iter()
                .filter(|&&t| t <= vmax_o && t >= vmin_o)
                .count();
            if nticks >= self.min_n_ticks {
                break;
            }
        }

        ticks.iter().map(|&t| t + offset).collect()
    }

    fn prune_ticks(&self, ticks: Vec<f64>, vmin: f64, vmax: f64) -> Vec<f64> {
        if self.prune == TickPrune::None || ticks.is_empty() {
            return ticks;
        }

        let mut first = 0;
        let mut last = ticks.len();
        if matches!(self.prune, TickPrune::Lower | TickPrune::Both) && same_tick(ticks[first], vmin)
        {
            first += 1;
        }
        if first < last
            && matches!(self.prune, TickPrune::Upper | TickPrune::Both)
            && same_tick(ticks[last - 1], vmax)
        {
            last -= 1;
        }
        ticks[first..last].to_vec()
    }
}

impl Locator for MaxNLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        let (mut vmin, mut vmax) = (vmin, vmax);
        if self.symmetric {
            vmax = vmin.abs().max(vmax.abs());
            vmin = -vmax;
        }
        let (vmin, vmax) = nonsingular(vmin, vmax, 1e-13, 1e-14, true);
        self.prune_ticks(self.raw_ticks(vmin, vmax), vmin, vmax)
    }

    fn view_limits(&self, dmin: f64, dmax: f64) -> (f64, f64) {
        let (mut dmin, mut dmax) = (dmin, dmax);
        if self.symmetric {
            dmax = dmin.abs().max(dmax.abs());
            dmin = -dmax;
        }
        // Default autolimit mode is not 'round_numbers', so return as-is after
        // the singularity guard.
        nonsingular(dmin, dmax, 1e-12, 1e-13, true)
    }
}

impl Default for MaxNLocator {
    /// matplotlib's `MaxNLocator()` default: `nbins=10`, default steps.
    fn default() -> Self {
        Self::new(NBins::Fixed(10))
    }
}

/// Automatic locator: a [`MaxNLocator`] preset (`nbins=auto`, nice steps).
///
/// Port of matplotlib's `AutoLocator`, which is `MaxNLocator(nbins='auto',
/// steps=[1, 2, 2.5, 5, 10])` in modern (non-classic) mode.
pub struct AutoLocator {
    inner: MaxNLocator,
}

impl AutoLocator {
    /// Construct the default `AutoLocator`.
    pub fn new() -> Self {
        AutoLocator {
            inner: MaxNLocator::with_steps(
                NBins::Auto,
                &[1.0, 2.0, 2.5, 5.0, 10.0],
                false,
                false,
                2,
            ),
        }
    }
}

impl Default for AutoLocator {
    fn default() -> Self {
        Self::new()
    }
}

impl Locator for AutoLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        self.inner.tick_values(vmin, vmax)
    }

    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        self.inner.view_limits(vmin, vmax)
    }
}

/// Automatic minor ticks between linear major ticks.
///
/// This stateless analogue of matplotlib's `AutoMinorLocator` derives major
/// ticks from [`AutoLocator`] for the requested view interval, then subdivides
/// each major interval. With the default setting it uses 5 subdivisions when
/// the major-step mantissa is 1, 2.5, 5, or 10, and 4 subdivisions otherwise,
/// matching matplotlib's `n='auto'` behavior.
pub struct AutoMinorLocator {
    subdivisions: Option<usize>,
}

impl AutoMinorLocator {
    /// Create an automatic minor locator with matplotlib-style subdivision
    /// selection.
    pub fn new() -> Self {
        AutoMinorLocator { subdivisions: None }
    }

    /// Create an automatic minor locator with an explicit number of
    /// subdivisions per major interval.
    ///
    /// Values below 2 cannot produce minor ticks and therefore return an empty
    /// vector from [`Locator::tick_values`].
    pub fn with_subdivisions(subdivisions: usize) -> Self {
        AutoMinorLocator {
            subdivisions: Some(subdivisions),
        }
    }

    /// Return the explicit subdivision count, or `None` for automatic
    /// matplotlib-style selection.
    #[must_use]
    pub fn subdivisions(&self) -> Option<usize> {
        self.subdivisions
    }

    /// Return automatic minor ticks for an explicit set of major ticks.
    ///
    /// This mirrors the normal [`Locator::tick_values`] behavior, but uses the
    /// caller-provided major tick positions instead of deriving them from
    /// [`AutoLocator`]. This is useful when an axis has already selected major
    /// ticks with a custom locator and wants the matching linear minor ticks.
    pub fn tick_values_from_major(&self, major_locs: &[f64], vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() || vmin == vmax {
            return Vec::new();
        }

        let reversed = vmax < vmin;
        let (lo, hi) = if reversed { (vmax, vmin) } else { (vmin, vmax) };
        let mut major_locs: Vec<f64> = major_locs
            .iter()
            .copied()
            .filter(|value| value.is_finite())
            .collect();
        major_locs.sort_by(|a, b| a.partial_cmp(b).expect("finite majors are comparable"));
        major_locs.dedup_by(|a, b| same_tick(*a, *b));
        if major_locs.len() < 2 {
            return Vec::new();
        }

        let major_step = major_locs
            .windows(2)
            .map(|pair| (pair[1] - pair[0]).abs())
            .find(|step| *step > 0.0 && step.is_finite())
            .unwrap_or(0.0);
        if major_step <= 0.0 || !major_step.is_finite() {
            return Vec::new();
        }

        let subdivisions = self
            .subdivisions
            .unwrap_or_else(|| auto_minor_subdivisions(major_step));
        if subdivisions < 2 {
            return Vec::new();
        }

        let minor_step = major_step / subdivisions as f64;
        let first = (lo / minor_step).ceil() as i64;
        let last = (hi / minor_step).floor() as i64;
        if last < first {
            return Vec::new();
        }

        let mut ticks = Vec::new();
        for i in first..=last {
            let tick = i as f64 * minor_step;
            if tick < lo - 1e-12 || tick > hi + 1e-12 {
                continue;
            }
            if major_locs.iter().any(|major| same_tick(tick, *major)) {
                continue;
            }
            ticks.push(tick);
        }
        if reversed {
            ticks.reverse();
        }
        ticks
    }
}

impl Default for AutoMinorLocator {
    fn default() -> Self {
        Self::new()
    }
}

impl Locator for AutoMinorLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        let (lo, hi) = if vmax < vmin {
            (vmax, vmin)
        } else {
            (vmin, vmax)
        };
        let major_locs = AutoLocator::new().tick_values(lo, hi);
        self.tick_values_from_major(&major_locs, vmin, vmax)
    }
}

fn auto_minor_subdivisions(major_step: f64) -> usize {
    let exponent = major_step.abs().log10().floor();
    let mantissa = major_step / 10f64.powf(exponent);
    if [1.0, 2.5, 5.0, 10.0]
        .iter()
        .any(|candidate| (mantissa - candidate).abs() < 1e-10)
    {
        5
    } else {
        4
    }
}

fn same_tick(a: f64, b: f64) -> bool {
    let scale = a.abs().max(b.abs()).max(1.0);
    (a - b).abs() <= scale * 1e-12
}

/// Place ticks at every integer multiple of a base (plus an offset).
///
/// Port of matplotlib's `MultipleLocator`.
pub struct MultipleLocator {
    edge: EdgeInteger,
    offset: f64,
}

impl MultipleLocator {
    /// Create a locator with the given positive `base` and zero offset.
    pub fn new(base: f64) -> Self {
        Self::with_offset(base, 0.0)
    }

    /// Create a locator with the given positive `base` and additive `offset`.
    pub fn with_offset(base: f64, offset: f64) -> Self {
        assert!(
            base.is_finite() && base > 0.0,
            "multiple locator base must be finite and > 0"
        );
        MultipleLocator {
            edge: EdgeInteger::new(base, 0.0),
            offset,
        }
    }

    /// Return the configured tick spacing.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.edge.step
    }

    /// Return the configured additive tick offset.
    #[must_use]
    pub fn offset(&self) -> f64 {
        self.offset
    }
}

impl Default for MultipleLocator {
    /// Create a locator with unit tick spacing and zero offset.
    fn default() -> Self {
        MultipleLocator::new(1.0)
    }
}

impl Locator for MultipleLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        let (mut vmin, mut vmax) = (vmin, vmax);
        if vmax < vmin {
            std::mem::swap(&mut vmin, &mut vmax);
        }
        let step = self.edge.step;
        vmin -= self.offset;
        vmax -= self.offset;
        let vmin = self.edge.ge(vmin) * step;
        let n = floordiv(vmax - vmin + 0.001 * step, step);
        let count = n as i64 + 3;
        (0..count)
            .map(|i| vmin - step + i as f64 * step + self.offset)
            .collect()
    }

    fn view_limits(&self, dmin: f64, dmax: f64) -> (f64, f64) {
        // Default autolimit mode ('data'): return the data range unchanged
        // after the singularity guard.
        nonsingular(dmin, dmax, 0.001, 1e-15, true)
    }
}

/// Place `numticks` evenly spaced ticks across the view interval.
///
/// Port of matplotlib's `LinearLocator` (without the interactive preset cache,
/// which is irrelevant for stateless tick computation).
pub struct LinearLocator {
    numticks: usize,
}

impl LinearLocator {
    /// Create a locator with the given number of ticks.
    pub fn new(numticks: usize) -> Self {
        LinearLocator { numticks }
    }

    /// Return the configured number of ticks.
    #[must_use]
    pub fn numticks(&self) -> usize {
        self.numticks
    }
}

impl Default for LinearLocator {
    /// matplotlib's default of 11 ticks.
    fn default() -> Self {
        LinearLocator { numticks: 11 }
    }
}

impl Locator for LinearLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        let (vmin, vmax) = nonsingular(vmin, vmax, 0.05, 1e-15, true);
        if self.numticks == 0 {
            return Vec::new();
        }
        if self.numticks == 1 {
            return vec![vmin];
        }
        let n = self.numticks - 1;
        // np.linspace: endpoints are exact; interior points are vmin + i*step.
        let step = (vmax - vmin) / n as f64;
        let mut out: Vec<f64> = (0..self.numticks).map(|i| vmin + i as f64 * step).collect();
        // Match numpy: force the final endpoint exactly.
        *out.last_mut().unwrap() = vmax;
        out
    }
}

/// Place ticks at a fixed set of positions, optionally subsampled to `nbins+1`.
///
/// Port of matplotlib's `FixedLocator`.
#[derive(Default)]
pub struct FixedLocator {
    locs: Vec<f64>,
    nbins: Option<usize>,
}

impl FixedLocator {
    /// Create a locator at exactly the given positions (no subsampling).
    pub fn new(locs: Vec<f64>) -> Self {
        FixedLocator { locs, nbins: None }
    }

    /// Create a locator from values that can be collected into fixed
    /// locations.
    pub fn from_locations<I>(locations: I) -> Self
    where
        I: IntoIterator<Item = f64>,
    {
        FixedLocator {
            locs: locations.into_iter().collect(),
            nbins: None,
        }
    }

    /// Create a locator that subsamples `locs` to at most `nbins + 1` ticks.
    ///
    /// `nbins` is clamped to a minimum of 2, as in matplotlib.
    pub fn with_nbins(locs: Vec<f64>, nbins: usize) -> Self {
        FixedLocator {
            locs,
            nbins: Some(nbins.max(2)),
        }
    }

    /// Return the fixed tick locations before optional subsampling.
    #[must_use]
    pub fn locations(&self) -> &[f64] {
        &self.locs
    }

    /// Return the optional maximum bin count used for subsampling.
    ///
    /// When present, this is the clamped matplotlib-style `nbins` value; the
    /// locator emits at most `nbins + 1` ticks.
    #[must_use]
    pub fn nbins(&self) -> Option<usize> {
        self.nbins
    }
}

impl Locator for FixedLocator {
    fn tick_values(&self, _vmin: f64, _vmax: f64) -> Vec<f64> {
        let nbins = match self.nbins {
            None => return self.locs.clone(),
            Some(n) => n,
        };
        let len = self.locs.len();
        if len == 0 {
            return Vec::new();
        }
        // step = max(ceil(len / nbins), 1)
        let step = ((len as f64 / nbins as f64).ceil() as usize).max(1);

        // Candidate sub-sequence starting at offset 0.
        let subsample = |start: usize| -> Vec<f64> {
            self.locs[start..].iter().step_by(step).copied().collect()
        };
        let min_abs = |v: &[f64]| v.iter().map(|x| x.abs()).fold(f64::INFINITY, f64::min);

        let mut ticks = subsample(0);
        for i in 1..step {
            let ticks1 = subsample(i);
            if !ticks1.is_empty() && min_abs(&ticks1) < min_abs(&ticks) {
                ticks = ticks1;
            }
        }
        ticks
    }
}

/// Place ticks on a logarithmic axis.
///
/// Major ticks are powers of `base`. Minor ticks can be requested by setting
/// `subs` to multiples within each decade, for example `[2, 3, ..., 9]` for
/// the usual base-10 minor ticks. The default locator produces major ticks
/// only; [`LogLocator::minor`] constructs the common minor-tick locator.
#[derive(Clone, Debug, PartialEq)]
pub struct LogLocator {
    base: f64,
    subs: Vec<f64>,
}

impl LogLocator {
    /// Construct a major-tick log locator with the given base.
    ///
    /// `base` must be finite and greater than one.
    pub fn new(base: f64) -> Self {
        Self::with_subs(base, vec![1.0])
    }

    /// Construct a log locator with explicit subtick multiples.
    ///
    /// Values in `subs` are retained only when finite and in `[1, base)`;
    /// duplicates are removed after sorting. Use `[1.0]` for major ticks.
    pub fn with_subs(base: f64, subs: Vec<f64>) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "log locator base must be finite and > 1"
        );
        let mut subs: Vec<f64> = subs
            .into_iter()
            .filter(|s| s.is_finite() && *s >= 1.0 && *s < base)
            .collect();
        subs.sort_by(|a, b| a.partial_cmp(b).expect("finite subs are comparable"));
        subs.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
        if subs.is_empty() {
            subs.push(1.0);
        }
        LogLocator { base, subs }
    }

    /// Construct the common minor-tick locator.
    ///
    /// For base 10 this yields subticks at `2..=9` times each decade.
    pub fn minor(base: f64) -> Self {
        let upper = base.floor() as i32;
        let subs = if upper > 2 {
            (2..upper).map(f64::from).collect()
        } else {
            Vec::new()
        };
        Self::with_subs(base, subs)
    }

    /// Return this locator's base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return this locator's decade multiples.
    #[must_use]
    pub fn subs(&self) -> &[f64] {
        &self.subs
    }
}

impl Default for LogLocator {
    /// Default base-10 major locator.
    fn default() -> Self {
        Self::new(10.0)
    }
}

impl Locator for LogLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() || vmin <= 0.0 || vmax <= 0.0 {
            return Vec::new();
        }

        let (lo, hi) = if vmin <= vmax {
            (vmin, vmax)
        } else {
            (vmax, vmin)
        };
        let log_base = self.base.ln();
        let start = (lo.ln() / log_base).floor() as i32;
        let end = (hi.ln() / log_base).ceil() as i32;
        let mut ticks = Vec::new();

        for exponent in start..=end {
            let decade = self.base.powi(exponent);
            for &sub in &self.subs {
                let tick = sub * decade;
                if tick >= lo * (1.0 - 1e-12) && tick <= hi * (1.0 + 1e-12) {
                    ticks.push(tick);
                }
            }
        }

        ticks.sort_by(|a, b| a.partial_cmp(b).expect("finite ticks are comparable"));
        ticks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0));
        if vmin > vmax {
            ticks.reverse();
        }
        ticks
    }

    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        if !vmin.is_finite() || !vmax.is_finite() || vmin <= 0.0 || vmax <= 0.0 {
            return (1.0, self.base);
        }
        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let log_base = self.base.ln();
        let lower = self.base.powi((lo.ln() / log_base).floor() as i32);
        let upper = self.base.powi((hi.ln() / log_base).ceil() as i32);
        if reversed {
            (upper, lower)
        } else {
            (lower, upper)
        }
    }
}

/// Place ticks on a symmetric-log axis.
///
/// Ticks are generated in three bands: negative logarithmic tail, a linear
/// region spanning `[-linthresh, linthresh]`, and positive logarithmic tail.
/// This mirrors the structure of matplotlib's symlog scale while remaining
/// independent of any concrete axis wiring.
#[derive(Clone, Debug, PartialEq)]
pub struct SymlogLocator {
    base: f64,
    linthresh: f64,
    linear_ticks: usize,
}

impl SymlogLocator {
    /// Construct a symlog locator.
    ///
    /// `base` must be finite and greater than one; `linthresh` must be finite
    /// and positive. The linear region defaults to ticks at
    /// `-linthresh`, `0`, and `linthresh`.
    pub fn new(base: f64, linthresh: f64) -> Self {
        Self::with_linear_ticks(base, linthresh, 3)
    }

    /// Construct a symlog locator with explicit linear-region tick count.
    ///
    /// `linear_ticks` is clamped to at least 2 so both edges of the linear
    /// region can be represented when visible.
    pub fn with_linear_ticks(base: f64, linthresh: f64, linear_ticks: usize) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "symlog locator base must be finite and > 1"
        );
        assert!(
            linthresh.is_finite() && linthresh > 0.0,
            "symlog locator linthresh must be finite and > 0"
        );
        SymlogLocator {
            base,
            linthresh,
            linear_ticks: linear_ticks.max(2),
        }
    }

    /// Return this locator's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return this locator's half-width of the linear region around zero.
    #[must_use]
    pub fn linthresh(&self) -> f64 {
        self.linthresh
    }

    /// Return the configured tick count inside the linear region.
    #[must_use]
    pub fn linear_ticks(&self) -> usize {
        self.linear_ticks
    }
}

impl Default for SymlogLocator {
    /// Default base-10 locator with `linthresh = 1`.
    fn default() -> Self {
        Self::new(10.0, 1.0)
    }
}

impl Locator for SymlogLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() {
            return Vec::new();
        }

        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let mut ticks = Vec::new();

        if lo < -self.linthresh {
            let max_abs = (-lo).max(self.linthresh);
            let max_exp = (max_abs / self.linthresh).log(self.base).ceil() as i32;
            for exponent in (1..=max_exp).rev() {
                let tick = -self.linthresh * self.base.powi(exponent);
                if tick >= lo * (1.0 + 1e-12) && tick <= hi * (1.0 - 1e-12) {
                    ticks.push(tick);
                }
            }
        }

        let linear_lo = lo.max(-self.linthresh);
        let linear_hi = hi.min(self.linthresh);
        if linear_lo <= linear_hi {
            let step = 2.0 * self.linthresh / (self.linear_ticks - 1) as f64;
            for i in 0..self.linear_ticks {
                let tick = -self.linthresh + i as f64 * step;
                if tick >= linear_lo - 1e-12 && tick <= linear_hi + 1e-12 {
                    ticks.push(if tick.abs() < 1e-12 { 0.0 } else { tick });
                }
            }
        }

        if hi > self.linthresh {
            let max_exp = (hi / self.linthresh).log(self.base).ceil() as i32;
            for exponent in 1..=max_exp {
                let tick = self.linthresh * self.base.powi(exponent);
                if tick >= lo * (1.0 - 1e-12) && tick <= hi * (1.0 + 1e-12) {
                    ticks.push(tick);
                }
            }
        }

        ticks.sort_by(|a, b| a.partial_cmp(b).expect("finite ticks are comparable"));
        ticks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0));
        if reversed {
            ticks.reverse();
        }
        ticks
    }

    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        let (lo, hi) = nonsingular(vmin, vmax, self.linthresh, 1e-13, true);
        let ticks = self.tick_values(lo, hi);
        match (ticks.first(), ticks.last()) {
            (Some(first), Some(last)) => {
                if vmin <= vmax {
                    (*first, *last)
                } else {
                    (*last, *first)
                }
            }
            _ => {
                if vmin <= vmax {
                    (-self.linthresh, self.linthresh)
                } else {
                    (self.linthresh, -self.linthresh)
                }
            }
        }
    }
}

/// Place ticks on an inverse-hyperbolic-sine axis.
///
/// The locator mirrors the qualitative shape of [`crate::axis::scale::AsinhScale`]:
/// a linear region around zero and logarithmic ticks in both tails. It is a
/// primitive locator only; concrete Axes integration can decide how to pair it
/// with a formatter and scale state later.
#[derive(Clone, Debug, PartialEq)]
pub struct AsinhLocator {
    base: f64,
    linear_width: f64,
    linear_ticks: usize,
}

impl AsinhLocator {
    /// Construct an asinh locator with base-10 tails and ticks at
    /// `-linear_width`, `0`, and `linear_width` in the center.
    ///
    /// `linear_width` must be finite and positive.
    pub fn new(linear_width: f64) -> Self {
        Self::with_linear_ticks(10.0, linear_width, 3)
    }

    /// Construct an asinh locator with explicit base and center tick count.
    ///
    /// `base` must be finite and greater than one; `linear_width` must be
    /// finite and positive. `linear_ticks` is clamped to at least two.
    pub fn with_linear_ticks(base: f64, linear_width: f64, linear_ticks: usize) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "asinh locator base must be finite and > 1"
        );
        assert!(
            linear_width.is_finite() && linear_width > 0.0,
            "asinh locator linear_width must be finite and > 0"
        );
        AsinhLocator {
            base,
            linear_width,
            linear_ticks: linear_ticks.max(2),
        }
    }

    /// Return this locator's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return the width of the quasi-linear region around zero.
    #[must_use]
    pub fn linear_width(&self) -> f64 {
        self.linear_width
    }

    /// Return the configured tick count inside the quasi-linear region.
    #[must_use]
    pub fn linear_ticks(&self) -> usize {
        self.linear_ticks
    }
}

impl Default for AsinhLocator {
    /// Default base-10 locator with a unit-width linear region.
    fn default() -> Self {
        Self::new(1.0)
    }
}

impl Locator for AsinhLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() {
            return Vec::new();
        }

        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let mut ticks = Vec::new();

        if lo < -self.linear_width {
            let max_abs = (-lo).max(self.linear_width);
            let max_exp = (max_abs / self.linear_width).log(self.base).ceil() as i32;
            for exponent in (1..=max_exp).rev() {
                let tick = -self.linear_width * self.base.powi(exponent);
                if tick >= lo * (1.0 + 1e-12) && tick <= hi * (1.0 - 1e-12) {
                    ticks.push(tick);
                }
            }
        }

        let linear_lo = lo.max(-self.linear_width);
        let linear_hi = hi.min(self.linear_width);
        if linear_lo <= linear_hi {
            let step = 2.0 * self.linear_width / (self.linear_ticks - 1) as f64;
            for i in 0..self.linear_ticks {
                let tick = -self.linear_width + i as f64 * step;
                if tick >= linear_lo - 1e-12 && tick <= linear_hi + 1e-12 {
                    ticks.push(if tick.abs() < 1e-12 { 0.0 } else { tick });
                }
            }
        }

        if hi > self.linear_width {
            let max_exp = (hi / self.linear_width).log(self.base).ceil() as i32;
            for exponent in 1..=max_exp {
                let tick = self.linear_width * self.base.powi(exponent);
                if tick >= lo * (1.0 - 1e-12) && tick <= hi * (1.0 + 1e-12) {
                    ticks.push(tick);
                }
            }
        }

        ticks.sort_by(|a, b| a.partial_cmp(b).expect("finite ticks are comparable"));
        ticks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0));
        if reversed {
            ticks.reverse();
        }
        ticks
    }

    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        let (lo, hi) = nonsingular(vmin, vmax, self.linear_width, 1e-13, true);
        let lower = if lo < -self.linear_width {
            -self.linear_width
                * self
                    .base
                    .powi(((-lo) / self.linear_width).log(self.base).ceil() as i32)
        } else {
            -self.linear_width
        };
        let upper = if hi > self.linear_width {
            self.linear_width
                * self
                    .base
                    .powi((hi / self.linear_width).log(self.base).ceil() as i32)
        } else {
            self.linear_width
        };
        if vmin <= vmax {
            (lower, upper)
        } else {
            (upper, lower)
        }
    }
}

/// Place ticks on a logit/probability axis.
///
/// Major ticks are powers of ten approaching zero, mirrored powers approaching
/// one, plus `0.5` when it lies in the view range. This covers the common
/// probability-axis labels without depending on any concrete Axes integration.
#[derive(Clone, Debug, PartialEq)]
pub struct LogitLocator {
    max_exponent: i32,
}

impl LogitLocator {
    /// Construct a logit locator with powers through `1e-6`.
    pub fn new() -> Self {
        Self::with_max_exponent(6)
    }

    /// Construct a logit locator with powers through `10^-max_exponent`.
    ///
    /// `max_exponent` is clamped to at least 1.
    pub fn with_max_exponent(max_exponent: i32) -> Self {
        LogitLocator {
            max_exponent: max_exponent.max(1),
        }
    }

    /// Return the largest generated power exponent.
    #[must_use]
    pub fn max_exponent(&self) -> i32 {
        self.max_exponent
    }
}

impl Default for LogitLocator {
    fn default() -> Self {
        Self::new()
    }
}

impl Locator for LogitLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() || vmin <= 0.0 || vmax >= 1.0 {
            return Vec::new();
        }

        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let mut ticks = Vec::new();

        for exponent in (1..=self.max_exponent).rev() {
            let p = 10f64.powi(-exponent);
            if p >= lo * (1.0 - 1e-12) && p <= hi * (1.0 + 1e-12) {
                ticks.push(p);
            }
        }
        if 0.5 >= lo && 0.5 <= hi {
            ticks.push(0.5);
        }
        for exponent in 1..=self.max_exponent {
            let p = 1.0 - 10f64.powi(-exponent);
            if p >= lo * (1.0 - 1e-12) && p <= hi * (1.0 + 1e-12) {
                ticks.push(p);
            }
        }

        ticks.sort_by(|a, b| a.partial_cmp(b).expect("finite ticks are comparable"));
        ticks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12);
        if reversed {
            ticks.reverse();
        }
        ticks
    }

    fn view_limits(&self, vmin: f64, vmax: f64) -> (f64, f64) {
        let lower = 10f64.powi(-self.max_exponent);
        let upper = 1.0 - lower;
        if !vmin.is_finite() || !vmax.is_finite() {
            return (lower, upper);
        }
        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let lo = lo.clamp(lower, upper);
        let hi = hi.clamp(lower, upper);
        if reversed { (hi, lo) } else { (lo, hi) }
    }
}

/// Place ticks on regularly spaced index positions.
///
/// Port of matplotlib's `IndexLocator`. Ticks are placed at values `offset + n *
/// base` that fall within the view interval. This is useful for plots whose
/// data coordinate is the sample index.
pub struct IndexLocator {
    base: f64,
    offset: f64,
}

impl IndexLocator {
    /// Create an index locator with positive `base` spacing and additive
    /// `offset`.
    ///
    /// Non-positive or non-finite bases are coerced to `1.0`, and non-finite
    /// offsets are coerced to `0.0`, matching the crate's no-panic locator
    /// convention.
    pub fn new(base: f64, offset: f64) -> Self {
        IndexLocator {
            base: if base.is_finite() && base > 0.0 {
                base
            } else {
                1.0
            },
            offset: if offset.is_finite() { offset } else { 0.0 },
        }
    }

    /// Return the configured index spacing.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return the configured additive index offset.
    #[must_use]
    pub fn offset(&self) -> f64 {
        self.offset
    }
}

impl Locator for IndexLocator {
    fn tick_values(&self, vmin: f64, vmax: f64) -> Vec<f64> {
        if !vmin.is_finite() || !vmax.is_finite() {
            return Vec::new();
        }

        let (lo, hi, reversed) = if vmin <= vmax {
            (vmin, vmax, false)
        } else {
            (vmax, vmin, true)
        };
        let first = ((lo - self.offset) / self.base).ceil();
        let last = ((hi - self.offset) / self.base).floor();
        if last < first {
            return Vec::new();
        }

        let count = (last - first) as usize + 1;
        let mut ticks: Vec<f64> = (0..count)
            .map(|i| self.offset + (first + i as f64) * self.base)
            .collect();
        if reversed {
            ticks.reverse();
        }
        ticks
    }

    fn view_limits(&self, dmin: f64, dmax: f64) -> (f64, f64) {
        nonsingular(dmin, dmax, 0.001, 1e-15, true)
    }
}

/// Place no ticks at all.
///
/// Port of matplotlib's `NullLocator`.
#[derive(Default)]
pub struct NullLocator;

impl Locator for NullLocator {
    fn tick_values(&self, _vmin: f64, _vmax: f64) -> Vec<f64> {
        Vec::new()
    }
}

/// Format tick values as plain decimal numbers.
///
/// A reasonable subset of matplotlib's `ScalarFormatter`: the number of
/// significant figures (decimal places) is chosen from the tick spacing via the
/// same algorithm as `ScalarFormatter._set_format`. To do so the formatter must
/// be told the tick locations up front via [`ScalarFormatter::set_locs`].
///
/// # Omissions
///
/// Offset notation and scientific notation are intentionally **not** implemented
/// (`useOffset`/`useMathText` in matplotlib): the order of magnitude is fixed at
/// zero and there is no offset string. Locale handling and Unicode-minus are
/// likewise out of scope.
pub struct ScalarFormatter {
    /// Number of decimal places, `%.{decimals}f`.
    decimals: usize,
    /// Whether [`set_locs`](ScalarFormatter::set_locs) has been called.
    have_format: bool,
}

impl ScalarFormatter {
    /// Create a formatter with a default of one decimal place.
    ///
    /// Call [`set_locs`](ScalarFormatter::set_locs) with the tick vector to pick
    /// the precision from the spacing, as matplotlib does in `set_locs`.
    pub fn new() -> Self {
        ScalarFormatter {
            decimals: 1,
            have_format: false,
        }
    }

    /// Construct a formatter with a fixed number of decimal places.
    ///
    /// Calling [`set_locs`](ScalarFormatter::set_locs) later may still replace
    /// this precision with spacing-derived precision.
    pub fn with_decimals(decimals: usize) -> Self {
        ScalarFormatter {
            decimals,
            have_format: false,
        }
    }

    /// Choose the number of decimal places from the tick locations.
    ///
    /// Port of `ScalarFormatter._set_format` with `offset = 0` and
    /// `orderOfMagnitude = 0` (no offset/sci-notation in this subset). With
    /// fewer than two locations the precision falls back to the default.
    pub fn set_locs(&mut self, locs: &[f64]) {
        self.have_format = true;
        if locs.len() < 2 {
            // matplotlib augments with the axis view interval here; without an
            // axis we keep the default precision.
            return;
        }
        let max = locs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let min = locs.iter().cloned().fold(f64::INFINITY, f64::min);
        let mut loc_range = max - min;
        if loc_range == 0.0 {
            loc_range = locs.iter().map(|x| x.abs()).fold(0.0, f64::max);
        }
        if loc_range == 0.0 {
            loc_range = 1.0;
        }
        let loc_range_oom = loc_range.log10().floor() as i32;
        // First estimate.
        let mut sigfigs = (3 - loc_range_oom).max(0);
        // Refined estimate: drop trailing zero digits.
        let thresh = 1e-3 * 10f64.powi(loc_range_oom);
        while sigfigs >= 0 {
            let factor = 10f64.powi(sigfigs);
            let maxdev = locs
                .iter()
                .map(|&x| (x - (x * factor).round() / factor).abs())
                .fold(0.0, f64::max);
            if maxdev < thresh {
                sigfigs -= 1;
            } else {
                break;
            }
        }
        sigfigs += 1;
        self.decimals = sigfigs.max(0) as usize;
    }

    /// Return the current number of decimal places.
    #[must_use]
    pub fn decimals(&self) -> usize {
        self.decimals
    }

    /// Return whether [`set_locs`](ScalarFormatter::set_locs) has selected a
    /// format for this instance.
    #[must_use]
    pub fn has_format(&self) -> bool {
        self.have_format
    }
}

impl Default for ScalarFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for ScalarFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        // Matplotlib rounds tiny values to exactly zero before formatting.
        let v = if value.abs() < 1e-8 { 0.0 } else { value };
        format!("{:.*}", self.decimals, v)
    }
}

/// Format logarithmic major tick values.
///
/// Exact powers of `base` are labelled. Non-decade values (typically minor
/// ticks) produce an empty label by default, matching matplotlib's default
/// minor tick behaviour.
#[derive(Clone, Debug, PartialEq)]
pub struct LogFormatter {
    base: f64,
}

impl LogFormatter {
    /// Construct a formatter for the given base.
    ///
    /// `base` must be finite and greater than one.
    pub fn new(base: f64) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "log formatter base must be finite and > 1"
        );
        LogFormatter { base }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    fn exponent(&self, value: f64) -> Option<i32> {
        if !value.is_finite() || value <= 0.0 {
            return None;
        }
        let exponent = (value.ln() / self.base.ln()).round();
        let decade = self.base.powf(exponent);
        let rel = ((value - decade) / decade).abs();
        if rel <= 1e-10 {
            Some(exponent as i32)
        } else {
            None
        }
    }

    fn format_exponent(&self, exponent: i32, mathtext: bool) -> String {
        let plain_label = (self.base == 10.0 && (-3..=4).contains(&exponent))
            || (self.base == 2.0 && (-3..=6).contains(&exponent));
        let value = self.base.powi(exponent);
        if plain_label {
            format_decimal(value)
        } else {
            let label = format!("{}^{{{}}}", format_decimal(self.base), exponent);
            if mathtext {
                format!("${label}$")
            } else {
                label
            }
        }
    }
}

impl Default for LogFormatter {
    /// Default base-10 log formatter.
    fn default() -> Self {
        Self::new(10.0)
    }
}

impl Formatter for LogFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        let Some(exponent) = self.exponent(value) else {
            return String::new();
        };

        self.format_exponent(exponent, false)
    }
}

/// Format logarithmic major ticks with mathtext for exponent labels.
///
/// This formatter preserves [`LogFormatter`]'s compact decimal labels for
/// nearby powers, hides non-decade minor ticks, and wraps large exponent labels
/// in `$...$` so higher-level rich-text rendering can draw real superscripts.
#[derive(Clone, Debug, PartialEq)]
pub struct LogFormatterMathtext {
    inner: LogFormatter,
}

impl LogFormatterMathtext {
    /// Construct a mathtext log formatter for the given base.
    ///
    /// `base` must be finite and greater than one.
    pub fn new(base: f64) -> Self {
        Self {
            inner: LogFormatter::new(base),
        }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.inner.base()
    }
}

impl Default for LogFormatterMathtext {
    /// Default base-10 mathtext log formatter.
    fn default() -> Self {
        Self::new(10.0)
    }
}

impl Formatter for LogFormatterMathtext {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        let Some(exponent) = self.inner.exponent(value) else {
            return String::new();
        };

        self.inner.format_exponent(exponent, true)
    }
}

/// Format symmetric-log tick values.
///
/// Values in the linear region are formatted as plain decimals. Exact
/// logarithmic tail ticks are labelled as signed powers of `base` when
/// `linthresh == 1`; for other thresholds they fall back to decimal labels.
/// Off-lattice values return an empty label, which is suitable for minor ticks.
#[derive(Clone, Debug, PartialEq)]
pub struct SymlogFormatter {
    base: f64,
    linthresh: f64,
}

impl SymlogFormatter {
    /// Construct a symlog formatter.
    ///
    /// `base` must be finite and greater than one; `linthresh` must be finite
    /// and positive.
    pub fn new(base: f64, linthresh: f64) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "symlog formatter base must be finite and > 1"
        );
        assert!(
            linthresh.is_finite() && linthresh > 0.0,
            "symlog formatter linthresh must be finite and > 0"
        );
        SymlogFormatter { base, linthresh }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return this formatter's half-width of the linear region around zero.
    #[must_use]
    pub fn linthresh(&self) -> f64 {
        self.linthresh
    }

    fn tail_exponent(&self, value: f64) -> Option<i32> {
        if !value.is_finite() || value.abs() <= self.linthresh {
            return None;
        }
        let abs = value.abs();
        let exponent = (abs / self.linthresh).log(self.base).round();
        let tick = self.linthresh * self.base.powf(exponent);
        let rel = ((abs - tick) / tick).abs();
        if rel <= 1e-10 {
            Some(exponent as i32)
        } else {
            None
        }
    }
}

impl Default for SymlogFormatter {
    /// Default base-10 formatter with `linthresh = 1`.
    fn default() -> Self {
        Self::new(10.0, 1.0)
    }
}

impl Formatter for SymlogFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if value.abs() <= self.linthresh * (1.0 + 1e-12) {
            return format_decimal(if value.abs() < 1e-12 { 0.0 } else { value });
        }

        let Some(exponent) = self.tail_exponent(value) else {
            return String::new();
        };
        if (self.linthresh - 1.0).abs() > 1e-12 {
            return format_decimal(value);
        }

        let sign = if value.is_sign_negative() { "-" } else { "" };
        let label = LogFormatter::new(self.base).format_exponent(exponent, false);
        format!("{sign}{label}")
    }
}

/// Format symmetric-log tick values with mathtext for exponent labels.
///
/// This formatter preserves [`SymlogFormatter`]'s decimal labels in the linear
/// region and near logarithmic tails, hides off-lattice tail ticks, and wraps
/// large signed power labels in `$...$` so rich-text rendering can draw real
/// superscripts.
#[derive(Clone, Debug, PartialEq)]
pub struct SymlogFormatterMathtext {
    inner: SymlogFormatter,
}

impl SymlogFormatterMathtext {
    /// Construct a mathtext symlog formatter.
    ///
    /// `base` must be finite and greater than one; `linthresh` must be finite
    /// and positive.
    pub fn new(base: f64, linthresh: f64) -> Self {
        Self {
            inner: SymlogFormatter::new(base, linthresh),
        }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.inner.base()
    }

    /// Return this formatter's half-width of the linear region around zero.
    #[must_use]
    pub fn linthresh(&self) -> f64 {
        self.inner.linthresh()
    }
}

impl Default for SymlogFormatterMathtext {
    /// Default base-10 formatter with `linthresh = 1`.
    fn default() -> Self {
        Self::new(10.0, 1.0)
    }
}

impl Formatter for SymlogFormatterMathtext {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if value.abs() <= self.inner.linthresh * (1.0 + 1e-12) {
            return format_decimal(if value.abs() < 1e-12 { 0.0 } else { value });
        }

        let Some(exponent) = self.inner.tail_exponent(value) else {
            return String::new();
        };
        if (self.inner.linthresh - 1.0).abs() > 1e-12 {
            return format_decimal(value);
        }

        let label = LogFormatter::new(self.inner.base).format_exponent(exponent, true);
        if value.is_sign_negative() && label.starts_with('$') && label.ends_with('$') {
            format!("$-{}$", &label[1..label.len() - 1])
        } else if value.is_sign_negative() {
            format!("-{label}")
        } else {
            label
        }
    }
}

/// Format inverse-hyperbolic-sine tick values.
///
/// Values in the quasi-linear region are formatted as plain decimals. Exact
/// logarithmic tail ticks are labelled as signed powers of `base` when
/// `linear_width == 1`; for other widths they fall back to decimal labels.
/// Off-lattice values return an empty label.
#[derive(Clone, Debug, PartialEq)]
pub struct AsinhFormatter {
    base: f64,
    linear_width: f64,
}

impl AsinhFormatter {
    /// Construct an asinh formatter.
    ///
    /// `base` must be finite and greater than one; `linear_width` must be
    /// finite and positive.
    pub fn new(base: f64, linear_width: f64) -> Self {
        assert!(
            base.is_finite() && base > 1.0,
            "asinh formatter base must be finite and > 1"
        );
        assert!(
            linear_width.is_finite() && linear_width > 0.0,
            "asinh formatter linear_width must be finite and > 0"
        );
        AsinhFormatter { base, linear_width }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.base
    }

    /// Return this formatter's quasi-linear region width around zero.
    #[must_use]
    pub fn linear_width(&self) -> f64 {
        self.linear_width
    }

    fn tail_exponent(&self, value: f64) -> Option<i32> {
        if !value.is_finite() || value.abs() <= self.linear_width {
            return None;
        }
        let abs = value.abs();
        let exponent = (abs / self.linear_width).log(self.base).round();
        let tick = self.linear_width * self.base.powf(exponent);
        let rel = ((abs - tick) / tick).abs();
        if rel <= 1e-10 {
            Some(exponent as i32)
        } else {
            None
        }
    }
}

impl Default for AsinhFormatter {
    /// Default base-10 formatter with `linear_width = 1`.
    fn default() -> Self {
        Self::new(10.0, 1.0)
    }
}

impl Formatter for AsinhFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if value.abs() <= self.linear_width * (1.0 + 1e-12) {
            return format_decimal(if value.abs() < 1e-12 { 0.0 } else { value });
        }

        let Some(exponent) = self.tail_exponent(value) else {
            return String::new();
        };
        if (self.linear_width - 1.0).abs() > 1e-12 {
            return format_decimal(value);
        }

        let sign = if value.is_sign_negative() { "-" } else { "" };
        let label = LogFormatter::new(self.base).format_exponent(exponent, false);
        format!("{sign}{label}")
    }
}

/// Format inverse-hyperbolic-sine tick values with mathtext for exponent
/// labels.
///
/// This formatter preserves [`AsinhFormatter`]'s decimal labels in the linear
/// region and near logarithmic tails, hides off-lattice tail ticks, and wraps
/// large signed power labels in `$...$` so rich-text rendering can draw real
/// superscripts.
#[derive(Clone, Debug, PartialEq)]
pub struct AsinhFormatterMathtext {
    inner: AsinhFormatter,
}

impl AsinhFormatterMathtext {
    /// Construct a mathtext asinh formatter.
    ///
    /// `base` must be finite and greater than one; `linear_width` must be
    /// finite and positive.
    pub fn new(base: f64, linear_width: f64) -> Self {
        Self {
            inner: AsinhFormatter::new(base, linear_width),
        }
    }

    /// Return this formatter's logarithm base.
    #[must_use]
    pub fn base(&self) -> f64 {
        self.inner.base()
    }

    /// Return this formatter's quasi-linear region width around zero.
    #[must_use]
    pub fn linear_width(&self) -> f64 {
        self.inner.linear_width()
    }
}

impl Default for AsinhFormatterMathtext {
    /// Default base-10 formatter with `linear_width = 1`.
    fn default() -> Self {
        Self::new(10.0, 1.0)
    }
}

impl Formatter for AsinhFormatterMathtext {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if value.abs() <= self.inner.linear_width * (1.0 + 1e-12) {
            return format_decimal(if value.abs() < 1e-12 { 0.0 } else { value });
        }

        let Some(exponent) = self.inner.tail_exponent(value) else {
            return String::new();
        };
        if (self.inner.linear_width - 1.0).abs() > 1e-12 {
            return format_decimal(value);
        }

        let label = LogFormatter::new(self.inner.base).format_exponent(exponent, true);
        if value.is_sign_negative() && label.starts_with('$') && label.ends_with('$') {
            format!("$-{}$", &label[1..label.len() - 1])
        } else if value.is_sign_negative() {
            format!("-{label}")
        } else {
            label
        }
    }
}

/// Format logit/probability tick values.
///
/// Exact powers of ten near zero are labelled as decimals for `0.1` and as
/// `10^{-n}` for smaller probabilities. Mirrored ticks near one are labelled
/// as decimals for `0.9` and `1-10^{-n}` closer to one. Off-lattice values
/// return an empty label.
#[derive(Clone, Debug, PartialEq)]
pub struct LogitFormatter {
    max_exponent: i32,
}

impl LogitFormatter {
    /// Construct a logit formatter with powers through `1e-6`.
    pub fn new() -> Self {
        Self::with_max_exponent(6)
    }

    /// Construct a logit formatter with powers through `10^-max_exponent`.
    ///
    /// `max_exponent` is clamped to at least 1.
    pub fn with_max_exponent(max_exponent: i32) -> Self {
        LogitFormatter {
            max_exponent: max_exponent.max(1),
        }
    }

    /// Return the largest generated tail-label exponent.
    #[must_use]
    pub fn max_exponent(&self) -> i32 {
        self.max_exponent
    }

    fn lower_exponent(&self, value: f64) -> Option<i32> {
        if !value.is_finite() || value <= 0.0 || value >= 0.5 {
            return None;
        }
        let exponent = -value.log10().round() as i32;
        if exponent < 1 || exponent > self.max_exponent {
            return None;
        }
        let tick = 10f64.powi(-exponent);
        if ((value - tick) / tick).abs() <= 1e-10 {
            Some(exponent)
        } else {
            None
        }
    }

    fn upper_exponent(&self, value: f64) -> Option<i32> {
        if !value.is_finite() || value <= 0.5 || value >= 1.0 {
            return None;
        }
        let q = 1.0 - value;
        let exponent = -q.log10().round() as i32;
        if exponent < 1 || exponent > self.max_exponent {
            return None;
        }
        let tick = 10f64.powi(-exponent);
        if ((q - tick) / tick).abs() <= 1e-10 {
            Some(exponent)
        } else {
            None
        }
    }
}

impl Default for LogitFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for LogitFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if (value - 0.5).abs() <= 1e-12 {
            return "1/2".to_owned();
        }
        if let Some(exponent) = self.lower_exponent(value) {
            return if exponent == 1 {
                "0.1".to_owned()
            } else {
                format!("10^{{-{exponent}}}")
            };
        }
        if let Some(exponent) = self.upper_exponent(value) {
            return if exponent == 1 {
                "0.9".to_owned()
            } else {
                format!("1-10^{{-{exponent}}}")
            };
        }
        String::new()
    }
}

/// Format logit/probability tick values with mathtext tail labels.
///
/// This preserves [`LogitFormatter`]'s compact decimal labels for `0.1`,
/// `0.5`, and `0.9`, while wrapping smaller lower-tail labels and mirrored
/// upper-tail labels in `$...$` so rich-text rendering can draw superscripts.
#[derive(Clone, Debug, PartialEq)]
pub struct LogitFormatterMathtext {
    inner: LogitFormatter,
}

impl LogitFormatterMathtext {
    /// Construct a logit mathtext formatter with powers through `1e-6`.
    pub fn new() -> Self {
        Self::with_max_exponent(6)
    }

    /// Construct a logit mathtext formatter with powers through
    /// `10^-max_exponent`.
    ///
    /// `max_exponent` is clamped to at least 1.
    pub fn with_max_exponent(max_exponent: i32) -> Self {
        Self {
            inner: LogitFormatter::with_max_exponent(max_exponent),
        }
    }

    /// Return the largest generated tail-label exponent.
    #[must_use]
    pub fn max_exponent(&self) -> i32 {
        self.inner.max_exponent()
    }
}

impl Default for LogitFormatterMathtext {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for LogitFormatterMathtext {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if (value - 0.5).abs() <= 1e-12 {
            return "1/2".to_owned();
        }
        if let Some(exponent) = self.inner.lower_exponent(value) {
            return if exponent == 1 {
                "0.1".to_owned()
            } else {
                format!("$10^{{-{exponent}}}$")
            };
        }
        if let Some(exponent) = self.inner.upper_exponent(value) {
            return if exponent == 1 {
                "0.9".to_owned()
            } else {
                format!("$1-10^{{-{exponent}}}$")
            };
        }
        String::new()
    }
}

/// Format values in engineering notation with SI prefixes.
///
/// Exponents are multiples of three, clamped to the standard SI prefix range
/// from yocto (`y`) through yotta (`Y`). The micro prefix is rendered as ASCII
/// `u` to keep labels backend- and font-safe.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EngFormatter {
    unit: String,
    places: Option<usize>,
    separator: String,
}

impl EngFormatter {
    /// Construct an engineering formatter with no unit suffix.
    pub fn new() -> Self {
        Self {
            unit: String::new(),
            places: None,
            separator: String::new(),
        }
    }

    /// Return a copy with a unit suffix, such as `"Hz"` or `"V"`.
    #[must_use]
    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = unit.into();
        self
    }

    /// Return a copy with a fixed number of decimal places.
    #[must_use]
    pub fn with_places(mut self, places: usize) -> Self {
        self.places = Some(places);
        self
    }

    /// Return a copy with a separator between the number and prefix/unit.
    #[must_use]
    pub fn with_separator(mut self, separator: impl Into<String>) -> Self {
        self.separator = separator.into();
        self
    }

    /// Return the configured unit suffix.
    #[must_use]
    pub fn unit(&self) -> &str {
        &self.unit
    }

    /// Return the fixed decimal-place count, if configured.
    #[must_use]
    pub fn places(&self) -> Option<usize> {
        self.places
    }

    /// Return the configured separator between number and prefix/unit.
    #[must_use]
    pub fn separator(&self) -> &str {
        &self.separator
    }

    fn prefix(exponent: i32) -> &'static str {
        match exponent {
            -24 => "y",
            -21 => "z",
            -18 => "a",
            -15 => "f",
            -12 => "p",
            -9 => "n",
            -6 => "u",
            -3 => "m",
            0 => "",
            3 => "k",
            6 => "M",
            9 => "G",
            12 => "T",
            15 => "P",
            18 => "E",
            21 => "Z",
            24 => "Y",
            _ => "",
        }
    }
}

impl Default for EngFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for EngFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        if value == 0.0 {
            let suffix = format!("{}{}", Self::prefix(0), self.unit);
            return if suffix.is_empty() {
                "0".to_owned()
            } else {
                format!("0{}{}", self.separator, suffix)
            };
        }

        let exponent = ((value.abs().log10().floor() as i32).div_euclid(3) * 3).clamp(-24, 24);
        let scaled = value / 10f64.powi(exponent);
        let number = if let Some(places) = self.places {
            format!("{scaled:.places$}")
        } else {
            format_decimal(scaled)
        };
        let suffix = format!("{}{}", Self::prefix(exponent), self.unit);
        if suffix.is_empty() {
            number
        } else {
            format!("{number}{}{}", self.separator, suffix)
        }
    }
}

/// Format values as percentages.
///
/// `xmax` is the data value corresponding to 100 percent, matching
/// matplotlib's `PercentFormatter` convention.
#[derive(Clone, Debug, PartialEq)]
pub struct PercentFormatter {
    xmax: f64,
    decimals: usize,
    symbol: String,
}

impl PercentFormatter {
    /// Construct a formatter where `100.0` maps to `100%`.
    pub fn new() -> Self {
        Self::with_xmax(100.0)
    }

    /// Construct a formatter where `1.0` maps to `100%`.
    ///
    /// This is the common probability/fraction convention, equivalent to
    /// matplotlib's `PercentFormatter(xmax=1.0)`.
    pub fn fraction() -> Self {
        Self::with_xmax(1.0)
    }

    /// Construct a formatter with a custom value for 100 percent.
    ///
    /// `xmax` must be finite and non-zero.
    pub fn with_xmax(xmax: f64) -> Self {
        assert!(
            xmax.is_finite() && xmax != 0.0,
            "percent formatter xmax must be finite and non-zero"
        );
        Self {
            xmax,
            decimals: 0,
            symbol: "%".to_owned(),
        }
    }

    /// Return a copy with a fixed number of decimal places.
    #[must_use]
    pub fn with_decimals(mut self, decimals: usize) -> Self {
        self.decimals = decimals;
        self
    }

    /// Return a copy with a custom percent symbol suffix.
    #[must_use]
    pub fn with_symbol(mut self, symbol: impl Into<String>) -> Self {
        self.symbol = symbol.into();
        self
    }

    /// Return the data value corresponding to 100 percent.
    #[must_use]
    pub fn xmax(&self) -> f64 {
        self.xmax
    }

    /// Return the fixed decimal-place count.
    #[must_use]
    pub fn decimals(&self) -> usize {
        self.decimals
    }

    /// Return the configured percent-symbol suffix.
    #[must_use]
    pub fn symbol(&self) -> &str {
        &self.symbol
    }
}

impl Default for PercentFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for PercentFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        let percent = value / self.xmax * 100.0;
        format!("{:.*}{}", self.decimals, percent, self.symbol)
    }
}

fn format_decimal(value: f64) -> String {
    if (value - value.round()).abs() < 1e-10 {
        format!("{:.0}", value)
    } else {
        let mut text = format!("{value:.12}");
        while text.contains('.') && text.ends_with('0') {
            text.pop();
        }
        if text.ends_with('.') {
            text.pop();
        }
        text
    }
}

/// Always return the empty string.
///
/// Port of matplotlib's `NullFormatter`.
#[derive(Default)]
pub struct NullFormatter;

impl Formatter for NullFormatter {
    fn format(&self, _value: f64, _pos: Option<usize>) -> String {
        String::new()
    }
}

/// Return fixed label strings indexed by tick position.
///
/// Port of matplotlib's `FixedFormatter`. Should be paired with a
/// [`FixedLocator`]. Positions out of range (or `None`) yield the empty string.
#[derive(Default)]
pub struct FixedFormatter {
    seq: Vec<String>,
}

impl FixedFormatter {
    /// Create a formatter from the sequence of label strings.
    pub fn new(seq: Vec<String>) -> Self {
        FixedFormatter { seq }
    }

    /// Create a formatter from labels that can be converted into strings.
    pub fn from_labels<I, S>(labels: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        FixedFormatter {
            seq: labels.into_iter().map(Into::into).collect(),
        }
    }

    /// Return the configured fixed label sequence.
    #[must_use]
    pub fn labels(&self) -> &[String] {
        &self.seq
    }
}

impl Formatter for FixedFormatter {
    fn format(&self, _value: f64, pos: Option<usize>) -> String {
        match pos {
            Some(p) if p < self.seq.len() => self.seq[p].clone(),
            _ => String::new(),
        }
    }
}

/// Return fixed label strings indexed by rounded tick value.
///
/// Port of matplotlib's `IndexFormatter`. A tick value is rounded to the
/// nearest integer and used as an index into the label vector. Non-finite,
/// negative, or out-of-range values yield the empty string.
#[derive(Default)]
pub struct IndexFormatter {
    labels: Vec<String>,
}

impl IndexFormatter {
    /// Create an index formatter from the sequence of label strings.
    pub fn new(labels: Vec<String>) -> Self {
        IndexFormatter { labels }
    }

    /// Create an index formatter from labels that can be converted into
    /// strings.
    pub fn from_labels<I, S>(labels: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        IndexFormatter {
            labels: labels.into_iter().map(Into::into).collect(),
        }
    }

    /// Return the configured index label sequence.
    #[must_use]
    pub fn labels(&self) -> &[String] {
        &self.labels
    }
}

impl Formatter for IndexFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        if !value.is_finite() {
            return String::new();
        }
        let index = value.round();
        if index < 0.0 {
            return String::new();
        }
        let index = index as usize;
        self.labels.get(index).cloned().unwrap_or_default()
    }
}

/// Format ticks with a user-supplied closure.
///
/// Port of matplotlib's `FuncFormatter`. The closure receives the value and the
/// optional position index and returns the label.
pub struct FuncFormatter {
    func: Box<dyn Fn(f64, Option<usize>) -> String + Send + Sync>,
}

impl FuncFormatter {
    /// Create a formatter from a boxed closure.
    pub fn new(func: Box<dyn Fn(f64, Option<usize>) -> String + Send + Sync>) -> Self {
        FuncFormatter { func }
    }

    /// Create a formatter from an unboxed closure or function.
    pub fn from_fn<F>(func: F) -> Self
    where
        F: Fn(f64, Option<usize>) -> String + Send + Sync + 'static,
    {
        Self::new(Box::new(func))
    }
}

impl Formatter for FuncFormatter {
    fn format(&self, value: f64, pos: Option<usize>) -> String {
        (self.func)(value, pos)
    }
}

/// Format ticks with an old-style `%` numeric format string.
///
/// This is a small, deterministic subset of matplotlib's
/// `FormatStrFormatter`: the first numeric conversion in the template receives
/// the tick value, `%%` escapes a literal percent sign, and surrounding text is
/// preserved. Supported conversion types are `d`, `i`, `f`, `e`, `E`, `g`, and
/// `G`, with optional sign, zero-padding, left-alignment, width, and precision.
pub struct FormatStrFormatter {
    fmt: String,
}

impl FormatStrFormatter {
    /// Create a formatter from a `%`-style template.
    pub fn new(fmt: impl Into<String>) -> Self {
        FormatStrFormatter { fmt: fmt.into() }
    }

    /// Return the configured `%`-style template.
    #[must_use]
    pub fn template(&self) -> &str {
        &self.fmt
    }
}

impl Default for FormatStrFormatter {
    /// Create a formatter with matplotlib's default `%g` template.
    fn default() -> Self {
        FormatStrFormatter::new("%g")
    }
}

impl Formatter for FormatStrFormatter {
    fn format(&self, value: f64, _pos: Option<usize>) -> String {
        format_percent_template(&self.fmt, value)
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct PercentSpec {
    left_align: bool,
    sign_plus: bool,
    sign_space: bool,
    zero_pad: bool,
    width: Option<usize>,
    precision: Option<usize>,
    conversion: char,
}

fn format_percent_template(fmt: &str, value: f64) -> String {
    let mut out = String::new();
    let mut chars = fmt.char_indices().peekable();
    let mut formatted_value = false;

    while let Some((_, ch)) = chars.next() {
        if ch != '%' {
            out.push(ch);
            continue;
        }

        if matches!(chars.peek(), Some((_, '%'))) {
            chars.next();
            out.push('%');
            continue;
        }

        if formatted_value {
            out.push('%');
            continue;
        }

        let (spec, raw) = parse_percent_spec(&mut chars);
        if let Some(spec) = spec {
            out.push_str(&format_percent_value(value, spec));
            formatted_value = true;
        } else {
            out.push('%');
            out.push_str(&raw);
        }
    }

    out
}

fn parse_percent_spec<I>(chars: &mut std::iter::Peekable<I>) -> (Option<PercentSpec>, String)
where
    I: Iterator<Item = (usize, char)>,
{
    let mut raw = String::new();
    let mut spec = PercentSpec::default();

    while let Some(&(_, ch)) = chars.peek() {
        match ch {
            '-' => spec.left_align = true,
            '+' => spec.sign_plus = true,
            ' ' => spec.sign_space = true,
            '0' => spec.zero_pad = true,
            '#' => {}
            _ => break,
        }
        raw.push(ch);
        chars.next();
    }

    let mut width = String::new();
    while let Some(&(_, ch)) = chars.peek() {
        if !ch.is_ascii_digit() {
            break;
        }
        width.push(ch);
        raw.push(ch);
        chars.next();
    }
    if !width.is_empty() {
        spec.width = width.parse().ok();
    }

    if matches!(chars.peek(), Some((_, '.'))) {
        raw.push('.');
        chars.next();
        let mut precision = String::new();
        while let Some(&(_, ch)) = chars.peek() {
            if !ch.is_ascii_digit() {
                break;
            }
            precision.push(ch);
            raw.push(ch);
            chars.next();
        }
        spec.precision = Some(precision.parse().unwrap_or(0));
    }

    let Some((_, conversion)) = chars.next() else {
        return (None, raw);
    };
    raw.push(conversion);
    if matches!(conversion, 'd' | 'i' | 'f' | 'e' | 'E' | 'g' | 'G') {
        spec.conversion = conversion;
        (Some(spec), raw)
    } else {
        (None, raw)
    }
}

fn format_percent_value(value: f64, spec: PercentSpec) -> String {
    let precision = spec.precision.unwrap_or(6);
    let mut rendered = match spec.conversion {
        'd' | 'i' => format!("{}", value.trunc() as i64),
        'f' => format!("{value:.precision$}"),
        'e' => format!("{value:.precision$e}"),
        'E' => format!("{value:.precision$E}"),
        'g' => format_general(value, precision, false),
        'G' => format_general(value, precision, true),
        _ => value.to_string(),
    };

    if value >= 0.0 && spec.sign_plus {
        rendered.insert(0, '+');
    } else if value >= 0.0 && spec.sign_space {
        rendered.insert(0, ' ');
    }

    let Some(width) = spec.width else {
        return rendered;
    };
    if rendered.len() >= width {
        return rendered;
    }

    let pad_len = width - rendered.len();
    if spec.left_align {
        rendered.push_str(&" ".repeat(pad_len));
    } else if spec.zero_pad {
        let sign_len = usize::from(rendered.starts_with(['-', '+', ' ']));
        rendered.insert_str(sign_len, &"0".repeat(pad_len));
    } else {
        rendered.insert_str(0, &" ".repeat(pad_len));
    }
    rendered
}

fn format_general(value: f64, precision: usize, uppercase: bool) -> String {
    if value == 0.0 {
        return "0".to_owned();
    }

    let precision = precision.max(1);
    let abs = value.abs();
    let exponent = abs.log10().floor() as i32;
    let mut rendered = if exponent < -4 || exponent >= precision as i32 {
        let exp_precision = precision.saturating_sub(1);
        if uppercase {
            format!("{value:.exp_precision$E}")
        } else {
            format!("{value:.exp_precision$e}")
        }
    } else {
        let decimals = (precision as i32 - exponent - 1).max(0) as usize;
        format!("{value:.decimals$}")
    };

    if let Some(exp_pos) = rendered.find(['e', 'E']) {
        let (mantissa, exponent_part) = rendered.split_at(exp_pos);
        let mantissa = trim_decimal_zeros(mantissa);
        rendered = format!("{mantissa}{exponent_part}");
    } else {
        rendered = trim_decimal_zeros(&rendered);
    }
    rendered
}

fn trim_decimal_zeros(value: &str) -> String {
    if let Some(dot) = value.find('.') {
        let mut end = value.len();
        while end > dot + 1 && value.as_bytes()[end - 1] == b'0' {
            end -= 1;
        }
        if end == dot + 1 {
            end -= 1;
        }
        value[..end].to_owned()
    } else {
        value.to_owned()
    }
}

/// Format ticks with a `{x}` / `{pos}` template string.
///
/// Small deterministic subset of matplotlib's `StrMethodFormatter`.
/// Occurrences of `{x}` and `{pos}` are replaced with the value and position
/// respectively, `{{` and `}}` escape literal braces, and numeric value fields
/// support a compact Python-like format-spec subset such as `{x:.2f}`,
/// `{x:+08.1e}`, or `{pos:02d}`. A missing position renders as the empty
/// string.
pub struct StrMethodFormatter {
    fmt: String,
}

impl StrMethodFormatter {
    /// Create a formatter from a template containing `{x}` and/or `{pos}`.
    pub fn new(fmt: impl Into<String>) -> Self {
        StrMethodFormatter { fmt: fmt.into() }
    }

    /// Return the configured `{x}`/`{pos}` template.
    #[must_use]
    pub fn template(&self) -> &str {
        &self.fmt
    }
}

impl Default for StrMethodFormatter {
    /// Create a formatter with the default `{x}` template.
    fn default() -> Self {
        StrMethodFormatter::new("{x}")
    }
}

impl Formatter for StrMethodFormatter {
    fn format(&self, value: f64, pos: Option<usize>) -> String {
        format_str_method_template(&self.fmt, value, pos)
    }
}

fn format_str_method_template(fmt: &str, value: f64, pos: Option<usize>) -> String {
    let mut out = String::new();
    let mut chars = fmt.char_indices().peekable();

    while let Some((_, ch)) = chars.next() {
        match ch {
            '{' if matches!(chars.peek(), Some((_, '{'))) => {
                chars.next();
                out.push('{');
            }
            '}' if matches!(chars.peek(), Some((_, '}'))) => {
                chars.next();
                out.push('}');
            }
            '{' => {
                let mut field = String::new();
                let mut closed = false;
                for (_, field_ch) in chars.by_ref() {
                    if field_ch == '}' {
                        closed = true;
                        break;
                    }
                    field.push(field_ch);
                }
                if closed {
                    if let Some(rendered) = format_str_method_field(&field, value, pos) {
                        out.push_str(&rendered);
                    } else {
                        out.push('{');
                        out.push_str(&field);
                        out.push('}');
                    }
                } else {
                    out.push('{');
                    out.push_str(&field);
                }
            }
            _ => out.push(ch),
        }
    }

    out
}

fn format_str_method_field(field: &str, value: f64, pos: Option<usize>) -> Option<String> {
    let (name, spec) = field.split_once(':').unwrap_or((field, ""));
    match name {
        "x" => Some(if spec.is_empty() {
            value.to_string()
        } else {
            format_brace_numeric(value, spec)?
        }),
        "pos" => {
            let Some(pos) = pos else {
                return Some(String::new());
            };
            Some(if spec.is_empty() {
                pos.to_string()
            } else {
                format_brace_integer(pos, spec)?
            })
        }
        _ => None,
    }
}

fn format_brace_numeric(value: f64, spec: &str) -> Option<String> {
    let mut chars = spec.char_indices().peekable();
    let (percent, raw) = parse_percent_spec(&mut chars);
    if chars.peek().is_some() {
        return None;
    }
    let mut percent = percent?;
    if raw != spec {
        return None;
    }
    if percent.conversion == '\0' {
        percent.conversion = 'g';
    }
    Some(format_percent_value(value, percent))
}

fn format_brace_integer(value: usize, spec: &str) -> Option<String> {
    let mut chars = spec.char_indices().peekable();
    let (percent, raw) = parse_percent_spec(&mut chars);
    if chars.peek().is_some() || raw != spec {
        return None;
    }
    let percent = percent?;
    match percent.conversion {
        'd' | 'i' | 'f' | 'e' | 'E' | 'g' | 'G' => {
            Some(format_percent_value(value as f64, percent))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Compare two tick vectors with a tight tolerance.
    ///
    /// Matplotlib's vectors carry the usual binary-float noise (e.g.
    /// `0.30000000000000004`); we assert near-equality rather than bit-equality.
    fn assert_ticks(actual: &[f64], expected: &[f64]) {
        assert_eq!(
            actual.len(),
            expected.len(),
            "length mismatch: got {actual:?}, expected {expected:?}"
        );
        for (a, e) in actual.iter().zip(expected) {
            assert!(
                (a - e).abs() < 1e-9,
                "value mismatch: got {actual:?}, expected {expected:?}"
            );
        }
    }

    // Ground-truth vectors below were produced by shelling out to a working
    // matplotlib install (3.x) on the reference ranges, e.g.:
    //   python3 -c "import matplotlib.ticker as t; \
    //       print(list(t.MaxNLocator().tick_values(0.0, 1.0)))"

    #[test]
    fn maxn_default_0_1() {
        let locs = MaxNLocator::default().tick_values(0.0, 1.0);
        assert_ticks(
            &locs,
            &[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
        );
    }

    #[test]
    fn maxn_default_0_100() {
        let locs = MaxNLocator::default().tick_values(0.0, 100.0);
        assert_ticks(
            &locs,
            &[
                0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0,
            ],
        );
    }

    #[test]
    fn maxn_default_neg3_7() {
        let locs = MaxNLocator::default().tick_values(-3.0, 7.0);
        assert_ticks(
            &locs,
            &[-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],
        );
    }

    #[test]
    fn maxn_default_0_09() {
        // Note: matplotlib returns 9 ticks here (0.0..=0.9, no 1.0), because
        // the upper edge tick 1.0 lies beyond vmax = 0.9.
        let locs = MaxNLocator::default().tick_values(0.0, 0.9);
        assert_ticks(&locs, &[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]);
    }

    #[test]
    fn maxn_prune_lower_upper_and_both() {
        let lower = MaxNLocator::new(NBins::Fixed(4))
            .with_prune(TickPrune::Lower)
            .tick_values(0.0, 1.0);
        let upper = MaxNLocator::new(NBins::Fixed(4))
            .with_prune(TickPrune::Upper)
            .tick_values(0.0, 1.0);
        let both = MaxNLocator::new(NBins::Fixed(4))
            .with_prune(TickPrune::Both)
            .tick_values(0.0, 1.0);

        assert_ticks(&lower, &[0.25, 0.5, 0.75, 1.0]);
        assert_ticks(&upper, &[0.0, 0.25, 0.5, 0.75]);
        assert_ticks(&both, &[0.25, 0.5, 0.75]);
    }

    #[test]
    fn maxn_prune_keeps_noncoincident_edges() {
        let locs = MaxNLocator::new(NBins::Fixed(4))
            .with_prune(TickPrune::Both)
            .tick_values(0.1, 0.9);

        assert_ticks(&locs, &[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]);
    }

    #[test]
    fn maxn_integer_builder_uses_integer_steps_when_possible() {
        let locs = MaxNLocator::new(NBins::Fixed(4))
            .with_integer(true)
            .tick_values(0.2, 3.8);

        assert!(locs.iter().all(|tick| (tick - tick.round()).abs() < 1e-12));
    }

    #[test]
    fn maxn_symmetric_builder_mirrors_about_zero() {
        let locs = MaxNLocator::new(NBins::Fixed(4))
            .with_symmetric(true)
            .tick_values(-1.0, 3.0);

        assert_ticks(&locs, &[-3.0, -1.5, 0.0, 1.5, 3.0]);
    }

    #[test]
    fn maxn_min_ticks_builder_clamps_to_at_least_one() {
        let locs = MaxNLocator::new(NBins::Fixed(1))
            .with_min_n_ticks(0)
            .tick_values(0.0, 1.0);

        assert!(!locs.is_empty());
    }

    #[test]
    fn maxn_exposes_builder_configuration() {
        let locator = MaxNLocator::new(NBins::Fixed(4))
            .with_integer(true)
            .with_symmetric(true)
            .with_min_n_ticks(0)
            .with_prune(TickPrune::Both);

        assert_eq!(locator.nbins(), NBins::Fixed(4));
        assert!(locator.integer());
        assert!(locator.symmetric());
        assert_eq!(locator.min_n_ticks(), 1);
        assert_eq!(locator.prune(), TickPrune::Both);
    }

    #[test]
    fn auto_0_1() {
        let locs = AutoLocator::new().tick_values(0.0, 1.0);
        assert_ticks(&locs, &[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]);
    }

    #[test]
    fn auto_neg3_7() {
        // AutoLocator uses nbins='auto' (=> 9) and steps [1,2,2.5,5,10],
        // yielding a step of 2 and edge ticks at -4 and 8.
        let locs = AutoLocator::new().tick_values(-3.0, 7.0);
        assert_ticks(&locs, &[-4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 8.0]);
    }

    #[test]
    fn auto_minor_uses_four_subdivisions_for_non_12510_major_steps() {
        // AutoLocator on 0..1 has a 0.2 major step. Since 2 is not in
        // matplotlib's [1, 2.5, 5, 10] auto-minor set, each interval has 4
        // subdivisions and therefore 3 visible minor ticks.
        let locs = AutoMinorLocator::new().tick_values(0.0, 1.0);

        assert_ticks(
            &locs,
            &[
                0.05, 0.10, 0.15, 0.25, 0.30, 0.35, 0.45, 0.50, 0.55, 0.65, 0.70, 0.75, 0.85, 0.90,
                0.95,
            ],
        );
    }

    #[test]
    fn auto_minor_uses_five_subdivisions_for_12510_major_steps() {
        // AutoLocator on 0..0.9 has a 0.1 major step. The mantissa is 1, so
        // each interval has 5 subdivisions and therefore 4 visible minor ticks.
        let locs = AutoMinorLocator::new().tick_values(0.0, 0.9);

        assert_ticks(
            &locs,
            &[
                0.02, 0.04, 0.06, 0.08, 0.12, 0.14, 0.16, 0.18, 0.22, 0.24, 0.26, 0.28, 0.32, 0.34,
                0.36, 0.38, 0.42, 0.44, 0.46, 0.48, 0.52, 0.54, 0.56, 0.58, 0.62, 0.64, 0.66, 0.68,
                0.72, 0.74, 0.76, 0.78, 0.82, 0.84, 0.86, 0.88,
            ],
        );
    }

    #[test]
    fn auto_minor_with_explicit_subdivisions_filters_major_ticks() {
        let locs = AutoMinorLocator::with_subdivisions(2).tick_values(0.0, 1.0);

        assert_ticks(&locs, &[0.1, 0.3, 0.5, 0.7, 0.9]);
    }

    #[test]
    fn auto_minor_can_use_explicit_major_ticks() {
        let locator = AutoMinorLocator::new();
        let locs = locator.tick_values_from_major(&[0.0, 0.5, 1.0], 0.0, 1.0);

        assert_ticks(&locs, &[0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9]);
    }

    #[test]
    fn auto_minor_explicit_major_ticks_sort_dedup_and_filter_coincidences() {
        let locator = AutoMinorLocator::with_subdivisions(2);
        let locs = locator.tick_values_from_major(&[1.0, 0.0, 0.5, 0.5, f64::NAN], 0.0, 1.0);

        assert_ticks(&locs, &[0.25, 0.75]);
    }

    #[test]
    fn auto_minor_explicit_major_ticks_handle_reversed_ranges() {
        let locator = AutoMinorLocator::with_subdivisions(2);
        let locs = locator.tick_values_from_major(&[0.0, 0.5, 1.0], 1.0, 0.0);

        assert_ticks(&locs, &[0.75, 0.25]);
    }

    #[test]
    fn auto_minor_exposes_configured_subdivisions() {
        assert_eq!(AutoMinorLocator::new().subdivisions(), None);
        assert_eq!(
            AutoMinorLocator::with_subdivisions(4).subdivisions(),
            Some(4)
        );
    }

    #[test]
    fn auto_minor_handles_reversed_ranges() {
        let locs = AutoMinorLocator::with_subdivisions(2).tick_values(1.0, 0.0);

        assert_ticks(&locs, &[0.9, 0.7, 0.5, 0.3, 0.1]);
    }

    #[test]
    fn auto_minor_guards_degenerate_inputs() {
        assert!(AutoMinorLocator::new().tick_values(1.0, 1.0).is_empty());
        assert!(
            AutoMinorLocator::new()
                .tick_values(f64::NAN, 1.0)
                .is_empty()
        );
        assert!(
            AutoMinorLocator::new()
                .tick_values(0.0, f64::INFINITY)
                .is_empty()
        );
        assert!(
            AutoMinorLocator::with_subdivisions(1)
                .tick_values(0.0, 1.0)
                .is_empty()
        );
        assert!(
            AutoMinorLocator::new()
                .tick_values_from_major(&[0.0], 0.0, 1.0)
                .is_empty()
        );
        assert!(
            AutoMinorLocator::new()
                .tick_values_from_major(&[0.0, 1.0], 0.0, f64::INFINITY)
                .is_empty()
        );
    }

    #[test]
    fn multiple_half_0_2() {
        let locs = MultipleLocator::new(0.5).tick_values(0.0, 2.0);
        assert_ticks(&locs, &[-0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5]);
    }

    #[test]
    fn multiple_locator_exposes_base_and_offset() {
        let locator = MultipleLocator::with_offset(0.5, 0.25);

        assert_eq!(locator.base(), 0.5);
        assert_eq!(locator.offset(), 0.25);
    }

    #[test]
    fn multiple_locator_default_uses_unit_spacing() {
        let locator = MultipleLocator::default();

        assert_eq!(locator.base(), 1.0);
        assert_eq!(locator.offset(), 0.0);
        assert_ticks(&locator.tick_values(0.0, 2.0), &[-1.0, 0.0, 1.0, 2.0, 3.0]);
    }

    #[test]
    #[should_panic(expected = "multiple locator base must be finite and > 0")]
    fn multiple_locator_rejects_nonpositive_base() {
        let _ = MultipleLocator::new(0.0);
    }

    #[test]
    #[should_panic(expected = "multiple locator base must be finite and > 0")]
    fn multiple_locator_rejects_nonfinite_base() {
        let _ = MultipleLocator::with_offset(f64::NAN, 0.0);
    }

    #[test]
    fn linear_default_0_10() {
        let locs = LinearLocator::default().tick_values(0.0, 10.0);
        assert_ticks(
            &locs,
            &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
        );
    }

    #[test]
    fn linear_5_0_1() {
        let locator = LinearLocator::new(5);
        let locs = locator.tick_values(0.0, 1.0);

        assert_eq!(locator.numticks(), 5);
        assert_ticks(&locs, &[0.0, 0.25, 0.5, 0.75, 1.0]);
    }

    #[test]
    fn reversed_range_is_sorted() {
        // matplotlib swaps reversed ranges internally.
        let locs = MaxNLocator::default().tick_values(1.0, 0.0);
        assert_ticks(
            &locs,
            &[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
        );
    }

    #[test]
    fn fixed_locator_passthrough() {
        let locs = FixedLocator::new(vec![1.0, 2.0, 3.0]).tick_values(0.0, 10.0);
        assert_ticks(&locs, &[1.0, 2.0, 3.0]);
    }

    #[test]
    fn fixed_locator_accepts_iterable_locations() {
        let locator = FixedLocator::from_locations([0.0, 0.5, 1.0]);

        assert_ticks(locator.locations(), &[0.0, 0.5, 1.0]);
        assert_ticks(&locator.tick_values(-10.0, 10.0), &[0.0, 0.5, 1.0]);
        assert_eq!(locator.nbins(), None);
    }

    #[test]
    fn fixed_locator_default_has_no_locations() {
        let locator = FixedLocator::default();

        assert!(locator.locations().is_empty());
        assert_eq!(locator.nbins(), None);
        assert!(locator.tick_values(0.0, 1.0).is_empty());
    }

    #[test]
    fn fixed_locator_subsample_keeps_zero() {
        // locs -3..=3, nbins=3 -> step=ceil(7/3)=3; the offset that includes 0
        // has the smallest min-abs and is selected.
        let locs = FixedLocator::with_nbins(vec![-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0], 3)
            .tick_values(0.0, 0.0);
        assert!(
            locs.contains(&0.0),
            "expected the zero-containing subset: {locs:?}"
        );
    }

    #[test]
    fn fixed_locator_exposes_configured_locations_and_nbins() {
        let locator = FixedLocator::with_nbins(vec![-1.0, 0.0, 1.0], 1);

        assert_eq!(locator.locations(), &[-1.0, 0.0, 1.0]);
        assert_eq!(locator.nbins(), Some(2));
        assert_eq!(FixedLocator::new(vec![2.0]).nbins(), None);
    }

    #[test]
    fn index_locator_uses_base_and_offset() {
        let locator = IndexLocator::new(2.0, 1.0);
        let locs = locator.tick_values(0.0, 8.0);

        assert_eq!(locator.base(), 2.0);
        assert_eq!(locator.offset(), 1.0);
        assert_ticks(&locs, &[1.0, 3.0, 5.0, 7.0]);
    }

    #[test]
    fn index_locator_handles_reversed_ranges() {
        let locs = IndexLocator::new(2.0, 1.0).tick_values(8.0, 0.0);
        assert_ticks(&locs, &[7.0, 5.0, 3.0, 1.0]);
    }

    #[test]
    fn index_locator_guards_invalid_inputs() {
        let locs = IndexLocator::new(0.0, 0.0).tick_values(0.0, 3.0);
        assert_ticks(&locs, &[0.0, 1.0, 2.0, 3.0]);
        let locs = IndexLocator::new(2.0, f64::NAN).tick_values(0.0, 4.0);
        assert_ticks(&locs, &[0.0, 2.0, 4.0]);
        assert_eq!(IndexLocator::new(2.0, f64::INFINITY).offset(), 0.0);
        assert!(
            IndexLocator::new(2.0, 0.0)
                .tick_values(f64::NAN, 3.0)
                .is_empty()
        );
    }

    #[test]
    fn log_locator_base10_decades() {
        let locs = LogLocator::new(10.0).tick_values(1.0, 1000.0);
        assert_ticks(&locs, &[1.0, 10.0, 100.0, 1000.0]);
    }

    #[test]
    fn log_locator_minor_subticks_present() {
        let locs = LogLocator::minor(10.0).tick_values(1.0, 20.0);

        assert!(locs.contains(&2.0));
        assert!(locs.contains(&9.0));
        assert!(locs.contains(&20.0));
        assert!(!locs.contains(&1.0));
        assert!(!locs.contains(&10.0));
    }

    #[test]
    fn log_locator_base2_decades() {
        let locs = LogLocator::new(2.0).tick_values(1.0, 32.0);
        assert_ticks(&locs, &[1.0, 2.0, 4.0, 8.0, 16.0, 32.0]);
    }

    #[test]
    fn log_locator_rejects_nonpositive_or_nonfinite_domain() {
        assert!(LogLocator::new(10.0).tick_values(-1.0, 100.0).is_empty());
        assert!(
            LogLocator::new(10.0)
                .tick_values(1.0, f64::INFINITY)
                .is_empty()
        );
    }

    #[test]
    fn log_locator_view_limits_snap_to_decades() {
        let (lo, hi) = LogLocator::new(10.0).view_limits(3.0, 88.0);
        assert_eq!((lo, hi), (1.0, 100.0));
    }

    #[test]
    fn log_formatter_labels_major_ticks_and_hides_minor_ticks() {
        let formatter = LogFormatter::new(10.0);

        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(10.0, None), "10");
        assert_eq!(formatter.format(100.0, None), "100");
        assert_eq!(formatter.format(1000.0, None), "1000");
        assert_eq!(formatter.format(2.0, None), "");
        assert_eq!(formatter.format(1e6, None), "10^{6}");
    }

    #[test]
    fn log_formatter_base2_labels_powers() {
        let formatter = LogFormatter::new(2.0);

        assert_eq!(formatter.base(), 2.0);
        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(8.0, None), "8");
        assert_eq!(formatter.format(128.0, None), "2^{7}");
        assert_eq!(formatter.format(3.0, None), "");
    }

    #[test]
    fn log_formatter_mathtext_wraps_exponent_labels() {
        let formatter = LogFormatterMathtext::new(10.0);

        assert_eq!(formatter.format(10.0, None), "10");
        assert_eq!(formatter.format(1e6, None), "$10^{6}$");
        assert_eq!(formatter.format(2.0, None), "");
    }

    #[test]
    fn log_formatter_mathtext_honors_base2() {
        let formatter = LogFormatterMathtext::new(2.0);

        assert_eq!(formatter.base(), 2.0);
        assert_eq!(formatter.format(8.0, None), "8");
        assert_eq!(formatter.format(128.0, None), "$2^{7}$");
    }

    #[test]
    fn symlog_locator_spans_negative_linear_and_positive_regions() {
        let locs = SymlogLocator::new(10.0, 1.0).tick_values(-100.0, 100.0);

        assert_ticks(&locs, &[-100.0, -10.0, -1.0, 0.0, 1.0, 10.0, 100.0]);
    }

    #[test]
    fn symlog_locator_honors_base_and_linthresh() {
        let locator = SymlogLocator::new(2.0, 0.5);
        let locs = locator.tick_values(-4.0, 4.0);

        assert_eq!(locator.base(), 2.0);
        assert_eq!(locator.linthresh(), 0.5);
        assert_eq!(locator.linear_ticks(), 3);
        assert_ticks(&locs, &[-4.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 4.0]);
    }

    #[test]
    fn symlog_locator_handles_reversed_ranges() {
        let locs = SymlogLocator::new(10.0, 1.0).tick_values(100.0, -100.0);

        assert_ticks(&locs, &[100.0, 10.0, 1.0, 0.0, -1.0, -10.0, -100.0]);
    }

    #[test]
    fn symlog_locator_rejects_nonfinite_domain() {
        assert!(
            SymlogLocator::new(10.0, 1.0)
                .tick_values(f64::NEG_INFINITY, 100.0)
                .is_empty()
        );
    }

    #[test]
    fn symlog_formatter_labels_linear_and_tail_ticks() {
        let formatter = SymlogFormatter::new(10.0, 1.0);

        assert_eq!(formatter.base(), 10.0);
        assert_eq!(formatter.linthresh(), 1.0);
        assert_eq!(formatter.format(-100.0, None), "-100");
        assert_eq!(formatter.format(-1.0, None), "-1");
        assert_eq!(formatter.format(0.0, None), "0");
        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(100.0, None), "100");
        assert_eq!(formatter.format(20.0, None), "");
        assert_eq!(formatter.format(1e6, None), "10^{6}");
        assert_eq!(formatter.format(-1e6, None), "-10^{6}");
    }

    #[test]
    fn symlog_formatter_nonunit_linthresh_uses_decimal_tail_labels() {
        let formatter = SymlogFormatter::new(10.0, 2.0);

        assert_eq!(formatter.format(2.0, None), "2");
        assert_eq!(formatter.format(20.0, None), "20");
        assert_eq!(formatter.format(40.0, None), "");
    }

    #[test]
    fn symlog_formatter_mathtext_wraps_large_tail_labels() {
        let formatter = SymlogFormatterMathtext::new(10.0, 1.0);

        assert_eq!(formatter.base(), 10.0);
        assert_eq!(formatter.linthresh(), 1.0);
        assert_eq!(formatter.format(-1.0, None), "-1");
        assert_eq!(formatter.format(0.0, None), "0");
        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(100.0, None), "100");
        assert_eq!(formatter.format(1e6, None), "$10^{6}$");
        assert_eq!(formatter.format(-1e6, None), "$-10^{6}$");
        assert_eq!(formatter.format(20.0, None), "");
    }

    #[test]
    fn symlog_formatter_mathtext_nonunit_linthresh_uses_decimal_tail_labels() {
        let formatter = SymlogFormatterMathtext::new(10.0, 2.0);

        assert_eq!(formatter.format(2.0, None), "2");
        assert_eq!(formatter.format(20.0, None), "20");
        assert_eq!(formatter.format(40.0, None), "");
    }

    #[test]
    fn asinh_locator_spans_negative_linear_and_positive_regions() {
        let locs = AsinhLocator::new(1.0).tick_values(-100.0, 100.0);

        assert_ticks(&locs, &[-100.0, -10.0, -1.0, 0.0, 1.0, 10.0, 100.0]);
    }

    #[test]
    fn asinh_locator_honors_base_and_linear_width() {
        let locator = AsinhLocator::with_linear_ticks(2.0, 0.5, 3);
        let locs = locator.tick_values(-4.0, 4.0);

        assert_eq!(locator.base(), 2.0);
        assert_eq!(locator.linear_width(), 0.5);
        assert_eq!(locator.linear_ticks(), 3);
        assert_ticks(&locs, &[-4.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 4.0]);
    }

    #[test]
    fn asinh_locator_handles_reversed_ranges() {
        let locs = AsinhLocator::new(1.0).tick_values(100.0, -100.0);

        assert_ticks(&locs, &[100.0, 10.0, 1.0, 0.0, -1.0, -10.0, -100.0]);
    }

    #[test]
    fn asinh_locator_rejects_nonfinite_domain() {
        assert!(
            AsinhLocator::new(1.0)
                .tick_values(f64::NEG_INFINITY, 100.0)
                .is_empty()
        );
    }

    #[test]
    fn asinh_locator_view_limits_snap_to_ticks() {
        let (lo, hi) = AsinhLocator::new(1.0).view_limits(-32.0, 32.0);

        assert_eq!((lo, hi), (-100.0, 100.0));
    }

    #[test]
    fn asinh_formatter_labels_linear_and_tail_ticks() {
        let formatter = AsinhFormatter::new(10.0, 1.0);

        assert_eq!(formatter.base(), 10.0);
        assert_eq!(formatter.linear_width(), 1.0);
        assert_eq!(formatter.format(-100.0, None), "-100");
        assert_eq!(formatter.format(-1.0, None), "-1");
        assert_eq!(formatter.format(0.0, None), "0");
        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(100.0, None), "100");
        assert_eq!(formatter.format(20.0, None), "");
        assert_eq!(formatter.format(1e6, None), "10^{6}");
        assert_eq!(formatter.format(-1e6, None), "-10^{6}");
    }

    #[test]
    fn asinh_formatter_nonunit_width_uses_decimal_tail_labels() {
        let formatter = AsinhFormatter::new(10.0, 2.0);

        assert_eq!(formatter.format(2.0, None), "2");
        assert_eq!(formatter.format(20.0, None), "20");
        assert_eq!(formatter.format(40.0, None), "");
    }

    #[test]
    fn asinh_formatter_mathtext_wraps_large_tail_labels() {
        let formatter = AsinhFormatterMathtext::new(10.0, 1.0);

        assert_eq!(formatter.base(), 10.0);
        assert_eq!(formatter.linear_width(), 1.0);
        assert_eq!(formatter.format(-1.0, None), "-1");
        assert_eq!(formatter.format(0.0, None), "0");
        assert_eq!(formatter.format(1.0, None), "1");
        assert_eq!(formatter.format(100.0, None), "100");
        assert_eq!(formatter.format(1e6, None), "$10^{6}$");
        assert_eq!(formatter.format(-1e6, None), "$-10^{6}$");
        assert_eq!(formatter.format(20.0, None), "");
    }

    #[test]
    fn asinh_formatter_mathtext_nonunit_width_uses_decimal_tail_labels() {
        let formatter = AsinhFormatterMathtext::new(10.0, 2.0);

        assert_eq!(formatter.format(2.0, None), "2");
        assert_eq!(formatter.format(20.0, None), "20");
        assert_eq!(formatter.format(40.0, None), "");
    }

    #[test]
    fn logit_locator_clusters_toward_zero_and_one() {
        let locs = LogitLocator::with_max_exponent(3).tick_values(0.001, 0.999);

        assert_ticks(&locs, &[0.001, 0.01, 0.1, 0.5, 0.9, 0.99, 0.999]);
    }

    #[test]
    fn logit_locator_handles_reversed_ranges() {
        let locs = LogitLocator::with_max_exponent(2).tick_values(0.99, 0.01);

        assert_ticks(&locs, &[0.99, 0.9, 0.5, 0.1, 0.01]);
    }

    #[test]
    fn logit_locator_rejects_outside_probability_domain() {
        assert!(LogitLocator::new().tick_values(0.0, 0.99).is_empty());
        assert!(LogitLocator::new().tick_values(0.01, 1.0).is_empty());
        assert!(
            LogitLocator::new()
                .tick_values(0.01, f64::INFINITY)
                .is_empty()
        );
    }

    #[test]
    fn logit_locator_view_limits_clamp_to_open_interval() {
        let (lo, hi) = LogitLocator::with_max_exponent(4).view_limits(-1.0, 2.0);

        assert_eq!((lo, hi), (1e-4, 1.0 - 1e-4));
    }

    #[test]
    fn logit_formatter_labels_probability_lattice() {
        let formatter = LogitFormatter::with_max_exponent(4);

        assert_eq!(formatter.max_exponent(), 4);
        assert_eq!(formatter.format(0.1, None), "0.1");
        assert_eq!(formatter.format(0.01, None), "10^{-2}");
        assert_eq!(formatter.format(0.5, None), "1/2");
        assert_eq!(formatter.format(0.9, None), "0.9");
        assert_eq!(formatter.format(0.99, None), "1-10^{-2}");
        assert_eq!(formatter.format(0.2, None), "");
    }

    #[test]
    fn logit_formatter_mathtext_wraps_tail_labels() {
        let formatter = LogitFormatterMathtext::with_max_exponent(4);

        assert_eq!(formatter.max_exponent(), 4);
        assert_eq!(formatter.format(0.1, None), "0.1");
        assert_eq!(formatter.format(0.01, None), "$10^{-2}$");
        assert_eq!(formatter.format(0.5, None), "1/2");
        assert_eq!(formatter.format(0.9, None), "0.9");
        assert_eq!(formatter.format(0.99, None), "$1-10^{-2}$");
        assert_eq!(formatter.format(0.2, None), "");
    }

    #[test]
    fn eng_formatter_uses_si_prefixes() {
        let formatter = EngFormatter::new();

        assert_eq!(formatter.format(1_000.0, None), "1k");
        assert_eq!(formatter.format(1_500_000.0, None), "1.5M");
        assert_eq!(formatter.format(0.001, None), "1m");
        assert_eq!(formatter.format(0.000_001, None), "1u");
        assert_eq!(formatter.format(-2_000.0, None), "-2k");
        assert_eq!(formatter.format(0.0, None), "0");
    }

    #[test]
    fn eng_formatter_supports_units_separator_and_places() {
        let formatter = EngFormatter::new()
            .with_unit("Hz")
            .with_separator(" ")
            .with_places(2);

        assert_eq!(formatter.unit(), "Hz");
        assert_eq!(formatter.separator(), " ");
        assert_eq!(formatter.places(), Some(2));
        assert_eq!(formatter.format(12_300.0, None), "12.30 kHz");
        assert_eq!(formatter.format(0.0, None), "0 Hz");
    }

    #[test]
    fn percent_formatter_defaults_to_xmax_100() {
        let formatter = PercentFormatter::new();

        assert_eq!(formatter.format(25.0, None), "25%");
        assert_eq!(formatter.format(100.0, None), "100%");
    }

    #[test]
    fn percent_formatter_fraction_maps_one_to_hundred_percent() {
        let formatter = PercentFormatter::fraction();

        assert_eq!(formatter.xmax(), 1.0);
        assert_eq!(formatter.format(0.25, None), "25%");
        assert_eq!(formatter.format(1.0, None), "100%");
    }

    #[test]
    fn percent_formatter_supports_fractional_xmax_and_decimals() {
        let formatter = PercentFormatter::with_xmax(1.0)
            .with_decimals(1)
            .with_symbol(" pct");

        assert_eq!(formatter.xmax(), 1.0);
        assert_eq!(formatter.decimals(), 1);
        assert_eq!(formatter.symbol(), " pct");
        assert_eq!(formatter.format(0.125, None), "12.5 pct");
        assert_eq!(formatter.format(1.0, None), "100.0 pct");
    }

    #[test]
    fn null_locator_empty() {
        assert!(NullLocator.tick_values(0.0, 10.0).is_empty());
        assert!(
            default_value::<NullLocator>()
                .tick_values(0.0, 10.0)
                .is_empty()
        );
    }

    #[test]
    fn null_formatter_empty() {
        assert_eq!(NullFormatter.format(2.5, Some(0)), "");
        assert_eq!(
            NullFormatter.format(2.5, Some(0)),
            default_value::<NullFormatter>().format(2.5, Some(0))
        );
    }

    fn default_value<T: Default>() -> T {
        T::default()
    }

    #[test]
    fn scalar_formatter_picks_precision() {
        let locs = MaxNLocator::default().tick_values(0.0, 1.0);
        let mut f = ScalarFormatter::new();
        assert!(!f.has_format());
        f.set_locs(&locs);
        // Spacing of 0.1 over [0,1] -> one decimal place.
        assert!(f.has_format());
        assert_eq!(f.decimals(), 1);
        assert_eq!(f.format(0.5, Some(5)), "0.5");
        assert_eq!(f.format(0.0, Some(0)), "0.0");
    }

    #[test]
    fn scalar_formatter_can_start_with_fixed_decimals() {
        let f = ScalarFormatter::with_decimals(3);

        assert_eq!(f.decimals(), 3);
        assert!(!f.has_format());
        assert_eq!(f.format(1.25, Some(0)), "1.250");
    }

    #[test]
    fn scalar_formatter_integers() {
        let locs = MaxNLocator::default().tick_values(0.0, 100.0);
        let mut f = ScalarFormatter::new();
        f.set_locs(&locs);
        // Integer spacing -> zero decimals.
        assert_eq!(f.decimals(), 0);
        assert_eq!(f.format(50.0, Some(5)), "50");
        assert_eq!(f.format(0.0, Some(0)), "0");
    }

    #[test]
    fn fixed_formatter_by_position() {
        let f = FixedFormatter::new(vec!["a".into(), "b".into()]);
        assert_eq!(f.labels(), &["a".to_string(), "b".to_string()]);
        assert_eq!(f.format(0.0, Some(0)), "a");
        assert_eq!(f.format(99.0, Some(1)), "b");
        assert_eq!(f.format(0.0, Some(2)), "");
        assert_eq!(f.format(0.0, None), "");
    }

    #[test]
    fn fixed_formatter_accepts_convertible_labels() {
        let f = FixedFormatter::from_labels(["zero", "one", "two"]);
        assert_eq!(
            f.labels(),
            &["zero".to_string(), "one".to_string(), "two".to_string()]
        );
        assert_eq!(f.format(0.0, Some(2)), "two");
        assert_eq!(f.format(0.0, Some(3)), "");
    }

    #[test]
    fn fixed_formatter_default_has_no_labels() {
        let f = FixedFormatter::default();

        assert!(f.labels().is_empty());
        assert_eq!(f.format(0.0, Some(0)), "");
    }

    #[test]
    fn index_formatter_uses_rounded_tick_value() {
        let f = IndexFormatter::new(vec!["zero".into(), "one".into(), "two".into()]);
        assert_eq!(
            f.labels(),
            &["zero".to_string(), "one".to_string(), "two".to_string()]
        );
        assert_eq!(f.format(0.2, Some(99)), "zero");
        assert_eq!(f.format(0.6, None), "one");
        assert_eq!(f.format(2.49, None), "two");
    }

    #[test]
    fn index_formatter_accepts_convertible_labels() {
        let f = IndexFormatter::from_labels(["zero", "one", "two"]);
        assert_eq!(
            f.labels(),
            &["zero".to_string(), "one".to_string(), "two".to_string()]
        );
        assert_eq!(f.format(1.4, None), "one");
        assert_eq!(f.format(2.6, None), "");
    }

    #[test]
    fn index_formatter_default_has_no_labels() {
        let f = IndexFormatter::default();

        assert!(f.labels().is_empty());
        assert_eq!(f.format(0.0, None), "");
    }

    #[test]
    fn index_formatter_out_of_range_is_empty() {
        let f = IndexFormatter::new(vec!["zero".into(), "one".into()]);
        assert_eq!(f.format(-0.6, None), "");
        assert_eq!(f.format(2.0, None), "");
        assert_eq!(f.format(f64::NAN, None), "");
    }

    #[test]
    fn func_formatter_closure() {
        let f = FuncFormatter::new(Box::new(|x, _| format!("{x:.0} km")));
        assert_eq!(f.format(10.0, None), "10 km");

        let f = FuncFormatter::from_fn(|x, pos| format!("{pos:?}:{x:.1}"));
        assert_eq!(f.format(2.25, Some(3)), "Some(3):2.2");
    }

    #[test]
    fn format_str_formatter_fixed_and_escaped_percent() {
        let f = FormatStrFormatter::new("x=%+.2f%%");

        assert_eq!(f.template(), "x=%+.2f%%");
        assert_eq!(f.format(1.234, None), "x=+1.23%");
        assert_eq!(f.format(-1.234, None), "x=-1.23%");
    }

    #[test]
    fn format_str_formatter_width_zero_pad_and_exp() {
        let f = FormatStrFormatter::new("%08.1e");

        assert_eq!(f.format(12.0, None), "0001.2e1");
    }

    #[test]
    fn format_str_formatter_integer_conversion() {
        let f = FormatStrFormatter::new("%+05d");

        assert_eq!(f.format(12.9, None), "+0012");
        assert_eq!(f.format(-12.9, None), "-0012");
    }

    #[test]
    fn format_str_formatter_general_trims_decimal_zeros() {
        let f = FormatStrFormatter::new("%g");
        let upper = FormatStrFormatter::new("%.3G");

        assert_eq!(f.format(12.300, None), "12.3");
        assert_eq!(upper.format(12345.0, None), "1.23E4");
    }

    #[test]
    fn format_str_formatter_default_uses_general_template() {
        let f = FormatStrFormatter::default();

        assert_eq!(f.template(), "%g");
        assert_eq!(f.format(12.300, None), "12.3");
    }

    #[test]
    fn format_str_formatter_unsupported_spec_is_preserved() {
        let f = FormatStrFormatter::new("x=%q");

        assert_eq!(f.format(3.0, None), "x=%q");
    }

    #[test]
    fn str_method_formatter_template() {
        let f = StrMethodFormatter::new("{x} m");
        assert_eq!(f.template(), "{x} m");
        assert_eq!(f.format(3.0, None), "3 m");
        let g = StrMethodFormatter::new("{x}@{pos}");
        assert_eq!(g.format(2.0, Some(4)), "2@4");
    }

    #[test]
    fn str_method_formatter_default_uses_x_template() {
        let f = StrMethodFormatter::default();

        assert_eq!(f.template(), "{x}");
        assert_eq!(f.format(3.0, Some(2)), "3");
    }

    #[test]
    fn str_method_formatter_numeric_format_spec() {
        let f = StrMethodFormatter::new("x={x:+08.1f}");

        assert_eq!(f.format(12.0, None), "x=+00012.0");
        assert_eq!(f.format(-12.0, None), "x=-00012.0");
    }

    #[test]
    fn str_method_formatter_integer_format_specs() {
        let f = StrMethodFormatter::new("x={x:04d} pos={pos:02d}");

        assert_eq!(f.format(12.9, Some(3)), "x=0012 pos=03");
    }

    #[test]
    fn str_method_formatter_exp_and_general_specs() {
        let exp = StrMethodFormatter::new("{x:.2e}");
        let general = StrMethodFormatter::new("{x:.3G}");

        assert_eq!(exp.format(1234.0, None), "1.23e3");
        assert_eq!(general.format(1234.0, None), "1.23E3");
    }

    #[test]
    fn str_method_formatter_escapes_braces() {
        let f = StrMethodFormatter::new("{{{x:.1f}}}");

        assert_eq!(f.format(3.25, None), "{3.2}");
    }

    #[test]
    fn str_method_formatter_preserves_unknown_fields() {
        let f = StrMethodFormatter::new("{label}={x:.1f}");

        assert_eq!(f.format(2.0, None), "{label}=2.0");
    }

    #[test]
    fn str_method_formatter_missing_pos_is_empty() {
        let f = StrMethodFormatter::new("{x}@{pos}");

        assert_eq!(f.format(2.0, None), "2@");
    }

    #[test]
    fn view_limits_default_identity_for_multiple() {
        let (lo, hi) = MultipleLocator::new(0.5).view_limits(0.0, 2.0);
        assert!((lo - 0.0).abs() < 1e-9 && (hi - 2.0).abs() < 1e-9);
    }
}