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
use crate::plot::legend::{LegendEntry, LegendGroup, LegendPosition};
use crate::render::annotations::{ReferenceLine, ShadedRegion, TextAnnotation};
use crate::render::datetime::DateTimeAxis;
use crate::render::palette::Palette;
use crate::render::plots::Plot;
use crate::render::render::waffle_legend_label;
use crate::render::render_utils;
use crate::render::theme::Theme;
use std::sync::Arc;
/// Default font-family stack applied when the user has not specified a font
/// and no theme font is set. Prefers DejaVu Sans (pre-installed on most Linux
/// systems including HPC clusters), falls back through common sans-serif fonts.
pub(crate) const DEFAULT_FONT_FAMILY: &str = "DejaVu Sans, Liberation Sans, Arial, sans-serif";
/// Controls how tick labels are formatted on an axis.
pub enum TickFormat {
/// Smart default: integers as "5", minimal decimals, scientific notation for extremes.
Auto,
/// Exactly n decimal places: `Fixed(2)` → `"3.14"`.
Fixed(usize),
/// Round to nearest integer: `"5"`.
Integer,
/// ASCII scientific notation: `"1.23e4"`, `"3.5e-2"`.
Sci,
/// Multiply by 100 and append `%`: `0.45` → `"45.0%"`.
Percent,
/// Theta degree for polar plots: `0.0` → `"0°"`, `90.0` → `"90°"`.
Degree,
/// Custom formatter function.
Custom(Arc<dyn Fn(f64) -> String + Send + Sync>),
}
impl std::fmt::Debug for TickFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Auto => write!(f, "TickFormat::Auto"),
Self::Fixed(n) => write!(f, "TickFormat::Fixed({n})"),
Self::Integer => write!(f, "TickFormat::Integer"),
Self::Sci => write!(f, "TickFormat::Sci"),
Self::Percent => write!(f, "TickFormat::Percent"),
Self::Degree => write!(f, "TickFormat::Degree"),
Self::Custom(_) => write!(f, "TickFormat::Custom(<fn>)"),
}
}
}
impl Clone for TickFormat {
fn clone(&self) -> Self {
match self {
Self::Auto => Self::Auto,
Self::Fixed(n) => Self::Fixed(*n),
Self::Integer => Self::Integer,
Self::Sci => Self::Sci,
Self::Percent => Self::Percent,
Self::Degree => Self::Degree,
Self::Custom(f) => Self::Custom(Arc::clone(f)),
}
}
}
impl TickFormat {
pub fn format(&self, v: f64) -> String {
// IEEE 754 negative zero (-0.0 == 0.0 but formats as "-0"). Normalise
// it to positive zero so no formatter can produce "-0" on a tick label.
let v = if v == 0.0 { 0.0 } else { v };
match self {
Self::Auto => tick_format_auto(v),
Self::Fixed(n) => format!("{:.*}", n, v),
Self::Integer => format!("{:.0}", v),
Self::Sci => tick_format_sci(v),
Self::Percent => format!("{:.1}%", v * 100.0),
Self::Degree => tick_format_degree(v),
Self::Custom(f) => f(v),
}
}
}
fn tick_format_degree(v: f64) -> String {
if v == 0.0 {
"0°".to_string()
} else {
format!("{}°", v as i64)
}
}
fn tick_format_auto(v: f64) -> String {
if v.fract().abs() < 1e-9 {
format!("{:.0}", v)
} else if v.abs() >= 10_000.0 || (v != 0.0 && v.abs() < 0.01) {
tick_format_sci(v)
} else {
let s = format!("{:.3}", v);
let s = s.trim_end_matches('0');
let s = s.trim_end_matches('.');
s.to_string()
}
}
fn tick_format_sci(v: f64) -> String {
let raw = format!("{:e}", v);
// raw looks like "1.23e4" or "1e0" or "3.5e-3"
if let Some(e_pos) = raw.find('e') {
let mantissa = &raw[..e_pos];
let exponent = &raw[e_pos + 1..];
// Strip trailing zeros from mantissa
let mantissa = if mantissa.contains('.') {
let m = mantissa.trim_end_matches('0').trim_end_matches('.');
m
} else {
mantissa
};
if exponent == "0" {
mantissa.to_string()
} else {
format!("{}e{}", mantissa, exponent)
}
} else {
raw
}
}
/// Defines the layout of the plot
pub struct Layout {
pub width: Option<f64>,
pub height: Option<f64>,
pub x_range: (f64, f64),
pub y_range: (f64, f64),
/// Raw data range before padding (used by log scale to avoid pad_min issues)
pub data_x_range: Option<(f64, f64)>,
pub data_y_range: Option<(f64, f64)>,
pub ticks: usize,
pub show_grid: bool,
pub x_label: Option<String>,
pub y_label: Option<String>,
pub title: Option<String>,
pub x_categories: Option<Vec<String>>,
pub y_categories: Option<Vec<String>>,
pub show_legend: bool,
pub show_colorbar: bool,
pub legend_position: LegendPosition,
pub legend_width: f64,
/// Manual legend entries. When `Some`, replaces auto-collection from plot data.
pub legend_entries: Option<Vec<LegendEntry>>,
/// Optional title rendered as a bold header above legend entries.
pub legend_title: Option<String>,
/// Grouped legend sections. When `Some`, takes priority over `legend_entries`.
pub legend_groups: Option<Vec<LegendGroup>>,
/// Draw background + border rects around the legend. Default: true.
pub legend_box: bool,
/// Override the computed legend height. When `None`, height is auto-computed from
/// the number of entries/groups. Set explicitly via `with_legend_height(px)`.
pub legend_height: Option<f64>,
/// Total number of flat legend entries expected (set by `auto_from_plots`).
/// Used by `from_layout` to reserve enough right-margin for the overflow line.
pub(crate) legend_entry_count: usize,
/// Longest legend label character count — set by `auto_from_plots` for column layout.
pub(crate) legend_max_label_chars: usize,
// Stats box
/// Pre-formatted text lines to display in a stats box (e.g. "R² = 0.847").
pub stats_entries: Vec<String>,
/// Optional bold title rendered above stats entries.
pub stats_title: Option<String>,
/// Position of the stats box on the canvas. Default: `InsideTopLeft`.
pub stats_position: LegendPosition,
/// Draw background + border rects around the stats box. Default: true.
pub stats_box: bool,
pub log_x: bool,
pub log_y: bool,
pub annotations: Vec<TextAnnotation>,
pub reference_lines: Vec<ReferenceLine>,
pub shaded_regions: Vec<ShadedRegion>,
pub suppress_x_ticks: bool,
pub suppress_y_ticks: bool,
pub font_family: Option<String>,
pub title_size: u32,
pub label_size: u32,
pub tick_size: u32,
pub body_size: u32,
/// Override axis line stroke width (px at scale=1). `None` = use scale default (1.0).
pub axis_line_width: Option<f64>,
/// Override tick mark stroke width (px at scale=1). `None` = use scale default (1.0).
pub tick_width: Option<f64>,
/// Override major tick mark length (px at scale=1). `None` = use scale default (5.0).
/// Minor tick length scales proportionally (60% of major).
pub tick_length: Option<f64>,
/// Override grid line stroke width (px at scale=1). `None` = use scale default (1.0).
pub grid_line_width: Option<f64>,
pub theme: Theme,
pub palette: Option<Palette>,
pub x_tick_format: TickFormat,
pub y_tick_format: TickFormat,
pub colorbar_tick_format: TickFormat,
pub y2_range: Option<(f64, f64)>,
pub data_y2_range: Option<(f64, f64)>,
pub y2_label: Option<String>,
pub log_y2: bool,
pub y2_tick_format: TickFormat,
pub suppress_y2_ticks: bool,
pub x_datetime: Option<DateTimeAxis>,
pub y_datetime: Option<DateTimeAxis>,
pub x_tick_rotate: Option<f64>,
/// When true, the computed axis range snaps to the tick boundary that just
/// contains the data — no extra breathing-room step is added. Useful for
/// cases like `TickFormat::Percent` where you want the axis to stop exactly
/// at 100 % rather than extending to 110 % or 120 %.
pub clamp_axis: bool,
/// Like `clamp_axis` but only for the y-axis. Set automatically by
/// `auto_from_plots` when all histograms in the plot list are normalized
/// (so that the y-axis tops out at exactly 1.0, not 1.1).
pub clamp_y_axis: bool,
/// Bin width detected from histogram data by `auto_from_plots`. When set,
/// the x-axis range is taken from the raw data range (no rounding outward)
/// and ticks are generated as integer multiples of this width so they fall
/// exactly on bar edges. `None` when no histograms are present or when
/// multiple overlapping histograms have differing bin widths.
pub x_bin_width: Option<f64>,
/// Number of character rows in the terminal target. When set, legend
/// `line_height` is quantised to an integer multiple of the cell height so
/// that every legend entry lands on its own terminal row with no gaps.
pub term_rows: Option<u32>,
/// Override the lower bound of the x-axis after auto-ranging.
pub x_axis_min: Option<f64>,
/// Override the upper bound of the x-axis after auto-ranging.
pub x_axis_max: Option<f64>,
/// Override the lower bound of the y-axis after auto-ranging.
pub y_axis_min: Option<f64>,
/// Override the upper bound of the y-axis after auto-ranging.
pub y_axis_max: Option<f64>,
/// Explicit major tick step for the x-axis. Skips auto computation when set.
pub x_tick_step: Option<f64>,
/// Explicit major tick step for the y-axis. Skips auto computation when set.
pub y_tick_step: Option<f64>,
/// Sub-intervals between major ticks (e.g. 5 → 4 minor marks per gap).
pub minor_ticks: Option<u32>,
/// Draw faint gridlines at minor tick positions (requires `minor_ticks`).
pub show_minor_grid: bool,
/// Pixel offset applied to the x-axis label after auto-positioning: `(dx, dy)`.
/// Positive dx shifts right; positive dy shifts down.
pub x_label_offset: (f64, f64),
/// Pixel offset applied to the y-axis label after auto-positioning: `(dx, dy)`.
/// Positive dx shifts right (away from the left edge); positive dy shifts down.
pub y_label_offset: (f64, f64),
/// Pixel offset applied to the y2-axis label after auto-positioning: `(dx, dy)`.
/// Positive dx shifts right (further from the right axis); positive dy shifts down.
pub y2_label_offset: (f64, f64),
/// Uniform scale factor for all plot chrome (font sizes, margins, tick marks,
/// legend geometry, arrow sizes). Canvas `width`/`height` are not affected.
/// Default: 1.0. Set via `with_scale(f)`.
pub scale: f64,
/// Angular position (in degrees) at which r-axis (ring) labels are drawn on
/// polar plots. Default: midpoint between the 0° spoke and the first clockwise
/// spoke (`360 / (theta_divisions * 2)`). Override to avoid overlap with
/// custom theta tick labels.
pub polar_r_label_angle: Option<f64>,
/// When `true`, the SVG backend injects interactive CSS, JavaScript, and
/// `data-*` attributes so the chart responds to hover, click, and search.
pub interactive: bool,
/// When `true`, enforce equal scaling on both axes so that one data unit
/// spans the same number of pixels horizontally and vertically. Circles
/// rendered with equal aspect look circular; without it they look like
/// ellipses whenever the x and y data ranges differ.
pub equal_aspect: bool,
/// When `true` (default), the y-axis lower bound is clamped to 0 when all
/// data values are non-negative. Set to `false` for plot types where zero
/// has no special meaning (line, scatter, box, etc.) so the axis fits the
/// data range instead. Set automatically by `auto_from_plots`; can also be
/// overridden manually.
pub anchor_y_zero: bool,
/// Number of vertical stagger tiers reserved above a BrickPlot notation track.
/// Set automatically by `auto_from_plots` when a `BrickPlot` with `notations`
/// is present. `0` = no extra space.
pub brick_notation_tiers: usize,
/// Word-wrap the plot title at this many characters; `None` disables wrapping.
pub title_wrap: Option<usize>,
/// Word-wrap the x-axis label at this many characters; `None` disables wrapping.
pub x_label_wrap: Option<usize>,
/// Word-wrap the y-axis label at this many characters; `None` disables wrapping.
pub y_label_wrap: Option<usize>,
/// Word-wrap the secondary y-axis label at this many characters; `None` disables wrapping.
pub y2_label_wrap: Option<usize>,
/// Word-wrap legend labels and titles at this many characters; `None` disables wrapping.
pub legend_wrap: Option<usize>,
/// Extra right-margin pixels reserved for HorizonPlot row annotations
/// (value labels and sign-color indicators). Set automatically by
/// `auto_from_plots`; zero when no annotations are requested.
pub horizon_right_annot_px: f64,
/// Extra right-margin pixels reserved for GanttPlot milestone/outside-bar
/// labels drawn post-clip. Set automatically by `auto_from_plots`.
pub gantt_right_annot_px: f64,
}
impl Layout {
pub fn new(x_range: (f64, f64), y_range: (f64, f64)) -> Self {
Self {
width: None,
height: None,
x_range,
y_range,
data_x_range: None,
data_y_range: None,
ticks: 5,
show_grid: true,
x_label: None,
y_label: None,
title: None,
x_categories: None,
y_categories: None,
show_legend: false,
show_colorbar: false,
legend_position: LegendPosition::OutsideRightTop,
legend_width: 120.0,
legend_entries: None,
legend_title: None,
legend_groups: None,
legend_box: true,
legend_height: None,
legend_entry_count: 0,
legend_max_label_chars: 0,
stats_entries: Vec::new(),
stats_title: None,
stats_position: LegendPosition::InsideTopLeft,
stats_box: true,
log_x: false,
log_y: false,
annotations: Vec::new(),
reference_lines: Vec::new(),
shaded_regions: Vec::new(),
suppress_x_ticks: false,
suppress_y_ticks: false,
font_family: None,
title_size: 18,
label_size: 14,
tick_size: 12,
body_size: 12,
axis_line_width: None,
tick_width: None,
tick_length: None,
grid_line_width: None,
theme: Theme::default(),
palette: None,
x_tick_format: TickFormat::Auto,
y_tick_format: TickFormat::Auto,
colorbar_tick_format: TickFormat::Auto,
y2_range: None,
data_y2_range: None,
y2_label: None,
log_y2: false,
y2_tick_format: TickFormat::Auto,
suppress_y2_ticks: false,
x_datetime: None,
y_datetime: None,
x_tick_rotate: None,
clamp_axis: false,
clamp_y_axis: false,
x_bin_width: None,
term_rows: None,
x_axis_min: None,
x_axis_max: None,
y_axis_min: None,
y_axis_max: None,
x_tick_step: None,
y_tick_step: None,
minor_ticks: None,
show_minor_grid: false,
x_label_offset: (0.0, 0.0),
y_label_offset: (0.0, 0.0),
y2_label_offset: (0.0, 0.0),
scale: 1.0,
polar_r_label_angle: None,
interactive: false,
equal_aspect: false,
anchor_y_zero: true,
brick_notation_tiers: 0,
title_wrap: None,
x_label_wrap: None,
y_label_wrap: None,
y2_label_wrap: None,
legend_wrap: None,
horizon_right_annot_px: 0.0,
gantt_right_annot_px: 0.0,
}
}
pub fn auto_from_data(data: &[f64], x_range: std::ops::Range<f64>) -> Self {
let y_min = 0.0;
let y_max = data.iter().cloned().fold(0.0, f64::max);
Layout::new((x_range.start, x_range.end), (y_min, y_max * 1.05))
}
/// Build a `Layout` whose axis ranges are derived automatically from the
/// bounding boxes of all plots.
///
/// **y-axis zero anchor** — for plots where zero is a meaningful baseline
/// (bar, histogram, stacked area, waterfall, lollipop, density, ridgeline,
/// ECDF, survival, ROC, PR, funnel, streamgraph) the y-axis is anchored at
/// 0 when all data is non-negative. For all other plot types (line, scatter,
/// box, violin, etc.) the axis fits the data range with a small breathing
/// margin. The computed [`Layout::anchor_y_zero`] field records which
/// behaviour was chosen and can be overridden after the fact.
pub fn auto_from_plots(plots: &[Plot]) -> Self {
let mut x_min = f64::INFINITY;
let mut x_max = f64::NEG_INFINITY;
let mut y_min = f64::INFINITY;
let mut y_max = f64::NEG_INFINITY;
let mut x_labels = None;
let mut y_labels = None;
let mut has_legend: bool = false;
let mut has_colorbar: bool = false;
let mut has_manhattan: bool = false;
let mut has_polar: bool = false;
// Tracks whether any plot type requires the y-axis to be anchored at 0
// (bar, histogram, stacked-area, etc.). When false, the axis fits the data.
let mut anchor_y_zero: bool = false;
let mut max_label_len: usize = 0;
let mut legend_entry_count: usize = 0;
let mut brick_has_notations: bool = false;
let mut pyramid_normalize: Option<bool> = None;
let mut horizon_right_annot_px: f64 = 0.0;
let mut gantt_right_annot_px: f64 = 0.0;
let mut bump_series_label_px: f64 = 0.0;
let mut bump_n_time: usize = 0;
for plot in plots {
if let Some(((xmin, xmax), (ymin, ymax))) = plot.bounds() {
x_min = x_min.min(xmin);
x_max = x_max.max(xmax);
y_min = y_min.min(ymin);
y_max = y_max.max(ymax);
}
if matches!(
plot,
Plot::Bar(_)
| Plot::Histogram(_)
| Plot::StackedArea(_)
| Plot::Waterfall(_)
| Plot::Lollipop(_)
| Plot::Ridgeline(_)
| Plot::Ecdf(_)
| Plot::Survival(_)
| Plot::Roc(_)
| Plot::Pr(_)
| Plot::Funnel(_)
| Plot::Streamgraph(_)
) {
anchor_y_zero = true;
}
if let Plot::Density(dp) = plot {
if !dp.fit_y {
anchor_y_zero = true;
}
}
if let Plot::Strip(sp) = plot {
let labels = sp.groups.iter().map(|g| g.label.clone()).collect();
x_labels = Some(labels);
if let Some(ref label) = sp.legend_label {
has_legend = true;
if sp.group_colors.is_some() {
// Legend entries are the per-group labels (see collect_legend_entries)
for g in &sp.groups {
max_label_len = max_label_len.max(g.label.len());
}
} else {
max_label_len = max_label_len.max(label.len());
}
}
}
if let Plot::Box(bp) = plot {
let labels = bp
.groups
.iter()
.map(|g| g.label.clone())
.collect::<Vec<_>>();
x_labels = Some(labels);
}
if let Plot::Violin(vp) = plot {
let labels = vp
.groups
.iter()
.map(|g| g.label.clone())
.collect::<Vec<_>>();
x_labels = Some(labels);
}
if let Plot::Raincloud(rp) = plot {
let labels = rp
.groups
.iter()
.map(|g| g.label.clone())
.collect::<Vec<_>>();
x_labels = Some(labels);
if rp.legend_label.is_some() {
has_legend = true;
for g in &rp.groups {
max_label_len = max_label_len.max(g.label.len());
}
}
}
if let Plot::Waterfall(wp) = plot {
let labels = wp.bars.iter().map(|b| b.label.clone()).collect::<Vec<_>>();
x_labels = Some(labels);
}
if let Plot::Bar(bp) = plot {
let labels = bp
.groups
.iter()
.map(|g| g.label.clone())
.collect::<Vec<_>>();
x_labels = Some(labels);
if let Some(ref ll) = bp.legend_label {
has_legend = true;
for l in ll {
max_label_len = max_label_len.max(l.len());
}
}
}
if let Plot::Scatter(sp) = plot {
if let Some(ref label) = sp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Line(lp) = plot {
if let Some(ref label) = lp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Series(sp) = plot {
if let Some(ref label) = sp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Brick(bp) = plot {
// Reverse labels so that names[0] appears at the TOP of the plot.
// map_y maps larger y-data values to the top; row 0 is rendered at
// y_data = [N-1, N], so the axis label for names[0] must be at y = N-0.5.
let labels: Vec<String> = bp.names.iter().rev().cloned().collect();
y_labels = Some(labels);
has_legend = true;
if let Some(ref template) = bp.template {
legend_entry_count += template.len();
}
if let Some(ref motifs) = bp.motifs {
// +1 when mark_primary is set: the primary entry gets a trailing '*'
let mark_bonus = if bp.mark_primary { 1 } else { 0 };
for v in motifs.values() {
max_label_len = max_label_len.max(v.len() + mark_bonus);
}
}
// Reserve vertical space for per-block notation labels when enabled.
if bp
.notations
.as_ref()
.is_some_and(|n| n.iter().any(|o| o.is_some()))
{
brick_has_notations = true;
}
}
if let Plot::Pie(pp) = plot {
if let Some(ref _label) = pp.legend_label {
has_legend = true;
let total: f64 = pp.slices.iter().map(|s| s.value).sum();
for slice in &pp.slices {
let entry_label = if pp.show_percent {
let pct = slice.value / total * 100.0;
format!("{} ({:.1}%)", slice.label, pct)
} else {
slice.label.clone()
};
max_label_len = max_label_len.max(entry_label.len());
}
}
}
if matches!(plot, Plot::Heatmap(_) | Plot::Histogram2d(_))
|| matches!(plot, Plot::Hexbin(hb) if hb.show_colorbar)
|| matches!(plot, Plot::Treemap(tm) if matches!(tm.color_mode, crate::plot::treemap::TreemapColorMode::ByValue(_)) && tm.show_colorbar)
|| matches!(plot, Plot::Sunburst(sb) if matches!(sb.color_mode, crate::plot::sunburst::SunburstColorMode::ByValue(_)) && sb.show_colorbar)
{
has_colorbar = true;
}
if let Plot::Volcano(vp) = plot {
if vp.legend_label.is_some() {
has_legend = true;
max_label_len = max_label_len.max(4); // "Down"
}
}
if let Plot::Manhattan(mp) = plot {
if mp.legend_label.is_some() {
has_legend = true;
max_label_len = max_label_len.max(12); // "Genome-wide"
}
has_manhattan = true;
}
if let Plot::DotPlot(dp) = plot {
x_labels = Some(dp.x_categories.clone());
// Reverse so y_cat[0] appears at the TOP (map_y maps larger values to top)
y_labels = Some(dp.y_categories.iter().rev().cloned().collect());
let dot_has_both = dp.size_label.is_some() && dp.color_legend_label.is_some();
// Colorbar handled by stacked renderer when both are present
if dp.color_legend_label.is_some() && !dot_has_both {
has_colorbar = true;
}
if dp.size_label.is_some() {
has_legend = true;
// Entry labels are short numbers like "100.0" (5 chars)
max_label_len = max_label_len.max(5);
}
}
if let Plot::StackedArea(sa) = plot {
for label in sa.labels.iter().flatten() {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Streamgraph(sg) = plot {
if sg.legend_label.is_some() {
for label in sg.labels.iter().flatten() {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
}
if let Plot::DicePlot(dp) = plot {
x_labels = Some(dp.x_categories.clone());
// Reverse so y_cat[0] appears at the TOP
y_labels = Some(dp.y_categories.iter().rev().cloned().collect());
if dp.fill_legend_label.is_some() {
has_colorbar = true;
}
if !dp.dot_legend.is_empty() {
has_legend = true;
for (label, _) in &dp.dot_legend {
max_label_len = max_label_len.max(label.len());
}
}
if let Some(ref title) = dp.position_legend_label {
has_legend = true;
// Title is centre-anchored — needs same headroom as entry labels.
max_label_len = max_label_len.max(title.len());
for label in &dp.category_labels {
max_label_len = max_label_len.max(label.len());
}
}
if let Some(ref title) = dp.size_legend_label {
has_legend = true;
max_label_len = max_label_len.max(title.len()).max(5);
}
for label in &dp.y_categories {
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Candlestick(cp) = plot {
let continuous = cp.candles.iter().any(|c| c.x.is_some());
if !continuous {
let labels = cp.candles.iter().map(|c| c.label.clone()).collect();
x_labels = Some(labels);
}
if let Some(ref label) = cp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Contour(cp) = plot {
if cp.filled {
has_colorbar = true;
}
if let Some(ref label) = cp.legend_label {
if !cp.filled {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
}
if let Plot::Chord(cp) = plot {
if cp.legend_label.is_some() {
has_legend = true;
for label in &cp.labels {
max_label_len = max_label_len.max(label.len());
}
}
}
if let Plot::Sankey(sp) = plot {
if sp.legend_label.is_some() {
has_legend = true;
for node in &sp.nodes {
max_label_len = max_label_len.max(node.label.len());
}
}
}
if let Plot::Radar(rp) = plot {
if rp.show_legend {
has_legend = true;
for s in &rp.series {
if let Some(ref lbl) = s.label {
max_label_len = max_label_len.max(lbl.len());
}
}
for r in &rp.references {
if let Some(ref lbl) = r.label {
max_label_len = max_label_len.max(lbl.len());
}
}
}
}
if let Plot::Network(net) = plot {
if net.legend_label.is_some() {
has_legend = true;
// Measure group labels, or node labels if no groups.
let mut seen_groups: Vec<&str> = Vec::new();
for node in &net.nodes {
if let Some(ref g) = node.group {
if !seen_groups.contains(&g.as_str()) {
max_label_len = max_label_len.max(g.len());
seen_groups.push(g);
}
}
}
if seen_groups.is_empty() {
for node in &net.nodes {
max_label_len = max_label_len.max(node.label.len());
}
}
}
}
if let Plot::PhyloTree(t) = plot {
if t.legend_label.is_some() {
has_legend = true;
for (node_id, _) in &t.clade_colors {
let llen = t.nodes[*node_id].label.as_deref().unwrap_or("").len();
max_label_len = max_label_len.max(llen);
}
}
}
if let Plot::Synteny(sp) = plot {
if sp.legend_label.is_some() {
has_legend = true;
for seq in &sp.sequences {
max_label_len = max_label_len.max(seq.label.len());
}
}
}
if let Plot::Density(dp) = plot {
if let Some(ref label) = dp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Lollipop(lp) = plot {
if let Some(ref label) = lp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Survival(sp) = plot {
if sp.legend_label.is_some() {
has_legend = true;
for g in &sp.groups {
max_label_len = max_label_len.max(g.label.len());
}
}
}
if let Plot::Roc(roc) = plot {
if roc.legend_label.is_some() {
has_legend = true;
for g in &roc.groups {
// Label + " (AUC = 0.xxx)" suffix = 16 chars
max_label_len = max_label_len.max(g.label.len() + 16);
}
}
}
if let Plot::Pr(pr) = plot {
if pr.legend_label.is_some() {
has_legend = true;
for g in &pr.groups {
// Label + " (AUC-PR = 0.xxx)" suffix = 18 chars
max_label_len = max_label_len.max(g.label.len() + 18);
}
}
}
if let Plot::Slope(sp) = plot {
// Reversed: points[0] at top; y=n is the largest y value (maps to top)
y_labels = Some(sp.points.iter().rev().map(|p| p.label.clone()).collect());
if sp.legend_label.is_some() {
has_legend = true;
if sp.color_by_direction {
// "Decrease" is the longest direction label (8 chars)
max_label_len = max_label_len.max(8);
} else if let Some(ref gc) = sp.group_colors {
// Per-group: use point labels
let _ = gc;
for p in &sp.points {
max_label_len = max_label_len.max(p.label.len());
}
} else {
max_label_len = max_label_len.max(5);
}
}
}
if let Plot::Forest(fp) = plot {
// Reversed: row[0] at top, map_y maps larger values to top
y_labels = Some(fp.rows.iter().rev().map(|r| r.label.clone()).collect());
if let Some(ref label) = fp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
}
if let Plot::Ridgeline(rp) = plot {
// Reversed: group[0] at top, map_y maps larger values to top
y_labels = Some(rp.groups.iter().rev().map(|g| g.label.clone()).collect());
if rp.show_legend {
has_legend = true;
for g in &rp.groups {
max_label_len = max_label_len.max(g.label.len());
}
}
}
if let Plot::Bump(bp) = plot {
let n = bp.total_series_count();
let n_time = bp.n_time_points();
// x_categories: one per time point (labels or "1", "2", ...)
let x_cats: Vec<String> = if !bp.x_labels.is_empty() {
bp.x_labels.clone()
} else {
(1..=n_time).map(|i| i.to_string()).collect()
};
x_labels = Some(x_cats);
// y_categories: rank labels with rank-1 at top.
// axis.rs draws y_categories[i] at y_val=i+1; rank r is plotted at y_data=n+1-r.
// So y_categories[i] at y_val=i+1 corresponds to rank n-i → label "n-i".
y_labels = Some((1..=n).rev().map(|r| r.to_string()).collect());
if bp.legend {
has_legend = true;
let series = bp.resolved_series();
for s in &series {
max_label_len = max_label_len.max(s.name.len());
}
}
if bp.show_series_labels {
let series = bp.resolved_series();
let max_chars = series.iter().map(|s| s.name.len()).max().unwrap_or(0);
let label_px = max_chars as f64 * 7.0 + bp.dot_radius + 10.0;
bump_series_label_px = bump_series_label_px.max(label_px);
bump_n_time = bump_n_time.max(n_time);
}
}
if let Plot::Polar(pp) = plot {
has_polar = true;
if pp.show_legend {
has_legend = true;
for s in &pp.series {
if let Some(ref lbl) = s.label {
max_label_len = max_label_len.max(lbl.len());
}
}
}
}
if let Plot::Ternary(tp) = plot {
if tp.show_legend {
has_legend = true;
for g in tp.unique_groups() {
max_label_len = max_label_len.max(g.len());
}
}
}
if let Plot::Venn(vp) = plot {
if vp.legend_label.is_some() {
has_legend = true;
for s in &vp.sets {
max_label_len = max_label_len.max(s.label.len());
}
}
}
if let Plot::Parallel(pp) = plot {
if pp.legend_label.is_some() {
has_legend = true;
for g in pp.groups() {
max_label_len = max_label_len.max(g.len());
}
}
}
if let Plot::Mosaic(mp) = plot {
if mp.legend_label.is_some() {
has_legend = true;
for row in mp.effective_row_order() {
max_label_len = max_label_len.max(row.len());
}
}
}
if let Plot::Ecdf(ep) = plot {
if ep.legend_label.is_some() {
has_legend = true;
for g in &ep.groups {
max_label_len = max_label_len.max(g.label.len());
}
}
}
if let Plot::QQ(qp) = plot {
if qp.legend_label.is_some() {
has_legend = true;
for g in &qp.groups {
max_label_len = max_label_len.max(g.label.len());
}
}
}
// 3D plot types: check for legend label and z-colormap
let (legend_3d, cmap_3d) = match plot {
Plot::Scatter3D(sp) => (sp.legend_label.as_deref(), sp.z_colormap.is_some()),
Plot::Surface3D(sp) => (sp.legend_label.as_deref(), sp.z_colormap.is_some()),
_ => (None, false),
};
if let Some(label) = legend_3d {
has_legend = true;
max_label_len = max_label_len.max(label.len());
}
if cmap_3d {
has_colorbar = true;
}
if let Plot::Funnel(fp) = plot {
if fp.legend_label.is_some() {
has_legend = true;
for s in &fp.stages {
max_label_len = max_label_len.max(s.label.len());
}
}
}
if let Plot::Rose(rp) = plot {
if rp.legend_label.is_some() {
has_legend = true;
for s in &rp.series {
max_label_len = max_label_len.max(s.name.len());
}
}
}
if let Plot::Calendar(cp) = plot {
if cp.show_legend {
has_legend = true;
}
}
if let Plot::Pyramid(pp) = plot {
// y-categories: age groups, bottom (index 0) → top (last)
y_labels = Some(pp.age_labels());
// Record normalization flag for post-loop tick format setup
pyramid_normalize = Some(pp.normalize);
if pp.show_legend {
has_legend = true;
if pp.series.len() <= 1 {
max_label_len = max_label_len
.max(pp.left_label.len())
.max(pp.right_label.len());
} else {
for s in &pp.series {
max_label_len = max_label_len.max(s.label.len());
}
}
}
}
if let Plot::Horizon(hp) = plot {
if !hp.series.is_empty() {
// y_categories: series[0] at top → reversed list
y_labels = Some(hp.series.iter().rev().map(|s| s.label.clone()).collect());
if hp.show_legend {
has_legend = true;
for s in &hp.series {
max_label_len = max_label_len.max(s.label.len());
}
}
if hp.show_value_labels || hp.show_sign_colors {
// Reserve right-margin space for per-row annotations.
// Estimate: sign char ("+"/"-") + up to 7-digit value, at tick_size width.
// We don't know tick_size here yet (it's scale-dependent), so use a
// pixel constant; the ComputedLayout scale factor is applied later.
horizon_right_annot_px = 68.0;
}
}
}
if let Plot::Gantt(gp) = plot {
if !gp.tasks.is_empty() {
// y_categories: row[0] at top → reversed list (bottom-to-top)
let labels_top_to_bottom = gp.row_labels();
y_labels = Some(labels_top_to_bottom.into_iter().rev().collect());
for label in gp.row_labels() {
max_label_len = max_label_len.max(label.len());
}
if let Some(ref lbl) = gp.legend_label {
has_legend = true;
max_label_len = max_label_len.max(lbl.len());
}
// Reserve right margin for milestone labels and outside-bar labels
// drawn post-clip. Estimate: font_size=11, char_w≈6.6px, gap+diamond.
if gp.show_labels {
let max_right_label_chars =
gp.tasks.iter().map(|t| t.label.len()).max().unwrap_or(0);
let needed = max_right_label_chars as f64 * 6.6 + gp.milestone_size + 14.0;
gantt_right_annot_px = gantt_right_annot_px.max(needed);
}
}
}
if let Plot::Waffle(wp) = plot {
if wp.legend_label.is_some() {
has_legend = true;
let total: f64 = wp.categories.iter().map(|c| c.value).sum();
let n_cells = wp.rows * wp.cols;
// Use largest-remainder counts to compute annotated label lengths
let counts = crate::render::render::waffle_largest_remainder(
&wp.categories.iter().map(|c| c.value).collect::<Vec<_>>(),
n_cells,
);
for (i, cat) in wp.categories.iter().enumerate() {
let label = waffle_legend_label(cat, i, total, &counts, wp);
max_label_len = max_label_len.max(label.len());
}
}
}
}
// Extend x bounds for BumpPlot endpoint series labels so they render inside
// the clip zone. Uses the default auto plot_width (600 px from from_layout)
// to compute the needed data-unit padding p on each side, solving:
// (0.5 + p) / (n + 2p) * 600 >= label_px
// → p = (label_px * n − 300) / (600 − 2 * label_px)
if bump_series_label_px > 0.0 && bump_n_time > 0 {
let l = bump_series_label_px;
let n = bump_n_time as f64;
let auto_w = 600.0_f64;
let denom = auto_w - 2.0 * l;
let p = if denom > 0.0 {
((l * n - 0.5 * auto_w) / denom).max(0.0)
} else {
n * 0.5 // label wider than half the plot — fallback
};
if p > 0.0 {
x_min = x_min.min(0.5 - p);
x_max = x_max.max(bump_n_time as f64 + 0.5 + p);
}
}
// Save raw data range before padding (log scale needs it)
let raw_x = (x_min, x_max);
let raw_y = (y_min, y_max);
// Add a small margin so data points don't land exactly on axis edges.
// Category-based plots (bar, box, violin, brick) already have built-in
// padding in their bounds(), so only pad continuous-axis plots.
// Grid-based plots (heatmap, histogram2d) also skip padding.
//
// Strategy: add 1% of the data span to max (and symmetrically to negative
// min). This is just enough to push an exact tick-boundary value above the
// boundary so that auto_nice_range's ceil moves it up by exactly one step,
// avoiding the old flat "+1" which could expand a 0-1 range to 0-2.
let has_x_cats = x_labels.is_some();
let has_y_cats = y_labels.is_some();
if !has_x_cats && !has_colorbar && x_max > x_min {
let x_span = x_max - x_min;
if x_min > 0.0 && x_min > x_span {
// Large positive offset (e.g. years, genomic positions): padding
// relative to the absolute value would push the axis to start at 0.
// Instead pad by a fraction of the data range.
let pad = x_span * 0.05;
x_min -= pad;
x_max += pad;
} else {
x_max += x_span * 0.01;
if x_min >= 0.0 {
x_min = 0.0;
} else {
x_min -= x_span * 0.01;
}
}
}
if !has_y_cats && !has_colorbar && y_max > y_min {
let y_span = y_max - y_min;
y_max += y_span * 0.01;
if y_min >= 0.0 && anchor_y_zero {
y_min = 0.0;
} else if y_min >= 0.0 {
// Fit-to-data: add breathing room but don't cross into negative territory.
y_min = (y_min - y_span * 0.01).max(0.0);
} else {
y_min -= y_span * 0.01;
}
}
let mut layout = Self::new((x_min, x_max), (y_min, y_max));
layout.anchor_y_zero = anchor_y_zero;
layout.data_x_range = Some(raw_x);
layout.data_y_range = Some(raw_y);
layout.horizon_right_annot_px = horizon_right_annot_px;
layout.gantt_right_annot_px = gantt_right_annot_px;
if brick_has_notations {
layout.brick_notation_tiers = 4; // matches N_TIERS in add_brickplot
}
if let Some(labels) = x_labels {
layout = layout.with_x_categories(labels);
}
if let Some(labels) = y_labels {
layout = layout.with_y_categories(labels);
}
// DotPlot with both size legend + colorbar uses a single stacked column
let has_dot_stacked = plots.iter().any(|p| {
if let Plot::DotPlot(dp) = p {
dp.size_label.is_some() && dp.color_legend_label.is_some()
} else {
false
}
});
if has_legend {
layout = layout.with_show_legend();
layout.legend_entry_count = legend_entry_count;
layout.legend_max_label_chars = max_label_len;
let dynamic_width = max_label_len as f64 * 8.0 + 40.0;
layout.legend_width = dynamic_width.max(80.0);
// Position legend die face needs 3 cells wide — ensure legend_width fits.
for plot in plots.iter() {
if let crate::render::plots::Plot::DicePlot(dp) = plot {
if dp.position_legend_label.is_some() {
let max_cat = dp
.category_labels
.iter()
.map(|l| l.len())
.max()
.unwrap_or(3);
let die_cell_w = (max_cat as f64 * 5.5 + 10.0).max(24.0);
layout.legend_width = layout.legend_width.max(3.0 * die_cell_w + 20.0);
}
}
}
}
if has_dot_stacked {
// Single column wide enough for the stacked colorbar + size-legend
layout.legend_width = 75.0;
}
if has_colorbar {
layout.show_colorbar = true;
}
if has_manhattan {
// Suppress numeric x tick labels and tick marks; chromosome names are drawn by add_manhattan.
layout.x_tick_format = TickFormat::Custom(Arc::new(|_| String::new()));
layout.suppress_x_ticks = true;
// Disable horizontal grid lines so threshold lines pop out clearly.
layout.show_grid = false;
}
if has_polar {
// Use degrees as default tick format for polar plots.
layout.x_tick_format = TickFormat::Degree;
}
// UpSet plots manage their own axes; disable the standard grid.
if plots.iter().any(|p| matches!(p, Plot::UpSet(_))) {
layout.show_grid = false;
}
// Population pyramid: absolute-value x-tick format
if let Some(is_pct) = pyramid_normalize {
layout.x_tick_format = TickFormat::Custom(Arc::new(move |v| {
let a = v.abs();
if is_pct {
if a == 0.0 {
"0%".to_string()
} else if a >= 10.0 {
format!("{:.0}%", a)
} else {
format!("{:.1}%", a)
}
} else if a == 0.0 {
"0".to_string()
} else if a >= 1_000_000.0 {
format!("{:.1}M", a / 1_000_000.0)
} else if a >= 1_000.0 {
format!("{:.1}k", a / 1_000.0)
} else if a >= 10.0 {
format!("{:.0}", a)
} else {
format!("{:.1}", a)
}
}));
}
// For normalized histograms the y range is always [0, 1]. Clamp the
// y-axis so it stops at exactly 1.0 rather than rounding up to 1.1.
// Only activate when every histogram in the list is normalized (mixing
// normalized with un-normalized histograms produces a y_max that is a
// count, not 1.0, so clamping is unnecessary there).
let any_hist = plots.iter().any(|p| matches!(p, Plot::Histogram(_)));
let all_normalized = plots.iter().all(|p| match p {
Plot::Histogram(h) => h.normalize,
_ => true, // non-histogram plots don't vote
});
if any_hist && all_normalized {
layout.clamp_y_axis = true;
}
// Collect bin widths from all histograms. When every histogram shares
// the same bin width (the common case, including overlapping histograms
// with a shared range), store it so the axis code can generate ticks
// that fall exactly on bar edges.
if any_hist {
let bin_widths: Vec<f64> = plots
.iter()
.filter_map(|p| {
if let Plot::Histogram(h) = p {
if let Some((edges, _)) = &h.precomputed {
if edges.len() >= 2 {
let bw = edges[1] - edges[0];
let uniform = edges
.windows(2)
.all(|w| (w[1] - w[0] - bw).abs() < 1e-9 * bw.abs().max(1e-10));
if uniform {
return Some(bw);
}
}
return None;
}
h.range.map(|r| (r.1 - r.0) / h.bins as f64)
} else {
None
}
})
.collect();
if !bin_widths.is_empty() {
let first = bin_widths[0];
if bin_widths
.iter()
.all(|&bw| (bw - first).abs() < 1e-9 * first.abs().max(1e-10))
{
layout.x_bin_width = Some(first);
}
}
}
// BrickPlot::with_row_height — auto-size canvas height so each row is
// exactly `row_height_px` pixels tall. We compute the real margin
// overhead from ComputedLayout (margins do not depend on canvas size)
// rather than using a fixed estimate, so the result is exact.
// Only the first BrickPlot with `row_height_px` takes effect.
for plot in plots.iter() {
if let Plot::Brick(bp) = plot {
if let Some(rh) = bp.row_height_px {
let n = bp.num_rows();
if n > 0 {
let cl = ComputedLayout::from_layout(&layout);
let overhead = cl.margin_top + cl.margin_bottom;
layout.height = Some(rh * n as f64 + overhead);
break;
}
}
}
}
// WafflePlot — auto-size canvas height to keep cells square.
// For wide grids (cols >> rows) the default 450px plot height would leave
// a large blank gap above and below the grid; here we shrink the canvas to
// match the height that the width-constrained cell size implies.
// Only applied when the user has not already set an explicit height.
if layout.height.is_none() {
for plot in plots.iter() {
if let Plot::Waffle(wp) = plot {
if wp.rows > 0 && wp.cols > 0 {
let cl = ComputedLayout::from_layout(&layout);
let plot_w = cl.plot_width();
// Cell size is constrained by width when cols > rows*(plot_w/plot_h)
let cell_px = plot_w / wp.cols as f64;
let natural_grid_h = cell_px * wp.rows as f64;
let default_plot_h = cl.plot_height();
// Only shrink — never expand beyond the default canvas height
if natural_grid_h < default_plot_h {
let overhead = cl.margin_top + cl.margin_bottom;
// Add a modest bottom padding so the unit label (if any)
// and the grid itself aren't flush against the canvas edge.
let bottom_pad = if wp.unit_label.is_some() { 28.0 } else { 12.0 };
layout.height = Some(natural_grid_h + overhead + bottom_pad);
}
break; // only the first WafflePlot drives the sizing
}
}
}
}
// HorizonPlot — auto-size canvas height when row_height is set.
if layout.height.is_none() {
for plot in plots.iter() {
if let Plot::Horizon(hp) = plot {
if let Some(rh) = hp.row_height {
let n = hp.series.len();
if n > 0 {
let cl = ComputedLayout::from_layout(&layout);
let overhead = cl.margin_top + cl.margin_bottom;
layout.height = Some(rh * n as f64 + overhead);
break;
}
}
}
}
}
layout
}
pub fn with_x_categories(mut self, labels: Vec<String>) -> Self {
self.x_categories = Some(labels);
self
}
pub fn with_y_categories(mut self, labels: Vec<String>) -> Self {
self.y_categories = Some(labels);
self
}
pub fn with_width(mut self, width: f64) -> Self {
self.width = Some(width);
self
}
pub fn with_height(mut self, height: f64) -> Self {
self.height = Some(height);
self
}
pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
self.title = Some(title.into());
self
}
pub fn with_x_label<S: Into<String>>(mut self, label: S) -> Self {
self.x_label = Some(label.into());
self
}
pub fn with_y_label<S: Into<String>>(mut self, label: S) -> Self {
self.y_label = Some(label.into());
self
}
/// Shift the x-axis label by `(dx, dy)` pixels from its auto-computed position.
/// Positive `dx` moves right; positive `dy` moves down.
pub fn with_x_label_offset(mut self, dx: f64, dy: f64) -> Self {
self.x_label_offset = (dx, dy);
self
}
/// Shift the y-axis label by `(dx, dy)` pixels from its auto-computed position.
/// Positive `dx` moves right (away from the left edge); positive `dy` moves down.
pub fn with_y_label_offset(mut self, dx: f64, dy: f64) -> Self {
self.y_label_offset = (dx, dy);
self
}
pub fn with_ticks(mut self, ticks: usize) -> Self {
self.ticks = ticks;
self
}
pub fn with_show_grid(mut self, show: bool) -> Self {
self.show_grid = show;
self
}
fn with_show_legend(mut self) -> Self {
self.show_legend = true;
self
}
pub fn with_legend_position(mut self, pos: LegendPosition) -> Self {
self.legend_position = pos;
self
}
/// Supply `Vec<LegendEntry>` directly, bypassing auto-collection from plot data.
/// Auto-sizes `legend_width` from the longest label.
pub fn with_legend_entries(mut self, entries: Vec<LegendEntry>) -> Self {
let max_chars = entries.iter().map(|e| e.label.len()).max().unwrap_or(4);
self.legend_width = (max_chars as f64 * 7.2 + 35.0).max(80.0);
self.show_legend = true;
self.legend_entries = Some(entries);
self
}
/// Place legend at absolute SVG canvas pixel coordinates; no right-margin reserved.
pub fn with_legend_at(mut self, x: f64, y: f64) -> Self {
self.legend_position = LegendPosition::Custom(x, y);
self.show_legend = true;
self
}
/// Place the legend at data-space coordinates, mapped through `map_x`/`map_y` at render time.
pub fn with_legend_at_data(mut self, x: f64, y: f64) -> Self {
self.legend_position = LegendPosition::DataCoords(x, y);
self.show_legend = true;
self
}
/// Show or hide the legend background and border box (default: `true`).
pub fn with_legend_box(mut self, show: bool) -> Self {
self.legend_box = show;
self
}
/// Set a bold title row above legend entries.
/// Also widens `legend_width` if the title text is wider than the current box.
pub fn with_legend_title<S: Into<String>>(mut self, title: S) -> Self {
let t = title.into();
// Title is centre-anchored; needs legend_width >= title_px + 10 to stay inside the box.
let needed = (t.len() as f64 * 8.5 + 10.0).max(80.0);
if needed > self.legend_width {
self.legend_width = needed;
}
self.legend_title = Some(t);
self
}
/// Add a labelled group of legend entries. Multiple calls stack; takes priority over
/// `with_legend_entries`.
/// Also widens `legend_width` to accommodate the group title and entry labels.
pub fn with_legend_group<S: Into<String>>(
mut self,
title: S,
entries: Vec<LegendEntry>,
) -> Self {
let t = title.into();
// Group title is start-anchored at legend_x+5; needs legend_width >= title_px + 10.
let needed_title = (t.len() as f64 * 7.2 + 10.0).max(80.0);
// Entry labels start at legend_x+25 (after swatch); same formula as with_legend_entries.
let max_entry_chars = entries.iter().map(|e| e.label.len()).max().unwrap_or(0);
let needed_entries = (max_entry_chars as f64 * 7.2 + 35.0).max(80.0);
self.legend_width = self.legend_width.max(needed_title).max(needed_entries);
self.legend_groups
.get_or_insert_with(Vec::new)
.push(LegendGroup { title: t, entries });
self.show_legend = true;
self
}
/// Override the auto-computed legend width. Use when labels overflow the default box.
pub fn with_legend_width(mut self, px: f64) -> Self {
self.legend_width = px;
self
}
/// Override the auto-computed legend height. Use when content overflows the default box.
pub fn with_legend_height(mut self, px: f64) -> Self {
self.legend_height = Some(px);
self
}
/// Add multiple pre-formatted lines to the stats box (e.g. `"R² = 0.847"`).
///
/// Replaces any previously set entries. Position defaults to `InsideTopLeft`.
pub fn with_stats_box(mut self, entries: Vec<impl Into<String>>) -> Self {
self.stats_entries = entries.into_iter().map(|s| s.into()).collect();
self
}
/// Append a single line to the stats box.
pub fn with_stats_entry(mut self, entry: impl Into<String>) -> Self {
self.stats_entries.push(entry.into());
self
}
/// Set the stats box position and entries in one call.
pub fn with_stats_box_at(
mut self,
position: LegendPosition,
entries: Vec<impl Into<String>>,
) -> Self {
self.stats_position = position;
self.stats_entries = entries.into_iter().map(|s| s.into()).collect();
self
}
/// Add a bold title rendered above the stats box entries.
pub fn with_stats_title(mut self, title: impl Into<String>) -> Self {
self.stats_title = Some(title.into());
self
}
/// Show or hide the background + border box around the stats entries. Default: `true`.
pub fn with_stats_box_border(mut self, show: bool) -> Self {
self.stats_box = show;
self
}
/// Set a uniform scale factor for all plot chrome.
///
/// Multiplies font sizes, margins, tick mark lengths, legend padding and swatch
/// geometry, and annotation arrow sizes. Canvas `width`/`height` are **not**
/// scaled — the user controls those independently (or relies on auto-sizing).
///
/// Useful for producing large SVG exports without manually adjusting every size
/// parameter. For raster PNG output at higher DPI, use `PngBackend`'s DPI scale
/// instead.
///
/// `TextAnnotation::font_size` and `ReferenceLine::stroke_width` are user-set
/// and are **not** auto-scaled; set them explicitly if needed.
///
/// Clamped to a minimum of 0.1 to prevent degenerate sub-pixel rendering.
pub fn with_scale(mut self, f: f64) -> Self {
self.scale = f.max(0.1);
self
}
/// Override the angle (degrees) at which r-axis labels are drawn on polar plots.
///
/// By default, labels sit at the midpoint between the 0° spoke and the first
/// clockwise spoke (`360 / (theta_divisions * 2)`). Use this to nudge them when
/// a custom theta tick label would overlap.
///
/// ```rust,no_run
/// use kuva::render::layout::Layout;
/// use kuva::plot::polar::{PolarPlot, PolarMode};
/// use kuva::render::plots::Plot;
///
/// let plot = PolarPlot::new().with_series(vec![1.0_f64], vec![0.0_f64]);
/// let plots = vec![Plot::Polar(plot)];
/// let layout = Layout::auto_from_plots(&plots)
/// .with_polar_r_label_angle(30.0); // labels at 30° from north
/// ```
pub fn with_polar_r_label_angle(mut self, deg: f64) -> Self {
self.polar_r_label_angle = Some(deg);
self
}
/// Enable SVG interactivity: hover highlighting, click-to-pin, search box,
/// coordinate readout, and legend-driven dim/highlight.
pub fn with_interactive(mut self) -> Self {
self.interactive = true;
self
}
/// Enforce equal x/y scaling so that one data unit spans the same number of
/// pixels on both axes. Circles look circular; squares look square. The
/// axis with the smaller data-to-pixel ratio is expanded symmetrically around
/// its midpoint until both ratios match. Has no effect on log-scale axes.
pub fn with_equal_aspect(mut self) -> Self {
self.equal_aspect = true;
self
}
/// Word-wrap all text elements (title, axis labels, legend) at `max_chars`
/// characters. Acts as a fallback: per-element overrides (`with_title_wrap`,
/// `with_legend_wrap`, etc.) always take precedence regardless of call order.
pub fn with_wrap(mut self, max_chars: usize) -> Self {
let v = if max_chars > 0 { Some(max_chars) } else { None };
if self.title_wrap.is_none() {
self.title_wrap = v;
}
if self.x_label_wrap.is_none() {
self.x_label_wrap = v;
}
if self.y_label_wrap.is_none() {
self.y_label_wrap = v;
}
if self.y2_label_wrap.is_none() {
self.y2_label_wrap = v;
}
if self.legend_wrap.is_none() {
self.legend_wrap = v;
}
self
}
/// Word-wrap the plot title at `max_chars` characters.
pub fn with_title_wrap(mut self, max_chars: usize) -> Self {
self.title_wrap = if max_chars > 0 { Some(max_chars) } else { None };
self
}
/// Word-wrap the x-axis label at `max_chars` characters.
pub fn with_x_label_wrap(mut self, max_chars: usize) -> Self {
self.x_label_wrap = if max_chars > 0 { Some(max_chars) } else { None };
self
}
/// Word-wrap the y-axis label at `max_chars` characters.
pub fn with_y_label_wrap(mut self, max_chars: usize) -> Self {
self.y_label_wrap = if max_chars > 0 { Some(max_chars) } else { None };
self
}
/// Word-wrap the secondary y-axis label at `max_chars` characters.
pub fn with_y2_label_wrap(mut self, max_chars: usize) -> Self {
self.y2_label_wrap = if max_chars > 0 { Some(max_chars) } else { None };
self
}
/// Word-wrap legend labels and titles at `max_chars` characters.
pub fn with_legend_wrap(mut self, max_chars: usize) -> Self {
self.legend_wrap = if max_chars > 0 { Some(max_chars) } else { None };
self
}
pub fn with_log_x(mut self) -> Self {
self.log_x = true;
self
}
pub fn with_log_y(mut self) -> Self {
self.log_y = true;
self
}
pub fn with_log_scale(mut self) -> Self {
self.log_x = true;
self.log_y = true;
self
}
pub fn with_annotation(mut self, annotation: TextAnnotation) -> Self {
self.annotations.push(annotation);
self
}
pub fn with_reference_line(mut self, line: ReferenceLine) -> Self {
self.reference_lines.push(line);
self
}
pub fn with_shaded_region(mut self, region: ShadedRegion) -> Self {
self.shaded_regions.push(region);
self
}
pub fn with_font_family<S: Into<String>>(mut self, family: S) -> Self {
self.font_family = Some(family.into());
self
}
pub fn with_title_size(mut self, size: u32) -> Self {
self.title_size = size;
self
}
pub fn with_label_size(mut self, size: u32) -> Self {
self.label_size = size;
self
}
pub fn with_tick_size(mut self, size: u32) -> Self {
self.tick_size = size;
self
}
pub fn with_body_size(mut self, size: u32) -> Self {
self.body_size = size;
self
}
/// Set the axis line stroke width in logical pixels (at scale 1.0).
/// Affects the X and Y axis border lines only, not ticks or grid.
pub fn with_axis_line_width(mut self, width: f64) -> Self {
self.axis_line_width = Some(width);
self
}
/// Set the tick mark stroke width in logical pixels (at scale 1.0).
pub fn with_tick_width(mut self, width: f64) -> Self {
self.tick_width = Some(width);
self
}
/// Set the major tick mark length in logical pixels (at scale 1.0).
/// Minor tick length is scaled proportionally (60% of major).
pub fn with_tick_length(mut self, length: f64) -> Self {
self.tick_length = Some(length);
self
}
/// Set the grid line stroke width in logical pixels (at scale 1.0).
pub fn with_grid_line_width(mut self, width: f64) -> Self {
self.grid_line_width = Some(width);
self
}
pub fn with_theme(mut self, theme: Theme) -> Self {
self.show_grid = theme.show_grid;
if let Some(ref font) = theme.font_family {
self.font_family = Some(font.clone());
}
self.theme = theme;
self
}
pub fn with_palette(mut self, palette: Palette) -> Self {
self.palette = Some(palette);
self
}
/// Set the same tick format for both axes.
pub fn with_tick_format(mut self, fmt: TickFormat) -> Self {
self.x_tick_format = fmt.clone();
self.y_tick_format = fmt;
self
}
/// Set the tick format for the x-axis only.
pub fn with_x_tick_format(mut self, fmt: TickFormat) -> Self {
self.x_tick_format = fmt;
self
}
/// Set the tick format for the y-axis only.
pub fn with_y_tick_format(mut self, fmt: TickFormat) -> Self {
self.y_tick_format = fmt;
self
}
/// Set the tick format for colorbar labels. Default: [`TickFormat::Auto`]
/// (switches to scientific notation for values ≥ 10 000 or ≤ 0.01).
pub fn with_colorbar_tick_format(mut self, fmt: TickFormat) -> Self {
self.colorbar_tick_format = fmt;
self
}
pub fn with_y2_range(mut self, min: f64, max: f64) -> Self {
self.y2_range = Some((min, max));
self
}
pub fn with_y2_label<S: Into<String>>(mut self, label: S) -> Self {
self.y2_label = Some(label.into());
self
}
/// Shift the y2-axis label by `(dx, dy)` pixels from its auto-computed position.
/// Positive `dx` moves right (further from the right axis); positive `dy` moves down.
pub fn with_y2_label_offset(mut self, dx: f64, dy: f64) -> Self {
self.y2_label_offset = (dx, dy);
self
}
pub fn with_log_y2(mut self) -> Self {
self.log_y2 = true;
self
}
pub fn with_y2_tick_format(mut self, fmt: TickFormat) -> Self {
self.y2_tick_format = fmt;
self
}
pub fn with_x_datetime(mut self, axis: DateTimeAxis) -> Self {
self.x_datetime = Some(axis);
self
}
pub fn with_y_datetime(mut self, axis: DateTimeAxis) -> Self {
self.y_datetime = Some(axis);
self
}
pub fn with_x_tick_rotate(mut self, angle: f64) -> Self {
self.x_tick_rotate = Some(angle);
self
}
/// Snap both axes to the tick boundary that just contains the data,
/// with no extra breathing-room step. Useful for `TickFormat::Percent`
/// (so the axis stops at 100 % instead of 110 %) or any domain where the
/// data naturally fills the full scale.
pub fn with_clamp_axis(mut self) -> Self {
self.clamp_axis = true;
self
}
/// Like `with_clamp_axis` but only for the y-axis. Set automatically by
/// `auto_from_plots` for normalized histograms; can also be used manually.
pub fn with_clamp_y_axis(mut self) -> Self {
self.clamp_y_axis = true;
self
}
/// Auto-compute y2_range from secondary plots, also expanding x_range to cover them.
pub fn with_y2_auto(mut self, secondary: &[Plot]) -> Self {
let mut x_min = self.x_range.0;
let mut x_max = self.x_range.1;
let mut y2_min = f64::INFINITY;
let mut y2_max = f64::NEG_INFINITY;
let mut max_secondary_label: usize = 0;
for plot in secondary {
if let Some(((xlo, xhi), (ylo, yhi))) = plot.bounds() {
x_min = x_min.min(xlo);
x_max = x_max.max(xhi);
y2_min = y2_min.min(ylo);
y2_max = y2_max.max(yhi);
}
// Collect legend label lengths so legend_width covers secondary labels too.
#[allow(clippy::collapsible_match)]
match plot {
Plot::Scatter(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Line(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Series(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Band(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Histogram(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Box(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Violin(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Strip(p) => {
if p.legend_label.is_some() {
if p.group_colors.is_some() {
for g in &p.groups {
max_secondary_label = max_secondary_label.max(g.label.len());
}
} else if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
}
Plot::Waterfall(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Candlestick(p) => {
if let Some(l) = &p.legend_label {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::StackedArea(p) => {
for l in p.labels.iter().flatten() {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Streamgraph(p) => {
for l in p.labels.iter().flatten() {
max_secondary_label = max_secondary_label.max(l.len());
}
}
Plot::Bar(p) => {
if let Some(ll) = &p.legend_label {
for l in ll {
max_secondary_label = max_secondary_label.max(l.len());
}
}
}
_ => {}
}
}
if max_secondary_label > 0 {
let needed = max_secondary_label as f64 * 8.5 + 35.0;
if needed > self.legend_width {
self.legend_width = needed;
self.show_legend = true;
}
}
self.x_range = (x_min, x_max);
let raw = (y2_min, y2_max);
self.data_y2_range = Some(raw);
if y2_max > y2_min {
let y2_span = y2_max - y2_min;
y2_max += y2_span * 0.01;
if y2_min >= 0.0 {
y2_min = 0.0;
} else {
y2_min -= y2_span * 0.01;
}
}
self.y2_range = Some((y2_min, y2_max));
self
}
pub fn with_term_rows(mut self, rows: u32) -> Self {
self.term_rows = Some(rows);
self
}
pub fn with_x_axis_min(mut self, v: f64) -> Self {
self.x_axis_min = Some(v);
self
}
pub fn with_x_axis_max(mut self, v: f64) -> Self {
self.x_axis_max = Some(v);
self
}
pub fn with_y_axis_min(mut self, v: f64) -> Self {
self.y_axis_min = Some(v);
self
}
pub fn with_y_axis_max(mut self, v: f64) -> Self {
self.y_axis_max = Some(v);
self
}
pub fn with_x_tick_step(mut self, s: f64) -> Self {
self.x_tick_step = Some(s);
self
}
pub fn with_y_tick_step(mut self, s: f64) -> Self {
self.y_tick_step = Some(s);
self
}
pub fn with_minor_ticks(mut self, n: u32) -> Self {
self.minor_ticks = Some(n);
self
}
pub fn with_show_minor_grid(mut self, v: bool) -> Self {
self.show_minor_grid = v;
self
}
/// Convenience: auto-range both axes from separate plot lists.
pub fn auto_from_twin_y_plots(primary: &[Plot], secondary: &[Plot]) -> Self {
Layout::auto_from_plots(primary).with_y2_auto(secondary)
}
}
#[derive(Clone)]
pub struct ComputedLayout {
pub width: f64,
pub height: f64,
pub margin_top: f64,
pub margin_bottom: f64,
pub margin_left: f64,
pub margin_right: f64,
pub x_range: (f64, f64),
pub y_range: (f64, f64),
pub x_ticks: usize,
pub y_ticks: usize,
pub legend_position: LegendPosition,
pub stats_position: LegendPosition,
pub legend_width: f64,
/// Optional explicit legend height override from `Layout::with_legend_height`.
pub legend_height_override: Option<f64>,
/// Pixel width of the widest y-axis tick label, computed from actual tick strings.
/// Used in `axis.rs` to position the Y axis label flush with the tick labels.
pub y_tick_label_px: f64,
pub log_x: bool,
pub log_y: bool,
pub font_family: Option<String>,
pub title_size: u32,
pub label_size: u32,
pub tick_size: u32,
pub body_size: u32,
pub theme: Theme,
pub x_tick_format: TickFormat,
pub y_tick_format: TickFormat,
pub colorbar_tick_format: TickFormat,
pub y2_range: Option<(f64, f64)>,
pub log_y2: bool,
pub y2_tick_format: TickFormat,
/// Pixel width consumed by the y2 axis (ticks + labels). 0.0 when no y2 axis.
pub y2_axis_width: f64,
/// Rotation angle for x-axis tick labels (degrees, typically -45.0). None = no rotation.
pub x_tick_rotate: Option<f64>,
/// Pixel spacing between legend entries, quantised to a whole terminal-row
/// multiple when `term_rows` is set. Always >= 18.0 (the SVG default).
pub legend_line_height: f64,
/// Explicit major tick step for the x-axis (None = auto).
pub x_tick_step: Option<f64>,
/// Explicit major tick step for the y-axis (None = auto).
pub y_tick_step: Option<f64>,
/// Sub-intervals between major ticks for minor tick marks.
pub minor_ticks: Option<u32>,
/// Draw faint gridlines at minor tick positions.
pub show_minor_grid: bool,
/// Common bin width when all histograms share the same bin size.
/// When set, x-axis ticks are generated to fall exactly on bin edges.
pub x_bin_width: Option<f64>,
/// Angular position (degrees) at which r-axis labels are drawn on polar plots.
/// `None` means auto (midpoint between 0° spoke and first clockwise spoke).
pub polar_r_label_angle: Option<f64>,
/// Scaled pixel constants for rendering, derived from `layout.scale`.
/// Avoids threading the scale factor through every render function.
pub tick_mark_major: f64, // 5.0 * scale (or layout.tick_length * scale)
pub tick_mark_minor: f64, // 3.0 * scale (60% of major)
pub tick_label_margin: f64, // 8.0 * scale — gap from axis line to tick label text
pub axis_stroke_width: f64, // 1.0 * scale — base stroke width (annotations, plot shapes)
pub axis_line_width: f64, // axis border lines (overridable via Layout::with_axis_line_width)
pub tick_stroke_width: f64, // tick mark strokes (overridable via Layout::with_tick_width)
pub grid_stroke_width: f64, // grid line strokes (overridable via Layout::with_grid_line_width)
pub legend_padding: f64, // 10.0 * scale — legend box internal padding
pub legend_inset: f64, // 8.0 * scale — Inside legend inset from plot edge
pub legend_swatch_size: f64, // 12.0 * scale — Rect/Line swatch length and height
pub legend_swatch_x: f64, // 5.0 * scale — swatch left inset within legend box
pub legend_text_x: f64, // 25.0 * scale — label text left inset within legend box
pub legend_swatch_r: f64, // 5.0 * scale — Circle swatch radius
pub legend_swatch_half: f64, // 8.0 * scale — CircleSize cap radius
pub annotation_arrow_len: f64, // 8.0 * scale — annotation arrowhead length
pub annotation_arrow_half_w: f64, // 4.0 * scale — annotation arrowhead half-width
pub colorbar_bar_width: f64, // 20.0 * scale — colorbar bar rect width
pub colorbar_x_inset: f64, // 70.0 * scale — colorbar position from canvas right
// Pre-computed linear transform coefficients for map_x / map_y.
// map_x(x) = x_offset + x * x_scale (linear)
// map_x(x) = x_offset + log10(x) * x_scale (log)
x_scale: f64,
x_offset: f64,
y_scale: f64,
y_offset: f64,
/// Mirror of `Layout::interactive` — propagated so renderers can access it.
pub interactive: bool,
/// Mirror of `Layout::equal_aspect` — read by `recompute_transforms`.
pub equal_aspect: bool,
/// Override x-axis label position (x_centre, y) used by DicePlot to place
/// the label relative to the actual grid rather than the canvas margin.
pub dice_x_label_pos: Option<(f64, f64)>,
/// Override y-axis label position (x, y_centre, rotated) for DicePlot.
pub dice_y_label_pos: Option<(f64, f64)>,
/// Y position for the plot title, computed from the pre-notation base margin so that
/// BrickPlot notation tiers don't push the title into the middle of the annotation zone.
pub title_y: f64,
/// Propagated from `Layout::title_wrap`.
pub title_wrap: Option<usize>,
/// Propagated from `Layout::x_label_wrap`.
pub x_label_wrap: Option<usize>,
/// Propagated from `Layout::y_label_wrap`.
pub y_label_wrap: Option<usize>,
/// Propagated from `Layout::y2_label_wrap`.
pub y2_label_wrap: Option<usize>,
/// Propagated from `Layout::legend_wrap`.
pub legend_wrap: Option<usize>,
/// Extra pixels added to `margin_bottom` for an OutsideBottom legend.
/// The x-axis label must be offset upward by this amount so it stays
/// above the legend rather than landing inside it.
pub legend_bottom_extra: f64,
/// Number of columns for `OutsideBottomColumns` legend layout; 0 for all other positions.
pub legend_col_count: usize,
}
impl ComputedLayout {
pub fn from_layout(layout: &Layout) -> Self {
let s = layout.scale.max(0.1);
let title_size = layout.title_size as f64 * s;
let label_size = layout.label_size as f64 * s;
let tick_size = layout.tick_size as f64 * s;
// Compute tick mark length early — needed for margin_left and tick_label_margin.
let tick_mark_major_px = layout.tick_length.map(|l| l * s).unwrap_or(5.0 * s);
// Top: title height + padding, or small padding if no title.
// Compute the base margin first (title + padding only), then add notation tiers on top.
// title_y uses the base margin so that notation tiers don't push the title downward
// into the middle of the per-block label zone.
let title_lines =
if let (Some(ref title), Some(max_chars)) = (&layout.title, layout.title_wrap) {
render_utils::wrap_text(title, max_chars).len()
} else if layout.title.is_some() {
1
} else {
0
};
let base_margin_top = if title_lines > 0 {
title_size * title_lines as f64 + label_size + 12.0 * s
} else {
10.0 * s
};
let mut title_y = base_margin_top / 2.0;
let mut margin_top = base_margin_top;
// BrickPlot per-block notation labels are drawn above the top row.
if layout.brick_notation_tiers > 0 {
let body = layout.body_size as f64 * s;
margin_top += (layout.brick_notation_tiers as f64 + 0.5) * body * 1.1 + 4.0 * s;
}
// Bottom: tick_mark + gap(5) + tick_label + gap(5) + axis_label + padding(10)
// When ticks are suppressed AND no rotation is requested (e.g. pure numeric axes),
// keep only minimal space. When rotation IS set (e.g. Manhattan chromosome labels drawn
// by the renderer itself), compute space for the rotated custom labels.
let mut margin_bottom = if layout.suppress_x_ticks && layout.x_tick_rotate.is_none() {
tick_size + 15.0 * s
} else if let Some(angle) = layout.x_tick_rotate {
// Rotated labels extend below their anchor point by label_px * sin(|angle|).
let char_w = tick_size * 0.6;
let max_chars = layout
.x_categories
.as_ref()
.and_then(|cats| cats.iter().map(|s| s.len()).max())
.unwrap_or(10) as f64;
let label_px = max_chars * char_w;
let angle_rad = angle.abs() * std::f64::consts::PI / 180.0;
let needed = label_px * angle_rad.sin() + tick_size + tick_mark_major_px + 10.0 * s;
needed.max(tick_size + label_size + tick_mark_major_px + 20.0 * s)
} else {
tick_size + label_size + tick_mark_major_px + 20.0 * s
};
// Extra bottom margin for wrapped x-axis label.
if let (Some(ref xlabel), Some(max_chars)) = (&layout.x_label, layout.x_label_wrap) {
let x_label_lines = render_utils::wrap_text(xlabel, max_chars).len();
if x_label_lines > 1 {
margin_bottom += (x_label_lines - 1) as f64 * label_size;
}
}
// Left: axis label + y tick label text width + gaps.
// Compute the actual maximum tick label pixel width from real tick strings so the
// left margin is exactly as wide as needed and the Y axis label snugs up against
// the tick labels rather than sitting at a fixed canvas-edge offset.
//
// Layout (left→right): [3px edge] [Y-label] [5px gap] [tick labels] [8px gap] [axis]
// → margin_left = label_size + y_tick_label_px + 16
let y_tick_label_px: f64 = if layout.suppress_y_ticks {
0.0
} else if let Some(ref cats) = layout.y_categories {
let max_chars = cats.iter().map(|s| s.len()).max().unwrap_or(4) as f64;
(max_chars * tick_size * 0.6).max(tick_size * 2.0)
} else if layout.log_y {
let ticks_log = render_utils::generate_ticks_log(
layout.y_range.0.max(1e-300),
layout.y_range.1.max(1e-300),
);
let max_chars = ticks_log
.iter()
.map(|&v| render_utils::format_log_tick(v).len())
.max()
.unwrap_or(3) as f64;
(max_chars * tick_size * 0.6).max(tick_size * 2.0)
} else if layout.y_datetime.is_some() {
tick_size * 5.0 // datetime labels vary; ~5 char-widths is a reasonable default
} else {
// Generate a preliminary set of tick values from the raw y_range (no auto-ranging
// yet) and format them to find the widest label string. Using layout.y_range
// rather than the final auto-ranged range is fine here — the formatted width
// changes very little after nice-rounding.
let n = if layout.ticks > 0 { layout.ticks } else { 5 };
let tick_vals = if let Some(step) = layout.y_tick_step {
render_utils::generate_ticks_with_step(layout.y_range.0, layout.y_range.1, step)
} else {
render_utils::generate_ticks(layout.y_range.0, layout.y_range.1, n)
};
let max_chars = tick_vals
.iter()
.map(|&v| layout.y_tick_format.format(v).len())
.max()
.unwrap_or(3) as f64;
(max_chars * tick_size * 0.6).max(tick_size * 2.0)
};
let y_label_lines =
if let (Some(ref ylabel), Some(max_chars)) = (&layout.y_label, layout.y_label_wrap) {
render_utils::wrap_text(ylabel, max_chars).len()
} else {
1
};
let mut margin_left = if layout.suppress_y_ticks {
10.0 * s
} else {
// 16px = 3 edge + 5 label-to-ticklabels gap + 8 tick_label_margin base;
// tick_mark_major_px is added separately so the margin grows with tick length.
// Extra label_size per wrapped line beyond the first.
label_size * y_label_lines as f64 + y_tick_label_px + 16.0 * s + tick_mark_major_px
};
// Estimate the overhang of the rightmost numeric x-tick label.
// Tick labels are centred on their tick position (TextAnchor::Middle), so the
// last tick (at x_max) extends half its pixel width to the right of the plot edge.
// Without this, labels like "15000" or "100.5" clip against the SVG boundary.
// Uses layout.x_range.1 / x_axis_max as a proxy — nice-rounding rarely changes
// the label length, mirroring how y_tick_label_px uses layout.y_range before
// auto-ranging (lines ~1174-1187 above).
let x_last_tick_half_w: f64 = if layout.suppress_x_ticks
|| layout.x_categories.is_some()
|| layout.x_tick_rotate.is_some()
|| layout.log_x
{
0.0 // handled elsewhere or not applicable
} else {
let val = layout.x_axis_max.unwrap_or(layout.x_range.1);
let label = layout.x_tick_format.format(val);
label.len() as f64 * tick_size * 0.6 * 0.5
};
let mut margin_right = label_size.max(x_last_tick_half_w)
+ layout.horizon_right_annot_px
+ layout.gantt_right_annot_px;
// For rotated x-axis category labels the text extends horizontally from its anchor.
// Negative angle → TextAnchor::End → extends left → first label can clip left edge.
// Positive angle → TextAnchor::Start → extends right → last label can clip right edge.
if let Some(angle) = layout.x_tick_rotate {
if !layout.suppress_x_ticks {
if let Some(ref cats) = layout.x_categories {
let char_w = tick_size * 0.6;
let angle_rad = angle.abs() * std::f64::consts::PI / 180.0;
let cos_a = angle_rad.cos();
if angle < 0.0 {
if let Some(first) = cats.first() {
let needed = first.len() as f64 * char_w * cos_a;
if needed > margin_left {
margin_left = needed;
}
}
} else if let Some(last) = cats.last() {
let needed = last.len() as f64 * char_w * cos_a;
if needed > margin_right {
margin_right = needed;
}
}
}
}
}
let y2_label_lines = if let (Some(ref y2label), Some(max_chars)) =
(&layout.y2_label, layout.y2_label_wrap)
{
render_utils::wrap_text(y2label, max_chars).len()
} else {
1
};
let y2_axis_width = if layout.y2_range.is_some() && !layout.suppress_y2_ticks {
label_size * y2_label_lines as f64 + tick_size * 3.0 + 15.0 * s
} else {
0.0
};
margin_right += y2_axis_width;
// Effective legend width: capped when legend_wrap is set.
let mut effective_legend_width = if let Some(max_chars) = layout.legend_wrap {
let cap = max_chars as f64 * 7.2 * s + 35.0 * s;
(layout.legend_width * s).min(cap).max(80.0 * s)
} else {
layout.legend_width * s
};
// When entries are numerous enough to trigger the height cap, the rendered legend shows
// a "… (+N more)" overflow line. Ensure the right margin reserves enough space for it.
{
let n_entries = if let Some(ref entries) = layout.legend_entries {
entries.len()
} else {
layout.legend_entry_count
};
if n_entries > 10 {
let canvas_h_est = layout.height.unwrap_or(400.0) * s;
let avail_h_est = (canvas_h_est - margin_top - 16.0 * s).max(18.0 * s);
let max_entries_est = ((avail_h_est / (18.0 * s)).floor() as usize).max(10);
if n_entries > max_entries_est {
let overflow = n_entries - max_entries_est.saturating_sub(1);
let overflow_text = format!("… (+{overflow} more)");
// Text sits at legend_text_x (25px) from legend_x; box needs to contain it.
let min_w = overflow_text.chars().count() as f64 * 7.5 * s + 25.0 * s + 8.0 * s;
effective_legend_width = effective_legend_width.max(min_w);
}
}
}
let mut legend_bottom_extra = 0.0_f64;
let mut legend_col_count: usize = 0;
if layout.show_legend {
// Estimate legend height for OutsideTop/Bottom margin adjustments.
let legend_line_h = 18.0 * s;
let wrap_line_count = |text: &str| -> usize {
if let Some(mc) = layout.legend_wrap {
render_utils::wrap_text(text, mc).len()
} else {
1
}
};
let legend_h_estimate = if let Some(ref groups) = layout.legend_groups {
let n: usize = groups
.iter()
.map(|g| {
wrap_line_count(&g.title)
+ g.entries
.iter()
.map(|e| wrap_line_count(&e.label))
.sum::<usize>()
})
.sum();
n as f64 * legend_line_h + 20.0 * s
} else if let Some(ref entries) = layout.legend_entries {
let n: usize = entries.iter().map(|e| wrap_line_count(&e.label)).sum();
n as f64 * legend_line_h + 20.0 * s
} else {
80.0 * s // conservative default for auto-collected entries
};
match layout.legend_position {
LegendPosition::OutsideRightTop
| LegendPosition::OutsideRightMiddle
| LegendPosition::OutsideRightBottom => {
margin_right += effective_legend_width;
}
LegendPosition::OutsideLeftTop
| LegendPosition::OutsideLeftMiddle
| LegendPosition::OutsideLeftBottom => {
margin_left += effective_legend_width;
}
LegendPosition::OutsideTopLeft
| LegendPosition::OutsideTopCenter
| LegendPosition::OutsideTopRight => {
margin_top += legend_h_estimate;
// Push title_y down so the title stays below the legend band.
title_y += legend_h_estimate;
}
LegendPosition::OutsideBottomLeft
| LegendPosition::OutsideBottomCenter
| LegendPosition::OutsideBottomRight => {
let extra = legend_h_estimate + 10.0 * s;
margin_bottom += extra;
// Track how much the bottom margin grew due to the legend so that
// the x-axis label can be positioned relative to the axis area,
// not the canvas bottom.
legend_bottom_extra = extra;
}
LegendPosition::OutsideBottomColumns => {
// Available width = canvas minus side margins (no right margin added for this position)
let avail_w = layout
.width
.map(|w| w - margin_left - margin_right)
.unwrap_or(600.0 * s);
// Column entry width: swatch+gap (18px) + label text at 0.68 char_w + inter-col gap (20px)
let char_px = tick_size * 0.68;
let max_chars = if let Some(ref entries) = layout.legend_entries {
entries.iter().map(|e| e.label.len()).max().unwrap_or(8) as f64
} else {
layout.legend_max_label_chars.max(8) as f64
};
let col_w = (18.0 + max_chars * char_px / s + 20.0) * s;
let n_cols = ((avail_w / col_w).floor() as usize).max(1);
let n_entries = if let Some(ref entries) = layout.legend_entries {
entries.len()
} else {
layout.legend_entry_count.max(1)
};
let n_rows = n_entries.div_ceil(n_cols);
let legend_h = n_rows as f64 * legend_line_h + 20.0 * s;
let extra = legend_h + 10.0 * s;
margin_bottom += extra;
legend_bottom_extra = extra;
legend_col_count = n_cols;
}
// Inside*, Custom, DataCoords: overlay or user controls — no margin change
_ => {}
}
}
if layout.show_colorbar {
margin_right += 90.0 * s; // 20px label-gap + 20px bar + 5px tick-mark + 30px tick labels + 15px gap
}
// If the user fixed the canvas width, ensure the legend doesn't crush the plot.
// Guarantee at least 150 px of plot area (or 30% of canvas, whichever is larger).
if let Some(fixed_w) = layout.width {
let min_plot_px = (fixed_w * 0.30).max(150.0);
let max_margin_right = (fixed_w - margin_left - min_plot_px).max(0.0);
if margin_right > max_margin_right {
margin_right = max_margin_right;
}
}
let plot_width = 600.0;
let plot_height = 450.0;
// Reserve space below the plot for the interactive UI strip.
// Only applies when height is auto-computed; user-fixed heights are left unchanged.
if layout.interactive && layout.height.is_none() {
margin_bottom += 32.0;
}
let width = layout
.width
.unwrap_or(margin_left + plot_width + margin_right);
let height = layout
.height
.unwrap_or(margin_top + plot_height + margin_bottom);
let x_ticks = if layout.ticks > 0 {
layout.ticks
} else {
render_utils::auto_tick_count(width)
};
let y_ticks = if layout.ticks > 0 {
layout.ticks
} else {
render_utils::auto_tick_count(height)
};
// For log scale, prefer the raw data range (before proportional padding).
// For clamp_axis, also use the raw range so the boundary lands on the
// tick that just contains the data with no extra step.
let (x_min, x_max) = if layout.log_x {
let (xlo, xhi) = layout.data_x_range.unwrap_or(layout.x_range);
render_utils::auto_nice_range_log(xlo, xhi)
} else if layout.clamp_axis {
let (xlo, xhi) = layout.data_x_range.unwrap_or(layout.x_range);
render_utils::auto_nice_range(xlo, xhi, x_ticks)
} else if layout.x_bin_width.is_some() {
// Histogram: use the exact data range so ticks start and end on bin
// boundaries rather than being rounded outward by auto_nice_range.
let (xlo, xhi) = layout.data_x_range.unwrap_or(layout.x_range);
(xlo, xhi)
} else {
render_utils::auto_nice_range(layout.x_range.0, layout.x_range.1, x_ticks)
};
let (y_min, y_max) = if layout.log_y {
let (ylo, yhi) = layout.data_y_range.unwrap_or(layout.y_range);
render_utils::auto_nice_range_log(ylo, yhi)
} else if layout.clamp_axis || layout.clamp_y_axis {
let (ylo, yhi) = layout.data_y_range.unwrap_or(layout.y_range);
render_utils::auto_nice_range(ylo, yhi, y_ticks)
} else {
render_utils::auto_nice_range(layout.y_range.0, layout.y_range.1, y_ticks)
};
// Apply explicit axis-range overrides (after auto-ranging).
let x_min = layout.x_axis_min.unwrap_or(x_min);
let x_max = layout.x_axis_max.unwrap_or(x_max);
let y_min = layout.y_axis_min.unwrap_or(y_min);
let y_max = layout.y_axis_max.unwrap_or(y_max);
let y2_range = if let Some((ylo, yhi)) = layout.y2_range {
if layout.log_y2 {
let (ylo, yhi) = layout.data_y2_range.unwrap_or((ylo, yhi));
Some(render_utils::auto_nice_range_log(ylo, yhi))
} else if layout.clamp_axis {
let (ylo, yhi) = layout.data_y2_range.unwrap_or((ylo, yhi));
Some(render_utils::auto_nice_range(ylo, yhi, y_ticks))
} else {
Some(render_utils::auto_nice_range(ylo, yhi, y_ticks))
}
} else {
None
};
// Quantise legend line-height to a whole number of terminal rows so that
// every legend entry maps to a distinct row without gaps.
let legend_line_height = if let Some(tr) = layout.term_rows {
let cell_h = height / tr as f64;
let rows_per_entry = ((18.0 * s) / cell_h).round().max(1.0);
rows_per_entry * cell_h
} else {
18.0 * s
};
let mut s = Self {
width,
height,
margin_top,
margin_bottom,
margin_left,
margin_right,
x_range: (x_min, x_max),
y_range: (y_min, y_max),
x_ticks,
y_ticks,
legend_position: layout.legend_position,
stats_position: layout.stats_position,
legend_width: effective_legend_width,
legend_height_override: layout.legend_height.map(|h| h * s),
y_tick_label_px,
log_x: layout.log_x,
log_y: layout.log_y,
font_family: layout
.font_family
.clone()
.or(layout.theme.font_family.clone())
.or(Some(DEFAULT_FONT_FAMILY.to_string())),
title_size: (layout.title_size as f64 * s).round().max(1.0) as u32,
label_size: (layout.label_size as f64 * s).round().max(1.0) as u32,
tick_size: (layout.tick_size as f64 * s).round().max(1.0) as u32,
body_size: (layout.body_size as f64 * s).round().max(1.0) as u32,
theme: layout.theme.clone(),
x_tick_format: layout.x_tick_format.clone(),
y_tick_format: layout.y_tick_format.clone(),
colorbar_tick_format: layout.colorbar_tick_format.clone(),
y2_range,
log_y2: layout.log_y2,
y2_tick_format: layout.y2_tick_format.clone(),
y2_axis_width,
x_tick_rotate: layout.x_tick_rotate,
legend_line_height,
x_tick_step: layout.x_tick_step,
y_tick_step: layout.y_tick_step,
minor_ticks: layout.minor_ticks,
show_minor_grid: layout.show_minor_grid,
x_bin_width: layout.x_bin_width,
polar_r_label_angle: layout.polar_r_label_angle,
tick_mark_major: tick_mark_major_px,
tick_mark_minor: layout.tick_length.map(|l| l * s * 0.6).unwrap_or(3.0 * s),
tick_label_margin: tick_mark_major_px + 3.0 * s,
axis_stroke_width: s,
axis_line_width: layout.axis_line_width.map(|w| w * s).unwrap_or(s),
tick_stroke_width: layout.tick_width.map(|w| w * s).unwrap_or(s),
grid_stroke_width: layout.grid_line_width.map(|w| w * s).unwrap_or(s),
legend_padding: 10.0 * s,
legend_inset: 8.0 * s,
legend_swatch_size: 12.0 * s,
legend_swatch_x: 5.0 * s,
legend_text_x: 25.0 * s,
legend_swatch_r: 5.0 * s,
legend_swatch_half: 8.0 * s,
annotation_arrow_len: 8.0 * s,
annotation_arrow_half_w: 4.0 * s,
colorbar_bar_width: 20.0 * s,
colorbar_x_inset: 65.0 * s,
x_scale: 0.0,
x_offset: 0.0,
y_scale: 0.0,
y_offset: 0.0,
interactive: layout.interactive,
equal_aspect: layout.equal_aspect,
dice_x_label_pos: None,
dice_y_label_pos: None,
title_y,
title_wrap: layout.title_wrap,
x_label_wrap: layout.x_label_wrap,
y_label_wrap: layout.y_label_wrap,
y2_label_wrap: layout.y2_label_wrap,
legend_wrap: layout.legend_wrap,
legend_bottom_extra,
legend_col_count,
};
s.recompute_transforms();
s
}
/// Recompute cached linear-transform coefficients after changing
/// width, height, margins, or axis ranges.
pub fn recompute_transforms(&mut self) {
let pw = self.plot_width();
let ph = self.plot_height();
if self.log_x {
let log_min = self.x_range.0.max(1e-10).log10();
let log_max = self.x_range.1.max(1e-10).log10();
let span = log_max - log_min;
self.x_scale = if span.abs() > f64::EPSILON {
pw / span
} else {
0.0
};
self.x_offset = self.margin_left - log_min * self.x_scale;
} else {
let span = self.x_range.1 - self.x_range.0;
self.x_scale = if span.abs() > f64::EPSILON {
pw / span
} else {
0.0
};
self.x_offset = self.margin_left - self.x_range.0 * self.x_scale;
}
if self.log_y {
let log_min = self.y_range.0.max(1e-10).log10();
let log_max = self.y_range.1.max(1e-10).log10();
let span = log_max - log_min;
self.y_scale = if span.abs() > f64::EPSILON {
ph / span
} else {
0.0
};
self.y_offset = self.height - self.margin_bottom + log_min * self.y_scale;
} else {
let span = self.y_range.1 - self.y_range.0;
self.y_scale = if span.abs() > f64::EPSILON {
ph / span
} else {
0.0
};
self.y_offset = self.height - self.margin_bottom + self.y_range.0 * self.y_scale;
}
// Equal-aspect: expand the tighter axis so 1 data unit = same pixels on both axes.
// Only applies to linear (non-log) axes; ignored when either scale is zero.
if self.equal_aspect
&& !self.log_x
&& !self.log_y
&& self.x_scale > f64::EPSILON
&& self.y_scale > f64::EPSILON
{
let s = self.x_scale.min(self.y_scale);
if self.x_scale > s {
// x is more zoomed in — expand x range to match y scale
let x_mid = (self.x_range.0 + self.x_range.1) / 2.0;
let new_half = self.plot_width() / (2.0 * s);
self.x_range = (x_mid - new_half, x_mid + new_half);
self.x_scale = s;
self.x_offset = self.margin_left - self.x_range.0 * self.x_scale;
} else {
// y is more zoomed in — expand y range to match x scale
let y_mid = (self.y_range.0 + self.y_range.1) / 2.0;
let new_half = self.plot_height() / (2.0 * s);
self.y_range = (y_mid - new_half, y_mid + new_half);
self.y_scale = s;
self.y_offset = self.height - self.margin_bottom + self.y_range.0 * self.y_scale;
}
}
}
pub fn plot_width(&self) -> f64 {
self.width - self.margin_left - self.margin_right
}
pub fn plot_height(&self) -> f64 {
self.height - self.margin_top - self.margin_bottom
}
#[inline(always)]
pub fn map_x(&self, x: f64) -> f64 {
if self.log_x {
self.x_offset + x.max(1e-10).log10() * self.x_scale
} else {
self.x_offset + x * self.x_scale
}
}
#[inline(always)]
pub fn map_y(&self, y: f64) -> f64 {
if self.log_y {
self.y_offset - y.max(1e-10).log10() * self.y_scale
} else {
self.y_offset - y * self.y_scale
}
}
pub fn map_y2(&self, y: f64) -> f64 {
if let Some((y2_min, y2_max)) = self.y2_range {
let ph = self.plot_height();
if self.log_y2 {
let y = y.max(1e-10);
let log_min = y2_min.log10();
let log_max = y2_max.log10();
self.height - self.margin_bottom - (y.log10() - log_min) / (log_max - log_min) * ph
} else {
self.height - self.margin_bottom - (y - y2_min) / (y2_max - y2_min) * ph
}
} else {
self.map_y(y)
}
}
/// Clone self with y_range = y2_range, log_y = log_y2, y_tick_format = y2_tick_format.
/// Used to render secondary-axis plots through existing add_* functions unchanged.
pub fn for_y2(&self) -> ComputedLayout {
let mut c = self.clone();
if let Some(y2) = self.y2_range {
c.y_range = y2;
}
c.log_y = self.log_y2;
c.y_tick_format = self.y2_tick_format.clone();
c.recompute_transforms();
c
}
}