ggplot-rs 0.41.0

A Rust implementation of ggplot2's Grammar of Graphics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
use plotters::prelude::IntoDrawingArea;

use crate::aes::Aes;
use crate::annotate::Annotation;
use crate::build::PlotBuilder;
use crate::coord::cartesian::CoordCartesian;
use crate::coord::fixed::CoordFixed;
use crate::coord::flip::CoordFlip;
use crate::coord::polar::CoordPolar;
use crate::coord::Coord;
use crate::data::{DataFrame, GGData, Value};
use crate::facet::{Facet, FacetLabeller, FacetScales, FacetSpace};
use crate::geom::area::GeomArea;
use crate::geom::bar::GeomBar;
use crate::geom::bin2d::GeomBin2d;
use crate::geom::blank::GeomBlank;
use crate::geom::boxplot::GeomBoxplot;
use crate::geom::col::GeomCol;
use crate::geom::contour::GeomContour;
use crate::geom::count::GeomCount;
use crate::geom::crossbar::GeomCrossbar;
use crate::geom::curve::GeomCurve;
use crate::geom::density::GeomDensity;
use crate::geom::density2d::GeomDensity2d;
use crate::geom::density_ridges::GeomDensityRidges;
use crate::geom::dotplot::GeomDotplot;
use crate::geom::errorbar::GeomErrorbar;
use crate::geom::freqpoly::GeomFreqpoly;
use crate::geom::hex::GeomHex;
use crate::geom::histogram::GeomHistogram;
use crate::geom::jitter::GeomJitter;
use crate::geom::line::GeomLine;
use crate::geom::linerange::GeomLinerange;
use crate::geom::path::GeomPath;
use crate::geom::point::GeomPoint;
use crate::geom::pointrange::GeomPointrange;
use crate::geom::polygon::GeomPolygon;
use crate::geom::qq::{GeomQQ, GeomQQLine};
use crate::geom::rect::GeomRect;
use crate::geom::refline::{GeomAbline, GeomHline, GeomVline};
use crate::geom::ribbon::GeomRibbon;
use crate::geom::rug::GeomRug;
use crate::geom::segment::GeomSegment;
use crate::geom::smooth::GeomSmooth;
use crate::geom::spoke::GeomSpoke;
use crate::geom::step::GeomStep;
use crate::geom::text::{GeomLabel, GeomText};
use crate::geom::tile::GeomTile;
use crate::geom::violin::GeomViolin;
use crate::geom::{Geom, GeomParams};
use crate::position::Position;
use crate::render::layout::PlotLayout;
#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
use crate::render::plotters_backend::PlottersAdapter;
use crate::render::renderer::PlotRenderer;
use crate::render::RenderError;
use crate::scale::continuous::ScaleContinuous;
use crate::scale::transform::ScaleTransform;
use crate::scale::Scale;
use crate::stat::Stat;
use crate::theme::Theme;

// Builder methods for the 0.17 statistical-graphics layers (QQ, step ribbons,
// ECDF bands, Cook's contours, horizontal error bars).
mod stat_layers;

/// Labels for the plot.
#[derive(Clone, Debug, Default)]
pub struct Labels {
    pub title: Option<String>,
    pub subtitle: Option<String>,
    pub x: Option<String>,
    pub y: Option<String>,
    pub caption: Option<String>,
    /// Corner tag (R's `labs(tag = ...)`), e.g. "A" for figure panels.
    pub tag: Option<String>,
}

/// A single layer in the plot.
pub struct Layer {
    pub data: Option<DataFrame>,
    pub mapping: Aes,
    pub geom: Box<dyn Geom>,
    pub stat: Box<dyn Stat>,
    pub position: Box<dyn Position>,
    pub params: GeomParams,
    pub show_legend: Option<bool>,
    /// The geom was configured explicitly (`geom_*_with(...)`), so its colours
    /// are deliberate and the theme's `primary_color` must not override them.
    pub explicit_style: bool,
    /// A `{column}` tooltip template ([`GGPlot::tooltip`]), rendered per row
    /// from the *built* layer data (post-stat) once that's available.
    pub tooltip_template: Option<String>,
    /// Legend key override ([`GGPlot::key_glyph`]); `None` = the geom's.
    pub key_glyph: Option<crate::guide::key::KeyGlyph>,
    /// Per-aesthetic `show.legend` ([`GGPlot::show_legend_for`]).
    pub show_legend_aes: Vec<(crate::aes::Aesthetic, bool)>,
}

/// The top-level plot specification — builder pattern.
pub struct GGPlot {
    pub(crate) data: DataFrame,
    pub(crate) mapping: Aes,
    pub(crate) layers: Vec<Layer>,
    pub(crate) scales: Vec<Box<dyn Scale>>,
    pub(crate) coord: Box<dyn Coord>,
    pub(crate) theme: Theme,
    pub(crate) labels: Labels,
    pub(crate) facet: Facet,
    /// Which facet panels get axes (#412).
    pub(crate) facet_axes: crate::facet::FacetAxes,
    pub(crate) annotations: Vec<Annotation>,
    pub(crate) guide_legend: crate::guide::config::GuideLegend,
    /// Warnings raised while specifying the plot (e.g. a clipped calendar
    /// span); prepended to the build warnings.
    pub(crate) warnings: Vec<String>,
    /// [`GGPlot::legend_bottom_when_narrow`]'s share, if set (#287).
    pub(crate) legend_bottom_share: Option<f64>,
    /// Clip the data layers to the panel (ggplot2's `coord_*(clip = "on")`,
    /// the default; #411).
    pub(crate) clip: bool,
    /// Tag axes, grid, legend, strips and titles with semantic CSS classes
    /// in SVG output (#465).
    pub(crate) svg_classes: bool,
    /// [`GGPlot::legend_inside_auto`]'s settings, if set (#332).
    pub(crate) legend_auto: Option<LegendAuto>,
    /// Panel aspect ratio used when the theme sets none (helpers such as
    /// `geom_calendar` need square cells; survives theme presets).
    pub(crate) default_aspect_ratio: Option<f64>,
    /// Hide axes and grid whatever theme is set (layout-only charts such as
    /// `geom_sankey`, whose x/y carry no data meaning); survives presets.
    pub(crate) hide_position_guides: bool,
    /// Hide only the y guides whatever theme is set (`geom_timeline`).
    pub(crate) hide_y_guides: bool,
    /// Plot-wide default locale for axis / legend labels ([`GGPlot::locale`]).
    pub(crate) locale: Option<crate::locale::Locale>,
    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/…
    /// ([`svg_root_data`](Self::svg_root_data)). Default `true`; a consumer
    /// overlaying a fragment on its own basemap (`render_svg_native_at`)
    /// turns it off so the fragment adds no root attributes of its own.
    pub(crate) svg_root_data: bool,
    /// Extra root `<svg>` attributes requested via [`svg_attr`](Self::svg_attr)/
    /// [`svg_attrs`](Self::svg_attrs), validated and applied at render time.
    pub(crate) root_attrs: Vec<(String, String)>,
    /// Whether to emit a `data-warnings` JSON array of the build warnings
    /// on the root `<svg>` ([`svg_warnings_attr`](Self::svg_warnings_attr)).
    /// Default off; byte-identical output when off.
    pub(crate) svg_warnings_attr: bool,
    /// Whether to emit `data-fvalue`/`data-fx` on marks
    /// ([`svg_formatted_values`](Self::svg_formatted_values)). Default off;
    /// byte-identical output when off.
    pub(crate) svg_formatted_values: bool,
    /// #221: validated [`layer_svg_attr`](Self::layer_svg_attr)s as
    /// `(layer index, name, value)`, applied by wrapping that layer's geom
    /// at build time.
    pub(crate) layer_svg_attrs: Vec<(usize, String, String)>,
    /// #255: accessible name for the rendered root `<svg>`
    /// ([`svg_title`](Self::svg_title)) — a `<title>` first child plus
    /// `role="img"`/`aria-labelledby`. Default `None`; byte-identical
    /// output when not set.
    pub(crate) svg_title: Option<String>,
    /// #255: accessible description for the rendered root `<svg>`
    /// ([`svg_desc`](Self::svg_desc)) — a `<desc>` first child plus
    /// `role="img"`/`aria-describedby`. Default `None`; byte-identical
    /// output when not set.
    pub(crate) svg_desc: Option<String>,
}

impl GGPlot {
    /// Create a new plot with the given data source.
    ///
    /// Never panics on malformed input: e.g. column-oriented data whose columns
    /// have different lengths is padded with `NA` and reported as a
    /// [`GGError::ValidationError`] by [`try_build`](Self::try_build) and the
    /// `render_*`/`save*` methods.
    /// One-call quick plot (ggplot2's `qplot()` / `quickplot()`): points for
    /// `x` + `y`; with only `x`, a histogram (numeric) or bar chart (text).
    pub fn qplot(data: impl GGData, x: &str, y: Option<&str>) -> Self {
        let plot = GGPlot::new(data);
        match y {
            Some(y) => plot.aes(Aes::new().x(x).y(y)).geom_point(),
            None => {
                let text = plot
                    .data
                    .column(x)
                    .and_then(|c| c.iter().find(|v| !v.is_na()))
                    .is_some_and(|v| matches!(v, Value::Str(_) | Value::Bool(_)));
                let plot = plot.aes(Aes::new().x(x));
                if text {
                    plot.geom_bar()
                } else {
                    plot.geom_histogram()
                }
            }
        }
    }

    pub fn new(data: impl GGData) -> Self {
        GGPlot {
            data: data.into_dataframe(),
            mapping: Aes::default(),
            layers: Vec::new(),
            scales: Vec::new(),
            coord: Box::new(CoordCartesian::new()),
            theme: Theme::default(),
            labels: Labels::default(),
            facet: Facet::default(),
            facet_axes: crate::facet::FacetAxes::default(),
            annotations: Vec::new(),
            guide_legend: crate::guide::config::GuideLegend::default(),
            warnings: Vec::new(),
            legend_bottom_share: None,
            clip: true,
            svg_classes: false,
            legend_auto: None,
            default_aspect_ratio: None,
            hide_position_guides: false,
            hide_y_guides: false,
            locale: None,
            svg_root_data: true,
            root_attrs: Vec::new(),
            svg_warnings_attr: false,
            svg_formatted_values: false,
            layer_svg_attrs: Vec::new(),
            svg_title: None,
            svg_desc: None,
        }
    }

    /// Set the plot-level aesthetic mapping.
    pub fn aes(mut self, mapping: Aes) -> Self {
        self.warnings.extend(mapping.warnings.iter().cloned());
        self.mapping = mapping;
        self
    }

    // ─── Geom shortcuts ──────────────────────────────────────────

    pub fn geom_point(self) -> Self {
        self.add_geom(GeomPoint::default())
    }

    pub fn geom_point_with(self, geom: GeomPoint) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_line(self) -> Self {
        self.add_geom(GeomLine::default())
    }

    pub fn geom_line_with(self, geom: GeomLine) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_bar(self) -> Self {
        self.add_geom(GeomBar::default())
    }

    pub fn geom_bar_with(self, geom: GeomBar) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_histogram(self) -> Self {
        self.add_geom(GeomHistogram::default())
    }

    pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_boxplot(self) -> Self {
        self.add_geom(GeomBoxplot::default())
    }

    pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_smooth(self) -> Self {
        self.add_geom(GeomSmooth::default())
    }

    pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_col(self) -> Self {
        self.add_geom(GeomCol::default())
    }

    pub fn geom_col_with(self, geom: GeomCol) -> Self {
        self.add_geom_with(geom)
    }

    /// Horizontal reference line at a constant `yintercept`. Like ggplot2 the
    /// intercept trains the y scale (the line is always visible) and the line
    /// appears in every facet panel.
    pub fn geom_hline(self, yintercept: f64) -> Self {
        self.add_refline(
            GeomHline::new(yintercept),
            false,
            &[("yintercept", yintercept)],
        )
    }

    /// Add a horizontal reference line with custom styling (color/linetype/width).
    pub fn geom_hline_with(self, geom: GeomHline) -> Self {
        let y = geom.yintercept;
        self.add_refline(geom, true, &[("yintercept", y)])
    }

    /// Data-mapped horizontal lines (ggplot2's `geom_hline(aes(yintercept =
    /// …))`): one line per row of the layer data (the plot data unless
    /// [`layer_data`](Self::layer_data) follows), per facet panel, styled by
    /// any `color`/`linetype`/`alpha` in `mapping`. The plot-level mapping is
    /// not inherited.
    ///
    /// ```
    /// # use ggplot_rs::prelude::*;
    /// let thresholds: Vec<(String, Vec<Value>)> = vec![
    ///     ("bound".into(), vec![Value::Float(-0.2), Value::Float(0.2)]),
    /// ];
    /// let svg = GGPlot::new(vec![
    ///         ("lag".to_string(), vec![Value::Float(1.0), Value::Float(2.0)]),
    ///         ("acf".to_string(), vec![Value::Float(0.5), Value::Float(0.1)]),
    ///     ])
    ///     .aes(Aes::new().x("lag").y("acf"))
    ///     .geom_col()
    ///     .geom_hline_aes(Aes::new().yintercept("bound"))
    ///     .layer_data(thresholds)
    ///     .render_svg_native()
    ///     .unwrap();
    /// assert!(svg.contains("data-value=\"0.2\""));
    /// ```
    pub fn geom_hline_aes(self, mapping: Aes) -> Self {
        self.add_geom(GeomHline::mapped()).layer_aes(mapping)
    }

    /// [`geom_hline_aes`](Self::geom_hline_aes) with custom default styling.
    pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
        self.add_geom_with(geom).layer_aes(mapping)
    }

    /// Vertical reference line at a constant `xintercept` (trains the x
    /// scale, appears in every panel).
    pub fn geom_vline(self, xintercept: f64) -> Self {
        self.add_refline(
            GeomVline::new(xintercept),
            false,
            &[("xintercept", xintercept)],
        )
    }

    /// Add a vertical reference line with custom styling (color/linetype/width).
    pub fn geom_vline_with(self, geom: GeomVline) -> Self {
        let x = geom.xintercept;
        self.add_refline(geom, true, &[("xintercept", x)])
    }

    /// Data-mapped vertical lines (`aes(xintercept = …)`), one per row; see
    /// [`geom_hline_aes`](Self::geom_hline_aes).
    pub fn geom_vline_aes(self, mapping: Aes) -> Self {
        self.add_geom(GeomVline::mapped()).layer_aes(mapping)
    }

    /// [`geom_vline_aes`](Self::geom_vline_aes) with custom default styling.
    pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
        self.add_geom_with(geom).layer_aes(mapping)
    }

    /// Line `y = intercept + slope · x` in data space, clipped to the panel.
    /// It does not train any scale (as in ggplot2).
    pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
        self.add_refline(
            GeomAbline::new(slope, intercept),
            false,
            &[("slope", slope), ("intercept", intercept)],
        )
    }

    /// Add a slope/intercept reference line with custom styling.
    pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
        let (b, a) = (geom.slope, geom.intercept);
        self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
    }

    /// Data-mapped ablines (`aes(slope = …, intercept = …)`), one per row; a
    /// missing aesthetic defaults to slope 1 / intercept 0.
    pub fn geom_abline_aes(self, mapping: Aes) -> Self {
        self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
    }

    /// [`geom_abline_aes`](Self::geom_abline_aes) with custom default styling.
    pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
        self.add_geom_with(geom).layer_aes(mapping)
    }

    /// A constant reference line as ggplot2 builds it: a one-row layer frame
    /// holding the constants, mapped to their aesthetics.
    fn add_refline(
        self,
        geom: impl Geom + 'static,
        explicit: bool,
        values: &[(&str, f64)],
    ) -> Self {
        let mut data = DataFrame::new();
        let mut mapping = Aes::new();
        for (col, v) in values {
            data.add_column(col.to_string(), vec![Value::Float(*v)]);
            mapping = match *col {
                "xintercept" => mapping.xintercept(col),
                "yintercept" => mapping.yintercept(col),
                "slope" => mapping.slope(col),
                _ => mapping.intercept(col),
            };
        }
        let plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.layer_aes(mapping).layer_data(data)
    }

    pub fn geom_text(self) -> Self {
        self.add_geom(GeomText::default())
    }

    pub fn geom_text_with(self, geom: GeomText) -> Self {
        self.add_geom_with(geom)
    }

    /// Annotate with a correlation coefficient + p-value (`ggpubr::stat_cor()`).
    /// Adds a text layer whose statistic computes Pearson correlation via
    /// anofox-statistics; use [`GGPlot::stat_cor_with`] to pick Spearman or set
    /// the label position.
    #[cfg(feature = "ggpubr")]
    pub fn stat_cor(self) -> Self {
        self.geom_text().stat(crate::stat::cor::StatCor::default())
    }

    /// [`GGPlot::stat_cor`] with an explicit [`StatCor`](crate::stat::cor::StatCor)
    /// (method / label position).
    #[cfg(feature = "ggpubr")]
    pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
        self.geom_text().stat(stat)
    }

    /// Annotate grouped data with a group-comparison p-value
    /// (`ggpubr::stat_compare_means()`). Adds a text layer whose statistic
    /// compares y across the discrete x groups (Wilcoxon for two groups,
    /// Kruskal-Wallis for more) via anofox-statistics.
    #[cfg(feature = "ggpubr")]
    pub fn stat_compare_means(self) -> Self {
        self.geom_text()
            .stat(crate::stat::compare_means::StatCompareMeans::default())
    }

    /// [`GGPlot::stat_compare_means`] with an explicit
    /// [`StatCompareMeans`](crate::stat::compare_means::StatCompareMeans).
    #[cfg(feature = "ggpubr")]
    pub fn stat_compare_means_with(
        self,
        stat: crate::stat::compare_means::StatCompareMeans,
    ) -> Self {
        self.geom_text().stat(stat)
    }

    /// Auto-draw pairwise significance brackets (`ggpubr::stat_compare_means`
    /// with `comparisons`). For each `(group_a, group_b)` pair it runs a
    /// two-sample test (Wilcoxon by default) on the plot's y-values, formats the
    /// p-value, and stacks a labelled [`geom_bracket`](GGPlot::geom_bracket)
    /// above the data. Uses the plot's x/y mapping and data.
    #[cfg(feature = "ggpubr")]
    pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
        self.stat_compare_means_pairwise_with(
            crate::stat::compare_means::CompareMethod::Auto,
            comparisons,
        )
    }

    /// [`stat_compare_means_pairwise`](GGPlot::stat_compare_means_pairwise) with
    /// an explicit test method.
    #[cfg(feature = "ggpubr")]
    pub fn stat_compare_means_pairwise_with(
        self,
        method: crate::stat::compare_means::CompareMethod,
        comparisons: &[(&str, &str)],
    ) -> Self {
        // Resolve the x/y source columns from the plot mapping + data.
        let col_for = |a: crate::aes::Aesthetic| {
            self.mapping
                .mappings
                .iter()
                .find(|m| m.aesthetic == a)
                .map(|m| m.column.clone())
        };
        let (xcol, ycol) = match (
            col_for(crate::aes::Aesthetic::X),
            col_for(crate::aes::Aesthetic::Y),
        ) {
            (Some(x), Some(y)) => (x, y),
            _ => return self,
        };
        let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
            (Some(x), Some(y)) => (x, y),
            _ => return self,
        };

        // Bucket y by x category (first-seen order) and find the data range.
        let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
        let mut ymax = f64::NEG_INFINITY;
        let mut ymin = f64::INFINITY;
        for (xv, yv) in xc.iter().zip(yc.iter()) {
            let y = match yv.as_f64() {
                Some(y) if y.is_finite() => y,
                _ => continue,
            };
            ymax = ymax.max(y);
            ymin = ymin.min(y);
            let key = xv.to_group_key();
            if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
                g.1.push(y);
            } else {
                groups.push((key, vec![y]));
            }
        }
        if groups.len() < 2 {
            return self;
        }
        let step = if ymax > ymin {
            (ymax - ymin) * 0.12
        } else {
            1.0
        };

        // One stacked bracket per resolvable comparison.
        let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
        let mut placed = 0usize;
        for (a, b) in comparisons {
            let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
            let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
            let (ga, gb) = match (ga, gb) {
                (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
                _ => continue,
            };
            let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
                Some(p) => p,
                None => continue,
            };
            xmin_v.push(Value::Str((*a).to_string()));
            xmax_v.push(Value::Str((*b).to_string()));
            y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
            label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
            placed += 1;
        }
        if xmin_v.is_empty() {
            return self;
        }

        let data = vec![
            ("xmin".to_string(), xmin_v),
            ("xmax".to_string(), xmax_v),
            ("y".to_string(), y_v),
            ("label".to_string(), label_v),
        ];
        self.add_geom(crate::geom::bracket::GeomBracket::default())
            .layer_data(data)
            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
    }

    /// Draw a significance bracket over the plot (`ggpubr::geom_bracket`): a bar
    /// spanning the categorical positions `xmin`..`xmax` at height `y`, captioned
    /// with `label` (e.g. a p-value or significance stars). Pairs with a boxplot
    /// and [`stat_compare_means`](GGPlot::stat_compare_means).
    pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
        self.geom_bracket_many(
            crate::geom::bracket::GeomBracket::default(),
            &[(xmin, xmax, y, label)],
        )
    }

    /// Draw several significance brackets at once with a configured
    /// [`GeomBracket`](crate::geom::bracket::GeomBracket). Each tuple is
    /// `(xmin, xmax, y, label)`.
    pub fn geom_bracket_many(
        self,
        geom: crate::geom::bracket::GeomBracket,
        brackets: &[(&str, &str, f64, &str)],
    ) -> Self {
        let xmin = brackets
            .iter()
            .map(|b| Value::Str(b.0.to_string()))
            .collect::<Vec<_>>();
        let xmax = brackets
            .iter()
            .map(|b| Value::Str(b.1.to_string()))
            .collect::<Vec<_>>();
        let y = brackets
            .iter()
            .map(|b| Value::Float(b.2))
            .collect::<Vec<_>>();
        let label = brackets
            .iter()
            .map(|b| Value::Str(b.3.to_string()))
            .collect::<Vec<_>>();
        let data = vec![
            ("xmin".to_string(), xmin),
            ("xmax".to_string(), xmax),
            ("y".to_string(), y),
            ("label".to_string(), label),
        ];
        self.add_geom(geom)
            .layer_data(data)
            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
    }

    /// Significance brackets from a precomputed test table (ggpubr's
    /// `stat_pvalue_manual` / `geom_bracket(data = …)`) — e.g. the anofox
    /// `test` contract output (`group1`, `group2`, `p_adj`/`p_value`, optional
    /// `y_position`, `label`). No test is recomputed. See
    /// [`BracketTable`](crate::geom::bracket::BracketTable) for the column
    /// rules, label templates (`"p = {p_adj}"`, `"{p.signif}"`) and the
    /// automatic stacking of rows without a `y_position`. Rows that cannot be
    /// drawn are dropped with a build warning.
    pub fn geom_bracket_table(
        mut self,
        table: impl GGData,
        spec: crate::geom::bracket::BracketTable,
    ) -> Self {
        let table = table.into_dataframe();
        let col_for = |a: crate::aes::Aesthetic| {
            self.mapping
                .mappings
                .iter()
                .find(|m| m.aesthetic == a)
                .map(|m| m.column.clone())
        };
        // The plot's x categories (to reject unknown groups) and finite y
        // range (to stack brackets above the data).
        let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
            .and_then(|c| self.data.column(&c))
            .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
            .map(|col| {
                let mut seen = std::collections::HashSet::new();
                col.iter()
                    .filter(|v| !v.is_na())
                    .map(|v| v.to_group_key())
                    .filter(|k| seen.insert(k.clone()))
                    .collect()
            })
            .unwrap_or_default();
        let y_range = col_for(crate::aes::Aesthetic::Y)
            .and_then(|c| self.data.column(&c))
            .and_then(|col| {
                let (lo, hi) = col
                    .iter()
                    .filter_map(|v| v.as_f64())
                    .filter(|v| v.is_finite())
                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
                        (lo.min(v), hi.max(v))
                    });
                (lo <= hi).then_some((lo, hi))
            });
        let mut warnings = Vec::new();
        let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
        self.warnings.extend(warnings);
        match resolved {
            Some(data) => self
                .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
                .layer_data(data)
                .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
            None => self,
        }
    }

    /// Text labels that repel each other and their points
    /// (`ggrepel::geom_text_repel`) — deterministic (seeded) layout; see
    /// [`GeomTextRepel`](crate::geom::repel::GeomTextRepel). Requires `x`,
    /// `y` and `label`.
    pub fn geom_text_repel(self) -> Self {
        self.add_geom(crate::geom::repel::GeomTextRepel::default())
    }

    /// [`geom_text_repel`](Self::geom_text_repel) with a configured geom
    /// (padding, nudge, `max_overlaps`, seed, …).
    pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
        self.add_geom_with(geom)
    }

    /// Boxed labels that repel each other and their points
    /// (`ggrepel::geom_label_repel`).
    pub fn geom_label_repel(self) -> Self {
        self.add_geom(crate::geom::repel::GeomLabelRepel::default())
    }

    /// [`geom_label_repel`](Self::geom_label_repel) with a configured geom.
    pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_label(self) -> Self {
        self.add_geom(GeomLabel::default())
    }

    pub fn geom_label_with(self, geom: GeomLabel) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_area(self) -> Self {
        self.add_geom(GeomArea::default())
    }

    pub fn geom_area_with(self, geom: GeomArea) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_ribbon(self) -> Self {
        self.add_geom(GeomRibbon::default())
    }

    pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_errorbar(self) -> Self {
        self.add_geom(GeomErrorbar::default())
    }

    pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_segment(self) -> Self {
        self.add_geom(GeomSegment::default())
    }

    pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_density(self) -> Self {
        self.add_geom(GeomDensity::default())
    }

    pub fn geom_density_with(self, geom: GeomDensity) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_rug(self) -> Self {
        self.add_geom(GeomRug::default())
    }

    pub fn geom_rug_with(self, geom: GeomRug) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_jitter(self) -> Self {
        self.add_geom(GeomJitter::default())
    }

    pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_path(self) -> Self {
        self.add_geom(GeomPath::default())
    }

    pub fn geom_path_with(self, geom: GeomPath) -> Self {
        self.add_geom_with(geom)
    }

    /// Plot `fun(x)` as a line over the plot data's x range (ggplot2's
    /// `geom_function()`); see [`geom_function_xlim`](Self::geom_function_xlim)
    /// to plot without data.
    pub fn geom_function(self, fun: impl Fn(f64) -> f64 + Send + Sync + 'static) -> Self {
        self.geom_line()
            .stat(crate::stat::function::StatFunction::new(fun))
    }

    /// Plot `fun(x)` over `[lo, hi]` without any data (`geom_function(xlim =)`).
    pub fn geom_function_xlim(
        self,
        fun: impl Fn(f64) -> f64 + Send + Sync + 'static,
        lo: f64,
        hi: f64,
    ) -> Self {
        let range = vec![("x".to_string(), vec![Value::Float(lo), Value::Float(hi)])];
        self.geom_line()
            .layer_data(range)
            .layer_aes(Aes::new().x("x"))
            .stat(crate::stat::function::StatFunction::new(fun).with_xlim(lo, hi))
    }

    /// Join each group's points (in x order) with steps or straight lines
    /// (ggplot2 4.0's `stat_connect(connection)`), drawn as a path.
    pub fn stat_connect(self, connection: crate::stat::connect::Connection) -> Self {
        self.geom_path()
            .stat(crate::stat::connect::StatConnect::new(connection))
    }

    /// Points with duplicate rows dropped (`stat_unique()`); `.stat(StatUnique)`
    /// applies it to any other layer.
    pub fn stat_unique(self) -> Self {
        self.geom_point().stat(crate::stat::unique::StatUnique)
    }

    /// Points from an arbitrary per-group transform (ggplot2 4.0's
    /// `stat_manual(fun)`); `.stat(StatManual::new(f))` for other geoms.
    pub fn stat_manual(
        self,
        fun: impl Fn(&crate::data::DataFrame) -> crate::data::DataFrame + Send + Sync + 'static,
    ) -> Self {
        self.geom_point()
            .stat(crate::stat::manual::StatManual::new(fun))
    }

    /// Hexagons filled with a summary of the raw `z` column
    /// (`stat_summary_hex(fun)`).
    pub fn stat_summary_hex(self, fun: crate::stat::summary::SummaryFun) -> Self {
        self.geom_hex()
            .stat(crate::stat::binhex::StatSummaryHex::new(fun))
    }

    /// A point per WKT `geometry` (feature `sf`; `stat_sf_coordinates()`).
    /// Use `.stat(StatSfCoordinates::default())` to put text, labels or any
    /// other geom on a map.
    #[cfg(feature = "sf")]
    pub fn stat_sf_coordinates(self) -> Self {
        self.geom_point()
            .stat(crate::stat::sf_coordinates::StatSfCoordinates::default())
    }

    /// Add a confidence-ellipse layer (default 95%) as a path per group.
    pub fn stat_ellipse(self) -> Self {
        self.geom_path()
            .stat(crate::stat::ellipse::StatEllipse::default())
    }

    /// Add a confidence-ellipse layer at the given level (0, 1).
    pub fn stat_ellipse_level(self, level: f64) -> Self {
        self.geom_path()
            .stat(crate::stat::ellipse::StatEllipse::new(level))
    }

    /// Add a quantile-regression line for each `tau` as a separate path layer
    /// (R's `stat_quantile`). Backed by anofox-regression (feature `regression`).
    #[cfg(feature = "regression")]
    pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
        for &tau in taus {
            self = self
                .geom_path()
                .stat(crate::stat::quantile::StatQuantile::new(tau));
        }
        self
    }

    /// Quantile-regression lines at the quartiles (0.25, 0.5, 0.75).
    #[cfg(feature = "regression")]
    pub fn geom_quantile(self) -> Self {
        self.stat_quantile(&[0.25, 0.5, 0.75])
    }

    pub fn geom_step(self) -> Self {
        self.add_geom(GeomStep::default())
    }

    pub fn geom_step_with(self, geom: GeomStep) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_freqpoly(self) -> Self {
        self.add_geom(GeomFreqpoly::default())
    }

    pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_linerange(self) -> Self {
        self.add_geom(GeomLinerange::default())
    }

    pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_pointrange(self) -> Self {
        self.add_geom(GeomPointrange::default())
    }

    pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_crossbar(self) -> Self {
        self.add_geom(GeomCrossbar::default())
    }

    pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_spoke(self) -> Self {
        self.add_geom(GeomSpoke::default())
    }

    pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_rect(self) -> Self {
        self.add_geom(GeomRect::default())
    }

    pub fn geom_rect_with(self, geom: GeomRect) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_tile(self) -> Self {
        self.add_geom(GeomTile::default())
    }

    pub fn geom_tile_with(self, geom: GeomTile) -> Self {
        self.add_geom_with(geom)
    }

    /// Dense regular grid of filled cells (heatmap/raster) from x, y, fill.
    pub fn geom_raster(self) -> Self {
        self.add_geom(crate::geom::raster::GeomRaster::default())
    }

    pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_polygon(self) -> Self {
        self.add_geom(GeomPolygon::default())
    }

    pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
        self.add_geom_with(geom)
    }

    /// Render simple-features geometry from a WKT `geometry` column (feature `sf`).
    #[cfg(feature = "sf")]
    pub fn geom_sf(self) -> Self {
        self.add_geom(crate::geom::sf::GeomSf::default())
    }

    #[cfg(feature = "sf")]
    pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
        self.add_geom_with(geom)
    }

    /// Labels placed inside `geom_sf` polygons (feature `sf`): `label`
    /// aesthetic, `geometry` column — ggplot2's `geom_sf_text`.
    #[cfg(feature = "sf")]
    pub fn geom_sf_text(self) -> Self {
        self.add_geom(crate::geom::sf_text::GeomSfText::default())
    }

    #[cfg(feature = "sf")]
    pub fn geom_sf_text_with(self, geom: crate::geom::sf_text::GeomSfText) -> Self {
        self.add_geom_with(geom)
    }

    /// Like [`geom_sf_text`](Self::geom_sf_text), on a background box —
    /// ggplot2's `geom_sf_label`.
    #[cfg(feature = "sf")]
    pub fn geom_sf_label(self) -> Self {
        self.add_geom(crate::geom::sf_text::GeomSfLabel::default())
    }

    #[cfg(feature = "sf")]
    pub fn geom_sf_label_with(self, geom: crate::geom::sf_text::GeomSfLabel) -> Self {
        self.add_geom_with(geom)
    }

    /// A metric scale bar in a panel corner (feature `sf`) — ggspatial's
    /// `annotation_scale()`. Assumes the X/Y domain is in metres (any
    /// `geom_sf` projection other than `SfProjection::PlateCarree`).
    #[cfg(feature = "sf")]
    pub fn annotation_scale(self) -> Self {
        self.add_geom(crate::geom::annotation_scale::GeomAnnotationScale::default())
    }

    #[cfg(feature = "sf")]
    pub fn annotation_scale_with(
        self,
        geom: crate::geom::annotation_scale::GeomAnnotationScale,
    ) -> Self {
        self.add_geom_with(geom)
    }

    /// A north arrow in a panel corner (feature `sf`) — see
    /// [`GeomNorthArrow`](crate::geom::annotation_scale::GeomNorthArrow).
    #[cfg(feature = "sf")]
    pub fn annotation_north_arrow_with(
        self,
        geom: crate::geom::annotation_scale::GeomNorthArrow,
    ) -> Self {
        self.add_geom_with(geom)
    }

    /// A small, muted attribution text in a panel corner (feature `sf`) —
    /// e.g. `"© Natural Earth"`.
    #[cfg(feature = "sf")]
    pub fn annotation_attribution(self, text: impl Into<String>) -> Self {
        self.add_geom(crate::geom::annotation_scale::GeomAttribution::new(text))
    }

    /// A raster basemap from an XYZ tile provider (feature `tiles`, #325),
    /// drawn under every other layer: tiles fetched through `fetcher` for
    /// the plot's Web-Mercator view (project `geom_sf` layers with
    /// `SfProjection::Mercator`, add `coord_sf()`), at a zoom picked from
    /// the panel size, plus the source's attribution in a corner. E.g.
    /// `annotation_map_tile(TileSource::xyz("https://tile.openstreetmap.org/{z}/{x}/{y}.png")
    /// .attribution("© OpenStreetMap contributors"), my_http_fetcher)`.
    #[cfg(feature = "tiles")]
    pub fn annotation_map_tile(
        self,
        source: crate::geom::map_tile::TileSource,
        fetcher: impl crate::geom::map_tile::TileFetcher + 'static,
    ) -> Self {
        self.annotation_map_tile_with(crate::geom::map_tile::GeomMapTile::new(source, fetcher))
    }

    /// [`annotation_map_tile`](Self::annotation_map_tile) with a configured
    /// layer (fixed zoom, detail, opacity).
    #[cfg(feature = "tiles")]
    pub fn annotation_map_tile_with(self, geom: crate::geom::map_tile::GeomMapTile) -> Self {
        let attribution = geom.source.attribution.clone();
        let mut plot = self.add_geom_with(geom);
        // Under every other layer (per-layer settings shift up by one).
        if let Some(layer) = plot.layers.pop() {
            plot.layers.insert(0, layer);
            for (idx, ..) in plot.layer_svg_attrs.iter_mut() {
                *idx += 1;
            }
        }
        if attribution.is_empty() {
            plot
        } else {
            plot.annotation_attribution(attribution)
        }
    }

    #[cfg(feature = "sf")]
    pub fn annotation_attribution_with(
        self,
        geom: crate::geom::annotation_scale::GeomAttribution,
    ) -> Self {
        self.add_geom_with(geom)
    }

    /// The square `n × m` guide for a
    /// [`ScaleFillBivariate`](crate::scale::bivariate::ScaleFillBivariate)
    /// fill scale (feature `sf`): two axis captions, biscale's own legend
    /// shape — drawn as a furniture layer, not through the ordinary
    /// per-aesthetic legend (set `.legend_position(LegendPosition::None)`
    /// to hide that one). [`GeomBivariateLegend::from_scale`] builds this
    /// from the same scale used for the fill, so the swatches match.
    #[cfg(feature = "sf")]
    pub fn bivariate_legend(
        self,
        geom: crate::geom::bivariate_legend::GeomBivariateLegend,
    ) -> Self {
        self.add_geom(geom)
    }

    /// Like [`Self::bivariate_legend`], but with each cell's row count
    /// drawn centred in its swatch — build with
    /// [`GeomBivariateLegend::counts`](crate::geom::bivariate_legend::GeomBivariateLegend::counts)
    /// (#259).
    #[cfg(feature = "sf")]
    pub fn bivariate_legend_counts(
        self,
        geom: crate::geom::bivariate_legend::GeomBivariateLegendCounts,
    ) -> Self {
        self.add_geom(geom)
    }

    pub fn geom_curve(self) -> Self {
        self.add_geom(GeomCurve::default())
    }

    pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_violin(self) -> Self {
        self.add_geom(GeomViolin::default())
    }

    pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
        self.add_geom_with(geom)
    }

    /// A ridgeline plot: one density of `x` per level of a discrete `y`,
    /// drawn upward from the level's baseline and overlapping the row above
    /// ([`GeomDensityRidges::scale`]) — distributions over time or groups.
    pub fn geom_density_ridges(self) -> Self {
        self.add_geom(GeomDensityRidges::default())
    }

    pub fn geom_density_ridges_with(self, geom: GeomDensityRidges) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_dotplot(self) -> Self {
        self.add_geom(GeomDotplot::default())
    }

    pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_qq(self) -> Self {
        self.add_geom(GeomQQ::default())
    }

    pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_qq_line(self) -> Self {
        self.add_geom(GeomQQLine::default())
    }

    pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_bin2d(self) -> Self {
        self.add_geom(GeomBin2d::default())
    }

    pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_hex(self) -> Self {
        self.add_geom(GeomHex::default())
    }

    pub fn geom_hex_with(self, geom: GeomHex) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_count(self) -> Self {
        self.add_geom(GeomCount::default())
    }

    pub fn geom_count_with(self, geom: GeomCount) -> Self {
        self.add_geom_with(geom)
    }

    pub fn geom_contour(self) -> Self {
        self.add_geom(GeomContour::default())
    }

    pub fn geom_contour_with(self, geom: GeomContour) -> Self {
        self.add_geom_with(geom)
    }

    /// Filled contour bands from gridded (x, y, z) data — draws polygons filled by
    /// band level. Pair with a continuous fill scale (e.g. `scale_fill_viridis_c`).
    pub fn geom_contour_filled(self) -> Self {
        self.add_geom(GeomPolygon {
            line_width: 0.0,
            alpha: 1.0,
            ..GeomPolygon::default()
        })
        .stat(crate::stat::contour_filled::StatContourFilled::default())
    }

    pub fn geom_density2d(self) -> Self {
        self.add_geom(GeomDensity2d::default())
    }

    pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
        self.add_geom_with(geom)
    }

    /// Waterfall (bridge) chart: map `x` (steps, in data order) and `y` (each
    /// step's change). Bars float from the running total and are filled by
    /// direction (Increase / Decrease / Total, with a legend); dashed
    /// connectors join consecutive bars. See [`geom_waterfall_with`](Self::geom_waterfall_with)
    /// for subtotals and a closing total.
    pub fn geom_waterfall(self) -> Self {
        self.default_styled(|p| {
            p.geom_waterfall_with(crate::geom::waterfall::GeomWaterfall::default())
        })
    }

    /// [`geom_waterfall`](Self::geom_waterfall) with explicit colours,
    /// `totals` (subtotal x levels) and `final_total`. Unless `fill` is
    /// already mapped at plot level, the layer maps `after_stat(fill =
    /// direction)`; unless a fill scale is already set, a manual fill scale
    /// with the geom's `up`/`down`/`total` colours is added (a later
    /// `scale_fill_*` call replaces it).
    pub fn geom_waterfall_with(self, geom: crate::geom::waterfall::GeomWaterfall) -> Self {
        use crate::scale::color::RGBAColor;
        use crate::stat::waterfall::{WATERFALL_DECREASE, WATERFALL_INCREASE, WATERFALL_TOTAL};
        let rgba = |(r, g, b): (u8, u8, u8)| RGBAColor::new(r, g, b);
        let mut values = vec![
            (WATERFALL_INCREASE, rgba(geom.up)),
            (WATERFALL_DECREASE, rgba(geom.down)),
        ];
        if geom.has_totals() {
            values.push((WATERFALL_TOTAL, rgba(geom.total)));
        }
        let fill_mapped = self
            .mapping
            .get_mapping(&crate::aes::Aesthetic::Fill)
            .is_some();
        let has_fill_scale = self
            .scales
            .iter()
            .any(|s| s.aesthetic() == crate::aes::Aesthetic::Fill);
        let mut plot = self.add_geom_with(geom);
        if !fill_mapped {
            plot = plot.layer_aes(Aes::new().after_stat_fill("direction"));
            if !has_fill_scale {
                plot = plot.scale_fill_manual(values);
            }
        }
        plot
    }

    /// Pareto chart: map `x` (categories) and `y` (values, summed per
    /// category). Bars are sorted descending and a cumulative line with
    /// points rises to the grand total, read against a 0–100 % right axis.
    pub fn geom_pareto(self) -> Self {
        self.add_pareto(crate::geom::pareto::GeomPareto::default(), false)
    }

    /// [`geom_pareto`](Self::geom_pareto) with explicit styling, sorting or a
    /// threshold line. Unless a y scale is already set, a continuous y scale
    /// with a [`SecAxis::percent_of_max`](crate::scale::sec_axis::SecAxis::percent_of_max)
    /// secondary axis ("Cumulative %") is added; a later `scale_y_continuous`
    /// replaces it.
    pub fn geom_pareto_with(self, geom: crate::geom::pareto::GeomPareto) -> Self {
        self.add_pareto(geom, true)
    }

    fn add_pareto(self, geom: crate::geom::pareto::GeomPareto, explicit: bool) -> Self {
        let has_y_scale = self
            .scales
            .iter()
            .any(|s| s.aesthetic() == crate::aes::Aesthetic::Y);
        let plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        if has_y_scale {
            plot
        } else {
            plot.scale_y_continuous(ScaleContinuous::new().with_sec_axis(
                crate::scale::sec_axis::SecAxis::percent_of_max().with_name("Cumulative %"),
            ))
        }
    }

    /// Sankey diagram from an edge list: map `from`, `to` and optionally
    /// `weight` (`Aes::new().from("src").to("dst").weight("flow")`). Nodes
    /// are placed in columns by their depth, sized by their flow and
    /// coloured by name through the fill scale (no legend — nodes are
    /// labelled); links take their source's colour. Axes and grid are
    /// hidden, whatever the theme.
    pub fn geom_sankey(self) -> Self {
        self.add_sankey(crate::geom::sankey::GeomSankey::default(), false)
    }

    /// [`geom_sankey`](Self::geom_sankey) with explicit layout and styling.
    pub fn geom_sankey_with(self, geom: crate::geom::sankey::GeomSankey) -> Self {
        self.add_sankey(geom, true)
    }

    fn add_sankey(self, geom: crate::geom::sankey::GeomSankey, explicit: bool) -> Self {
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.hide_position_guides = true;
        plot.layer_aes(Aes::new().after_stat_fill("node"))
            .show_legend(false)
    }

    /// Chord diagram / dependency wheel from an edge list: map `from`, `to`
    /// and optionally `weight`. Each node is an arc sized by its total flow
    /// (in + out); each link a ribbon through the centre, coloured by its
    /// source. Nodes are coloured by name through the fill scale (no legend
    /// — they are labelled); axes and grid are hidden and the panel is kept
    /// square so the circle stays round.
    pub fn geom_chord(self) -> Self {
        self.add_chord(crate::geom::chord::GeomChord::default(), false)
    }

    /// [`geom_chord`](Self::geom_chord) with explicit padding and styling.
    pub fn geom_chord_with(self, geom: crate::geom::chord::GeomChord) -> Self {
        self.add_chord(geom, true)
    }

    fn add_chord(self, geom: crate::geom::chord::GeomChord, explicit: bool) -> Self {
        let (ex, ey) = geom.extents();
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(ey / ex);
        plot.layer_aes(Aes::new().after_stat_fill("node"))
            .show_legend(false)
    }

    /// Arc diagram from an edge list: map `from`, `to` and optionally
    /// `weight`. Nodes sit on a line (sized by total flow), links are arcs
    /// whose width is their weight. Coloured by node name through the fill
    /// scale (no legend — nodes are labelled); axes and grid are hidden.
    pub fn geom_arcdiagram(self) -> Self {
        self.add_arcdiagram(crate::geom::arcdiagram::GeomArcdiagram::default(), false)
    }

    /// [`geom_arcdiagram`](Self::geom_arcdiagram) with explicit ordering,
    /// direction and styling.
    pub fn geom_arcdiagram_with(self, geom: crate::geom::arcdiagram::GeomArcdiagram) -> Self {
        self.add_arcdiagram(geom, true)
    }

    fn add_arcdiagram(self, geom: crate::geom::arcdiagram::GeomArcdiagram, explicit: bool) -> Self {
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.hide_position_guides = true;
        plot.layer_aes(Aes::new().after_stat_fill("node"))
            .show_legend(false)
    }

    /// Squarified treemap: map `weight` (tile area) and optionally
    /// `subgroup` (tiles nest inside group rectangles), `fill` and `label`
    /// (`Aes::new().weight("sales").subgroup("region").label("country")`).
    /// When `subgroup` is mapped at plot level and `fill` is not, tiles are
    /// filled by subgroup. The panel aspect matches the layout so tiles come
    /// out square; the position scales get no expansion and the axes and
    /// grid are hidden.
    pub fn geom_treemap(self) -> Self {
        self.add_treemap(crate::geom::treemap::GeomTreemap::default(), false)
    }

    /// [`geom_treemap`](Self::geom_treemap) with explicit layout and styling.
    pub fn geom_treemap_with(self, geom: crate::geom::treemap::GeomTreemap) -> Self {
        self.add_treemap(geom, true)
    }

    fn add_treemap(self, geom: crate::geom::treemap::GeomTreemap, explicit: bool) -> Self {
        use crate::aes::Aesthetic;
        let aspect = geom.aspect;
        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
        let fill_by = match (
            self.mapping.get_mapping(&Aesthetic::Fill),
            self.mapping.get_mapping(&Aesthetic::Subgroup),
        ) {
            (None, Some(sub)) => Some(sub.to_string()),
            _ => None,
        };
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0 / aspect.max(1e-6));
        if let Some(sub) = fill_by {
            plot = plot.layer_aes(Aes::new().fill(&sub));
        }
        if !has_x {
            plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
        }
        if !has_y {
            plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
        }
        plot
    }

    /// Sunburst over the hierarchy columns `levels` (outermost first),
    /// sized by `weight` (1 per row when unmapped): concentric rings, one per
    /// level, each node's angle ∝ its value and nested in its parent's.
    /// Sets `coord_polar`, colours each branch by its top-level ancestor
    /// (lighter further out; no legend — sectors are labelled), drops scale
    /// expansion and hides the position guides.
    pub fn geom_sunburst<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
        let geom = crate::geom::partition::GeomPartition::sunburst(levels);
        // The hole is `hole` level-widths of the `levels.len() + hole` radius.
        let depth = geom.levels.len().max(1) as f64;
        let inner = geom.hole / (geom.hole + depth);
        let mut plot = self.default_styled(|p| p.geom_partition_with(geom));
        plot.coord = Box::new(CoordPolar::new().inner_radius(inner));
        plot
    }

    /// Icicle chart over `levels`: the partition of
    /// [`geom_sunburst`](Self::geom_sunburst) in Cartesian coordinates, root
    /// level on top.
    pub fn geom_icicle<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
        self.default_styled(|p| {
            p.geom_partition_with(crate::geom::partition::GeomPartition::icicle(levels))
        })
    }

    /// A partition layer with explicit settings (sunburst under
    /// `coord_polar`, icicle otherwise); same defaults as the shortcuts
    /// except the coordinate system, which is left as is.
    pub fn geom_partition_with(self, geom: crate::geom::partition::GeomPartition) -> Self {
        use crate::aes::Aesthetic;
        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
        let fill_mapped = self.mapping.get_mapping(&Aesthetic::Fill).is_some();
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        if !fill_mapped {
            plot = plot
                .layer_aes(Aes::new().after_stat_fill("root"))
                .show_legend(false);
        }
        if !has_x {
            plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
        }
        if !has_y {
            plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
        }
        plot
    }

    /// Funnel chart: map `x` (stage, in data order; repeats are summed) and
    /// `y` (value). Equal-height stages whose width is proportional to the
    /// value, each tapering to the next; labels show the value and the
    /// conversion from the first stage. Stages are filled by name (no
    /// legend); axes and grid are hidden. See
    /// [`GeomFunnel::silhouette`](crate::geom::funnel::GeomFunnel::silhouette)
    /// for the Highcharts-style fixed shape.
    pub fn geom_funnel(self) -> Self {
        self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::default()))
    }

    /// Pyramid chart: apex on top, stage heights proportional to the values.
    pub fn geom_pyramid(self) -> Self {
        self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::pyramid()))
    }

    /// [`geom_funnel`](Self::geom_funnel) with an explicit shape and styling.
    pub fn geom_funnel_with(self, geom: crate::geom::funnel::GeomFunnel) -> Self {
        let fill_mapped = self
            .mapping
            .get_mapping(&crate::aes::Aesthetic::Fill)
            .is_some();
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        if !fill_mapped {
            plot = plot
                .layer_aes(Aes::new().after_stat_fill("stage"))
                .show_legend(false);
        }
        plot
    }

    /// Streamgraph: [`geom_area`](Self::geom_area) stacked around a
    /// wiggle-minimising baseline ([`StackOffset::Wiggle`](crate::position::stack::StackOffset::Wiggle)).
    /// Map `x`, `y` (non-negative) and `fill` (the series). For a
    /// symmetric ThemeRiver use
    /// `.geom_area().position(position_stack().with_offset(StackOffset::Silhouette))`.
    pub fn geom_stream(self) -> Self {
        self.geom_area().position(
            crate::position::stack::position_stack()
                .with_offset(crate::position::stack::StackOffset::Wiggle),
        )
    }

    /// Lollipop chart: a stem from 0 to `y` capped with a dot, per `x`
    /// (`coord_flip` for horizontal lollipops).
    pub fn geom_lollipop(self) -> Self {
        self.add_geom(crate::geom::lollipop::GeomLollipop::default())
    }

    pub fn geom_lollipop_with(self, geom: crate::geom::lollipop::GeomLollipop) -> Self {
        self.add_geom_with(geom)
    }

    /// Dumbbell chart: a segment from `ymin` to `ymax` per `x`, with a dot at
    /// each end (low / high colours); `coord_flip` for the usual horizontal
    /// layout.
    pub fn geom_dumbbell(self) -> Self {
        self.add_geom(crate::geom::lollipop::GeomDumbbell::default())
    }

    pub fn geom_dumbbell_with(self, geom: crate::geom::lollipop::GeomDumbbell) -> Self {
        self.add_geom_with(geom)
    }

    /// Bullet chart (horizontal): map `x` (KPI) and `y` (actual); configure
    /// the target column and range bands on the geom, e.g.
    /// `GeomBullet::default().with_target("goal").with_ranges([60.0, 80.0, 100.0])`.
    /// Sets `coord_flip`; use [`geom_bullet_vertical`](Self::geom_bullet_vertical)
    /// for upright bullets.
    pub fn geom_bullet(self, geom: crate::geom::bullet::GeomBullet) -> Self {
        self.add_geom_with(geom).coord_flip()
    }

    /// [`geom_bullet`](Self::geom_bullet) without the flip (vertical bars).
    pub fn geom_bullet_vertical(self, geom: crate::geom::bullet::GeomBullet) -> Self {
        self.add_geom_with(geom)
    }

    /// Waffle chart: map `fill` (category) and `weight` (units per row);
    /// units fill a grid `rows` high, one contiguous block per category.
    /// Axes and grid are hidden; units stay square at any panel aspect.
    pub fn geom_waffle(self, rows: usize) -> Self {
        self.default_styled(|p| p.geom_waffle_with(crate::geom::waffle::GeomWaffle::waffle(rows)))
    }

    /// Parliament (hemicycle) chart: map `fill` (party) and `weight`
    /// (seats); seats on concentric arcs, parties left to right in data
    /// order. `rows = 0` picks the number of arcs from the seat count.
    pub fn geom_parliament(self, rows: usize) -> Self {
        self.default_styled(|p| {
            p.geom_waffle_with(crate::geom::waffle::GeomWaffle::parliament(rows))
        })
    }

    /// A waffle / parliament layer with explicit settings.
    pub fn geom_waffle_with(self, geom: crate::geom::waffle::GeomWaffle) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot
    }

    /// Packed bubble chart: circles with area ∝ `weight`, packed without
    /// overlap; with `subgroup` they cluster per group (outlined). Fills by
    /// subgroup when `subgroup` is mapped at plot level and `fill` is not.
    /// The panel is square and the axes and grid are hidden.
    pub fn geom_packed_bubble(self) -> Self {
        self.default_styled(|p| {
            p.geom_packed_bubble_with(crate::geom::pack::GeomPackedBubble::default())
        })
    }

    /// [`geom_packed_bubble`](Self::geom_packed_bubble) with explicit styling.
    pub fn geom_packed_bubble_with(self, geom: crate::geom::pack::GeomPackedBubble) -> Self {
        use crate::aes::Aesthetic;
        let fill_by = match (
            self.mapping.get_mapping(&Aesthetic::Fill),
            self.mapping.get_mapping(&Aesthetic::Subgroup),
        ) {
            (None, Some(sub)) => Some(sub.to_string()),
            _ => None,
        };
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0);
        if let Some(sub) = fill_by {
            plot = plot.layer_aes(Aes::new().fill(&sub));
        }
        plot
    }

    /// Network graph from an edge list: map `from`, `to` and optionally
    /// `weight`. Force-directed layout (seeded, deterministic), edges with
    /// width ∝ weight, nodes sized by degree and labelled. Square panel,
    /// axes and grid hidden. See [`GeomNetwork`](crate::geom::network::GeomNetwork)
    /// for directed edges, other layouts and colouring by component.
    pub fn geom_network(self) -> Self {
        self.add_network(crate::geom::network::GeomNetwork::default(), false)
    }

    /// [`geom_network`](Self::geom_network) with explicit settings.
    pub fn geom_network_with(self, geom: crate::geom::network::GeomNetwork) -> Self {
        self.add_network(geom, true)
    }

    fn add_network(self, geom: crate::geom::network::GeomNetwork, explicit: bool) -> Self {
        let by_component = geom.color_components;
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0);
        if by_component {
            plot = plot
                .layer_aes(Aes::new().after_stat_fill("component"))
                .show_legend(false);
        }
        plot
    }

    /// Tree diagram from parent → child links: map `from` (parent) and `to`
    /// (child). Tidy layout (leaves evenly spaced, parents centred over
    /// their children), top-down with curved links. See
    /// [`GeomTree::org_chart`](crate::geom::tree::GeomTree::org_chart) and
    /// other orientations via [`geom_tree_with`](Self::geom_tree_with).
    /// Axes and grid are hidden.
    pub fn geom_tree(self) -> Self {
        self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::default()))
    }

    /// Dendrogram from [`dendrogram_links`](crate::stat::tree::dendrogram_links)
    /// output (`from`, `to`, `height`): step links at the merge heights,
    /// leaves labelled.
    pub fn geom_dendrogram(self) -> Self {
        self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::dendrogram()))
    }

    /// A tree layer with explicit layout and styling.
    pub fn geom_tree_with(self, geom: crate::geom::tree::GeomTree) -> Self {
        let radial = geom.orientation == crate::stat::tree::TreeOrientation::Radial;
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        if radial {
            plot.default_aspect_ratio = Some(1.0);
        }
        plot
    }

    /// Area-proportional Venn / Euler diagram: map `sets` (`"A"`, `"B"`,
    /// `"A&B"`, … — venn.js-style inclusive sizes) and `weight` (size).
    /// Exact for two and three sets' pairwise overlaps, approximate beyond.
    /// Circles are filled by set name (no legend — regions are labelled);
    /// square panel, axes and grid hidden.
    pub fn geom_venn(self) -> Self {
        self.default_styled(|p| p.geom_venn_with(crate::geom::venn::GeomVenn::default()))
    }

    /// [`geom_venn`](Self::geom_venn) with explicit styling.
    pub fn geom_venn_with(self, geom: crate::geom::venn::GeomVenn) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0);
        plot.layer_aes(Aes::new().after_stat_fill("set"))
            .show_legend(false)
    }

    /// Word cloud: map `label` (word) and `weight` (frequency); optionally
    /// `color`. Largest words placed first along a spiral from the centre,
    /// no overlaps, deterministic; words that don't fit are dropped. Axes
    /// and grid are hidden.
    pub fn geom_wordcloud(self) -> Self {
        self.default_styled(|p| {
            p.geom_wordcloud_with(crate::geom::wordcloud::GeomWordcloud::default())
        })
    }

    /// [`geom_wordcloud`](Self::geom_wordcloud) with explicit sizes,
    /// rotation share, seed and palette.
    pub fn geom_wordcloud_with(self, geom: crate::geom::wordcloud::GeomWordcloud) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot
    }

    /// Variwide chart: map `x` (category), `y` (height) and `weight` (bar
    /// width). Unless an x scale is set, the x axis is continuous over the
    /// column layout with each category named under its column (computed
    /// from the plot data, so map `x`/`weight` at plot level).
    pub fn geom_variwide(self) -> Self {
        self.default_styled(|p| {
            p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::variwide())
        })
    }

    /// Marimekko (mosaic) chart: map `x` (column), `fill` (segment) and
    /// `weight` (value). Column widths are their totals' shares, segments
    /// their share of the column (y axis 0–100 %).
    pub fn geom_marimekko(self) -> Self {
        self.default_styled(|p| {
            p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::marimekko())
        })
    }

    /// A variwide / Marimekko layer with explicit settings.
    pub fn geom_marimekko_with(self, geom: crate::geom::marimekko::GeomMarimekko) -> Self {
        use crate::aes::Aesthetic;
        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
        // Column centres and names from the plot data (same layout as the stat).
        let axis = self.mapping.get_mapping(&Aesthetic::X).and_then(|xc| {
            let x = self.data.column(xc)?;
            let w = self
                .mapping
                .get_mapping(&Aesthetic::Weight)
                .and_then(|wc| self.data.column(wc));
            let totals = crate::stat::marimekko::column_totals(x, w);
            let widths: Vec<f64> = totals.iter().map(|t| t.1).collect();
            let spans = crate::stat::marimekko::column_spans(&widths, geom.gap);
            Some((
                spans
                    .iter()
                    .map(|s| (s.0 + s.1) / 2.0)
                    .collect::<Vec<f64>>(),
                totals.into_iter().map(|t| t.0).collect::<Vec<String>>(),
            ))
        });
        let mosaic = geom.mosaic;
        let mut plot = self.add_geom_with(geom);
        if !has_x {
            let mut sx = ScaleContinuous::new().with_expand(0.0, 0.0);
            if let Some((breaks, labels)) = axis {
                sx = sx.with_breaks(breaks).with_labels(labels);
            }
            plot = plot.scale_x_continuous(sx);
        }
        if mosaic && !has_y {
            plot = plot.scale_y_continuous(
                ScaleContinuous::new()
                    .with_expand(0.0, 0.0)
                    .with_label_formatter(|v| format!("{}%", (v * 100.0).round())),
            );
        }
        plot
    }

    /// Timeline: map `x` (event time, e.g. a date), `label`, and optionally
    /// `xend` (span end) and `color`. Events sit on a central baseline with
    /// boxed labels stacked on alternating levels so they never overlap;
    /// the y axis and horizontal grid are hidden.
    pub fn geom_timeline(self) -> Self {
        let mut plot = self.add_geom(crate::geom::timeline::GeomTimeline::default());
        plot.hide_y_guides = true;
        plot
    }

    /// [`geom_timeline`](Self::geom_timeline) with explicit styling.
    pub fn geom_timeline_with(self, geom: crate::geom::timeline::GeomTimeline) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_y_guides = true;
        plot
    }

    /// X-range / Gantt chart: map `y` (task), `xmin` (start) and `xmax`
    /// (end), optionally `fill`. Zero-length tasks are milestones
    /// (diamonds). Unless a y scale is set, tasks read top to bottom in data
    /// order (from the plot data). See
    /// [`GeomXrange`](crate::geom::xrange::GeomXrange) for progress and
    /// dependency arrows.
    pub fn geom_xrange(self) -> Self {
        self.add_xrange(crate::geom::xrange::GeomXrange::default(), false)
    }

    /// [`geom_xrange`](Self::geom_xrange) with progress / dependency columns.
    pub fn geom_xrange_with(self, geom: crate::geom::xrange::GeomXrange) -> Self {
        self.add_xrange(geom, true)
    }

    fn add_xrange(self, geom: crate::geom::xrange::GeomXrange, explicit: bool) -> Self {
        use crate::aes::Aesthetic;
        let has_y = self.scales.iter().any(|s| s.aesthetic() == Aesthetic::Y);
        // First task on top: reverse the data order for the discrete axis.
        let levels: Option<Vec<String>> = self
            .mapping
            .get_mapping(&Aesthetic::Y)
            .and_then(|c| self.data.column(c))
            .map(|col| {
                let mut seen: indexmap::IndexSet<String> = indexmap::IndexSet::new();
                for v in col.iter().filter(|v| !v.is_na()) {
                    seen.insert(v.key_str().into_owned());
                }
                seen.into_iter().rev().collect()
            });
        let mut plot = if explicit {
            self.add_geom_with(geom)
        } else {
            self.add_geom(geom)
        };
        if let (false, Some(levels)) = (has_y, levels) {
            let refs: Vec<&str> = levels.iter().map(String::as_str).collect();
            plot = plot
                .scale_y_discrete(crate::scale::discrete::ScaleDiscrete::new().with_limits(refs));
        }
        plot
    }

    /// Tile-grid cartogram: map `x` (grid column), `y` (grid row, 0 at the
    /// top), `fill` and `label`; one equal tile per row (see
    /// [`us_state_grid`](crate::geom::tilemap::us_state_grid) for a ready
    /// US layout). Axes and grid are hidden.
    pub fn geom_tilemap(self, shape: crate::geom::tilemap::TileShape) -> Self {
        self.default_styled(|p| {
            p.geom_tilemap_with(crate::geom::tilemap::GeomTilemap {
                shape,
                ..Default::default()
            })
        })
    }

    /// [`geom_tilemap`](Self::geom_tilemap) with explicit styling.
    pub fn geom_tilemap_with(self, geom: crate::geom::tilemap::GeomTilemap) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot
    }

    /// Wind barbs: map `x` (and optionally `y`), and name the speed (knots,
    /// or m/s via `.meters_per_second()`) and direction (degrees the wind
    /// comes from) columns:
    /// `geom_windbarb(GeomWindbarb::new("speed", "dir"))`.
    pub fn geom_windbarb(self, geom: crate::geom::windbarb::GeomWindbarb) -> Self {
        self.add_geom(geom)
    }

    /// Variable-radius pie (Highcharts `variablepie`): map `y` (wedge
    /// angle), `radius` (wedge length) and `fill` (category), optionally
    /// `label`. Square panel, axes and grid hidden.
    pub fn geom_variable_pie(self) -> Self {
        let mut plot = self.add_geom(crate::geom::variablepie::GeomVariablePie::default());
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0);
        plot
    }

    /// [`geom_variable_pie`](Self::geom_variable_pie) with explicit settings
    /// (e.g. a donut `inner`).
    pub fn geom_variable_pie_with(self, geom: crate::geom::variablepie::GeomVariablePie) -> Self {
        let mut plot = self.add_geom_with(geom);
        plot.hide_position_guides = true;
        plot.default_aspect_ratio = Some(1.0);
        plot
    }

    /// HLC bars: a high–low bar with a close tick (no `open` needed); map
    /// `x` and `high`/`low`/`close`.
    pub fn geom_hlc(self) -> Self {
        self.add_geom(crate::geom::candlestick::GeomOhlc::hlc())
    }

    /// Heikin-Ashi candles: [`geom_candlestick`](Self::geom_candlestick)
    /// over the Heikin-Ashi transform of the OHLC values
    /// ([`StatHeikinAshi`](crate::stat::heikin_ashi::StatHeikinAshi)).
    pub fn geom_heikin_ashi(self) -> Self {
        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
            .stat(crate::stat::heikin_ashi::StatHeikinAshi)
    }

    /// Renko chart: map `y` to the price (rows in time order); a brick of
    /// `box_size` per full move, reversals after two boxes. The x axis
    /// counts bricks.
    pub fn geom_renko(self, box_size: f64) -> Self {
        self.add_geom(crate::geom::renko::GeomRenko::renko(box_size))
            .xlab("Brick")
    }

    /// Point-and-figure chart: map `y` to the price (rows in time order);
    /// X columns rise, O columns fall, a column reverses after `reversal`
    /// boxes of `box_size`. The x axis counts columns.
    pub fn geom_point_figure(self, box_size: f64, reversal: usize) -> Self {
        self.add_geom(crate::geom::renko::GeomRenko::point_figure(
            box_size, reversal,
        ))
        .xlab("Column")
    }

    /// Event flags: map `x` and `label` (usually as a layer with its own
    /// `layer_data`); flags stand on the x axis, or on a series with
    /// [`GeomFlags::on_series`](crate::geom::flags::GeomFlags::on_series).
    /// Flags at the same x stack.
    pub fn geom_flags(self) -> Self {
        self.add_geom(crate::geom::flags::GeomFlags::default())
    }

    pub fn geom_flags_with(self, geom: crate::geom::flags::GeomFlags) -> Self {
        self.add_geom_with(geom)
    }

    /// Flow map (feature `sf`): map `x`/`y` (origin lon/lat), `xend`/`yend`
    /// (destination) and `weight`; curved bands with arrowheads, projected
    /// with the geom's projection (match your `geom_sf` layers), e.g.
    /// `geom_flow(GeomFlow::default().project(SfProjection::Mercator))`.
    #[cfg(feature = "sf")]
    pub fn geom_flow(self, geom: crate::geom::flow::GeomFlow) -> Self {
        self.add_geom(geom)
    }

    /// Candlestick chart: map `x` and `open`/`high`/`low`/`close`
    /// (`Aes::new().x("date").open("o").high("h").low("l").close("c")`).
    pub fn geom_candlestick(self) -> Self {
        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
    }

    pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
        self.add_geom_with(geom)
    }

    /// OHLC bar chart (high–low bar with open/close ticks); same aesthetics as
    /// [`geom_candlestick`](Self::geom_candlestick).
    pub fn geom_ohlc(self) -> Self {
        self.add_geom(crate::geom::candlestick::GeomOhlc::default())
    }

    pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
        self.add_geom_with(geom)
    }

    /// Calendar heatmap (GitHub/ECharts style): the plot's `x` (a date —
    /// `DateTime`, epoch seconds or `"YYYY-MM-DD"`) is laid out as week
    /// columns × weekday rows (Sunday on top) via [`StatCalendar`], coloured
    /// by `fill`, with month labels along x, Mon/Wed/Fri along y, month
    /// boundary outlines and square cells. Spans over
    /// [`MAX_CALENDAR_YEARS`] are clipped to the most recent years (with a
    /// build warning). Uses the plot-level data and `x` mapping.
    ///
    /// [`StatCalendar`]: crate::stat::calendar::StatCalendar
    /// [`MAX_CALENDAR_YEARS`]: crate::stat::calendar::MAX_CALENDAR_YEARS
    pub fn geom_calendar(self) -> Self {
        self.geom_calendar_with(
            GeomTile {
                color: (255, 255, 255),
                line_width: 1.5,
                ..Default::default()
            },
            false,
        )
    }

    /// [`geom_calendar`](Self::geom_calendar) with a custom cell style and
    /// optionally Monday-first weeks.
    pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
        use crate::stat::calendar::{
            day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
            CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
        };
        let grid = self
            .mapping
            .get_mapping(&crate::aes::Aesthetic::X)
            .and_then(|c| self.data.column(c))
            .and_then(|col| {
                CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
            });
        let Some((grid, clipped)) = grid else {
            // No dates: an empty calendar layer (renders an empty panel).
            return self.add_geom_with(tile).stat(StatCalendar {
                grid: None,
                monday_first,
            });
        };
        if clipped {
            self.warnings.push(format!(
                "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
            ));
        }
        let (xb, _) = month_breaks(&grid);
        // Rows: y = 6 - weekday; label Mon/Wed/Fri.
        let yb = if monday_first {
            vec![6.0, 4.0, 2.0]
        } else {
            vec![5.0, 3.0, 1.0]
        };
        let segs = month_boundaries(&grid);
        let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
            segs.iter().map(|s| Value::Float(f(s))).collect()
        };
        let boundaries = vec![
            ("x".to_string(), col(|s| s.0)),
            ("y".to_string(), col(|s| s.1)),
            ("xend".to_string(), col(|s| s.2)),
            ("yend".to_string(), col(|s| s.3)),
        ];
        self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
        let plot = self
            .add_geom_with(tile)
            .stat(StatCalendar {
                grid: Some(grid),
                monday_first,
            })
            .scale_x_continuous(
                ScaleContinuous::new()
                    .with_breaks(xb)
                    // Month / weekday names follow the plot locale.
                    .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
                    .with_expand(0.0, 0.0),
            )
            .scale_y_continuous(
                ScaleContinuous::new()
                    .with_breaks(yb)
                    .with_localized_labels(weekday_labels)
                    .with_expand(0.0, 0.0),
            );
        if segs.is_empty() {
            return plot;
        }
        // Styled by the theme's `calendar_month_border` at draw time.
        plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
            .layer_data(boundaries)
            .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
            .show_legend(false)
    }

    pub fn geom_blank(self) -> Self {
        self.add_geom(GeomBlank)
    }

    /// Add a geom configured explicitly by the caller: its colours win over
    /// the theme's `primary_color`.
    /// Run a `geom_*_with` builder for a shortcut's *default* geom, then
    /// clear the `explicit_style` mark it put on the layer, so the defaults
    /// still take theme ink/paper and `primary_color` like `geom_line()`
    /// does (#362).
    fn default_styled(self, build: impl FnOnce(Self) -> Self) -> Self {
        let i = self.layers.len();
        let mut plot = build(self);
        if let Some(layer) = plot.layers.get_mut(i) {
            layer.explicit_style = false;
        }
        plot
    }

    fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
        let mut plot = self.add_geom(geom);
        if let Some(layer) = plot.layers.last_mut() {
            layer.explicit_style = true;
        }
        plot
    }

    fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
        let stat = geom.default_stat();
        let position = geom.default_position();
        let params = geom.default_params();
        self.layers.push(Layer {
            data: None,
            mapping: Aes::default(),
            geom: Box::new(geom),
            stat,
            position,
            params,
            show_legend: None,
            explicit_style: false,
            tooltip_template: None,
            key_glyph: None,
            show_legend_aes: Vec::new(),
        });
        self
    }

    // ─── Layer-level overrides ──────────────────────────────────

    /// Override the stat for the most recently added layer.
    pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.stat = Box::new(stat);
        }
        self
    }

    /// Override the position for the most recently added layer.
    pub fn position(mut self, pos: impl Position + 'static) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.position = Box::new(pos);
        }
        self
    }

    /// Override the data for the most recently added layer.
    pub fn layer_data(mut self, data: impl GGData) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.data = Some(data.into_dataframe());
        }
        self
    }

    /// Override the aesthetic mapping for the most recently added layer.
    pub fn layer_aes(mut self, mapping: Aes) -> Self {
        self.warnings.extend(mapping.warnings.iter().cloned());
        if let Some(layer) = self.layers.last_mut() {
            layer.mapping = mapping;
        }
        self
    }

    /// A `{column}` tooltip template for the most recently added layer
    /// (B2-5), replacing its default `<title>`. Each placeholder is filled
    /// from the *built* layer data (so it can reference a stat-computed
    /// column, e.g. a hex's `count`) at that row, formatted through the
    /// column's scale when it has one
    /// ([`Scale::format_value`](crate::scale::Scale::format_value)) — the same
    /// `data-fvalue` logic, but written into the tooltip text. A column
    /// that doesn't exist on this layer renders as empty, not literally
    /// `{column}`. `{{`/`}}` are literal braces. The result is escaped the
    /// same way any other tooltip is — this is plain text, not markup.
    pub fn tooltip(mut self, template: &str) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.tooltip_template = Some(template.to_string());
        }
        self
    }

    /// Control whether the most recently added layer contributes to the legend.
    /// `true` = always show, `false` = always hide, default (None) = auto.
    pub fn show_legend(mut self, show: bool) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.show_legend = Some(show);
        }
        self
    }

    /// Drop one aesthetic's legend (ggplot2's `guides(fill = "none")`, #409).
    pub fn guide_none(mut self, aes: crate::aes::Aesthetic) -> Self {
        if !self.guide_legend.hidden.contains(&aes) {
            self.guide_legend.hidden.push(aes);
        }
        self
    }

    /// Title one aesthetic's legend (`guides(colour = guide_legend(title =
    /// "…"))` / `labs(colour = "…")`, #409).
    pub fn guide_title(mut self, aes: crate::aes::Aesthetic, title: &str) -> Self {
        self.guide_legend.titles.retain(|(a, _)| *a != aes);
        self.guide_legend.titles.push((aes, title.to_string()));
        self
    }

    /// Options for a continuous colour / fill legend (ggplot2's
    /// `guides(fill = guide_colourbar(barwidth =, nbin =, display =, frame
    /// =, ticks =))`, or `guide_coloursteps()` with [`GuideColourbar::steps`];
    /// #409).
    ///
    /// [`GuideColourbar::steps`]: crate::guide::config::GuideColourbar::steps
    pub fn guide_colourbar(
        mut self,
        aes: crate::aes::Aesthetic,
        bar: crate::guide::config::GuideColourbar,
    ) -> Self {
        self.guide_legend.colourbars.retain(|(a, _)| *a != aes);
        self.guide_legend.colourbars.push((aes, bar));
        self
    }

    /// Options for a binned scale's legend (ggplot2's `guides(size =
    /// guide_bins(show.limits =, axis =))`, #409 / #408). `guide_bins()` is
    /// already the default guide of the `scale_*_binned()` scales; this
    /// sets its options.
    pub fn guide_bins(
        mut self,
        aes: crate::aes::Aesthetic,
        bins: crate::guide::config::GuideBins,
    ) -> Self {
        self.guide_legend.plain_keys.retain(|a| *a != aes);
        self.guide_legend.bins.retain(|(a, _)| *a != aes);
        self.guide_legend.bins.push((aes, bins));
        self
    }

    /// Draw one aesthetic's legend at its own side (ggplot2 3.5's
    /// `guides(colour = guide_legend(position = "bottom"))`, #409); the
    /// others stay at the theme's `legend_position`.
    pub fn guide_position(
        mut self,
        aes: crate::aes::Aesthetic,
        position: crate::theme::LegendPosition,
    ) -> Self {
        self.guide_legend.positions.retain(|(a, _)| *a != aes);
        self.guide_legend.positions.push((aes, position));
        self
    }

    /// Add a legend entry drawn by your own code — ggplot2's
    /// `guide_custom()` (#409): see [`GuideCustom`](crate::guide::config::GuideCustom).
    pub fn guide_custom(mut self, guide: crate::guide::config::GuideCustom) -> Self {
        self.guide_legend.custom.push(guide);
        self
    }

    /// Draw a binned scale's legend as plain keys, one labelled `lo–hi`
    /// per bin (`guides(size = "legend")`), instead of `guide_bins()`.
    pub fn guide_legend_keys(mut self, aes: crate::aes::Aesthetic) -> Self {
        self.guide_legend.bins.retain(|(a, _)| *a != aes);
        if !self.guide_legend.plain_keys.contains(&aes) {
            self.guide_legend.plain_keys.push(aes);
        }
        self
    }

    /// ggplot2's `guide_coloursteps()` for `aes`: the colourbar drawn as one
    /// solid block per interval between breaks, evenly sized (#409).
    pub fn guide_coloursteps(self, aes: crate::aes::Aesthetic) -> Self {
        self.guide_colourbar(aes, crate::guide::config::GuideColourbar::steps())
    }

    /// Reverse one aesthetic's legend keys (`guides(colour =
    /// guide_legend(reverse = TRUE))`, #409).
    pub fn guide_reverse(mut self, aes: crate::aes::Aesthetic, reverse: bool) -> Self {
        self.guide_legend.reversed.retain(|a| *a != aes);
        if reverse {
            self.guide_legend.reversed.push(aes);
        }
        self
    }

    /// Draw one legend's keys with fixed values (ggplot2's `guides(colour =
    /// guide_legend(override.aes = list(size = 4, alpha = 1)))`, #409).
    pub fn guide_override(
        mut self,
        aes: crate::aes::Aesthetic,
        keys: crate::guide::config::KeyOverride,
    ) -> Self {
        self.guide_legend.overrides.retain(|(a, _)| *a != aes);
        self.guide_legend.overrides.push((aes, keys));
        self
    }

    /// ggplot2's `guides(x = guide_axis_logticks())` (#409): log10 minor
    /// ticks on that axis (long at decades, mid at 5s, short otherwise).
    /// Call after `scale_x_log10()` / `scale_y_log10()`.
    pub fn guide_axis_logticks(mut self, aes: crate::aes::Aesthetic) -> Self {
        for s in self.scales.iter_mut().filter(|s| s.aesthetic() == aes) {
            s.set_log_ticks(true);
        }
        self
    }

    /// Show or hide the most recent layer in one aesthetic's legend only
    /// (ggplot2's `show.legend = c(colour = TRUE, fill = FALSE)`; #410).
    pub fn show_legend_for(mut self, aes: crate::aes::Aesthetic, show: bool) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.show_legend_aes.retain(|(a, _)| *a != aes);
            layer.show_legend_aes.push((aes, show));
        }
        self
    }

    /// Draw the most recent layer's legend keys as `glyph` (ggplot2's
    /// `key_glyph =`, e.g. `KeyGlyph::Timeseries` for a line; #410).
    pub fn key_glyph(mut self, glyph: crate::guide::key::KeyGlyph) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            layer.key_glyph = Some(glyph);
        }
        self
    }

    /// Mark the most recently added layer as purely decorative (#161): its
    /// drawn marks keep their own visual style but carry **no** per-mark
    /// metadata — no `<title>`, no `data-x`/`data-series`/`data-value`/
    /// `data-fvalue`, and no [`data_attr`](crate::aes::Aes::data_attr)
    /// attributes — so an SVG consumer that treats "has a non-empty
    /// `<title>`" as "is a selectable data point" doesn't pick it up. Meant
    /// for a layer that annotates another layer's mark rather than drawing
    /// data in its own right (e.g. a boxplot's own mean dot, drawn by a
    /// separate `geom_point` layer purely to mark the spot the box's own
    /// tooltip already names). Each mark also carries
    /// `data-part="decorative"` and `aria-hidden="true"` (`data-geom`
    /// still names the real geom), so a consumer can select decorative
    /// marks positively rather than only infer them from what they lack.
    /// Their class is `gg-mark gg-decorative`, not the geom's own
    /// (`gg-point`, `gg-line`, …).
    ///
    /// A `.tooltip(...)` template on a decorative layer has no visible
    /// effect — the geom's marks carry no tooltip regardless — and warns,
    /// like the existing has-no-effect warning for a geom that doesn't
    /// read tooltips at all.
    ///
    /// A decorative layer also defaults to hidden in the legend (it's
    /// annotating, not its own series), unless
    /// [`show_legend`](Self::show_legend)`(true)` is called — before or
    /// after `decorative()` — to opt back in; an explicit
    /// `show_legend(false)` is left untouched either way.
    pub fn decorative(mut self) -> Self {
        if let Some(layer) = self.layers.last_mut() {
            let geom = std::mem::replace(&mut layer.geom, Box::new(GeomBlank));
            layer.geom = Box::new(crate::geom::decorative::Decorative(geom));
            if layer.show_legend.is_none() {
                layer.show_legend = Some(false);
            }
        }
        self
    }

    /// Add one SVG attribute to **every mark** of the most recently added
    /// layer (#221) — e.g. to make a label layer drawn over node boxes inert,
    /// so hover/click and screen readers pass through to the box below:
    ///
    /// ```
    /// # use ggplot_rs::{aes::Aes, data::Value, GGPlot};
    /// # let data = vec![("x".to_string(), vec![Value::Float(1.0)]),
    /// #   ("y".to_string(), vec![Value::Float(1.0)]),
    /// #   ("l".to_string(), vec![Value::Str("a".into())])];
    /// let svg = GGPlot::new(data)
    ///     .aes(Aes::new().x("x").y("y").label("l"))
    ///     .geom_text()
    ///     .layer_svg_attr("aria-hidden", "true")
    ///     .layer_svg_attr("pointer-events", "none")
    ///     .layer_svg_attr("class", "node-label")
    ///     .render_svg_native_with_size(200, 200)
    ///     .unwrap();
    /// assert!(svg.contains(r#"aria-hidden="true" pointer-events="none""#));
    /// ```
    ///
    /// The allow-list is deliberately small: `class` (space-separated
    /// tokens, each `[A-Za-z][A-Za-z0-9_-]*`, appended to the mark's own
    /// `gg-mark gg-<kind>` class; invalid tokens are dropped), `aria-hidden`
    /// (`"true"`/`"false"`), `pointer-events` (an SVG keyword such as
    /// `"none"`), and `data-*` (`Aes::data_attr`'s name rules; a row's own
    /// `data_attr` of the same name wins). Anything else — in particular
    /// `style` and `on*` handlers, so a strict CSP without `unsafe-inline`
    /// still holds — is ignored with a build warning, as is a bad value or a
    /// call before any layer. A later call with the same name replaces the
    /// earlier value. Values are escaped on output. For a per-row class use
    /// [`Aes::class`](crate::aes::Aes::class); to wrap several layers' marks
    /// per key in one `<g>`, [`Aes::group_wrap`](crate::aes::Aes::group_wrap).
    /// SVG backend only.
    pub fn layer_svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        let (name, value) = (name.into(), value.into());
        let Some(idx) = self.layers.len().checked_sub(1) else {
            self.warnings.push(format!(
                "layer_svg_attr(\"{name}\") called before any layer was added — ignored"
            ));
            return self;
        };
        if let Some((n, v)) =
            crate::render::svg_backend::validate_layer_svg_attr(&name, &value, &mut self.warnings)
        {
            self.layer_svg_attrs
                .retain(|(i, k, _)| !(*i == idx && *k == n));
            self.layer_svg_attrs.push((idx, n, v));
        }
        self
    }

    /// [`layer_svg_attr`](Self::layer_svg_attr) for several attributes at once.
    pub fn layer_svg_attrs<N: Into<String>, V: Into<String>>(
        self,
        attrs: impl IntoIterator<Item = (N, V)>,
    ) -> Self {
        attrs
            .into_iter()
            .fold(self, |p, (n, v)| p.layer_svg_attr(n, v))
    }

    // ─── Scales ──────────────────────────────────────────────────

    pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
        self.scale_color(s)
    }

    pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
        self.scale_fill(s)
    }

    /// The `colour`/`color` column already holds `#RRGGBB`/`#RGB` hex
    /// strings, used as-is — no legend (R's `scale_colour_identity`).
    pub fn scale_colour_identity(self) -> Self {
        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Color);
        self.scale_color(s)
    }

    /// American-spelling alias for [`scale_colour_identity`](Self::scale_colour_identity).
    pub fn scale_color_identity(self) -> Self {
        self.scale_colour_identity()
    }

    /// The `fill` column already holds `#RRGGBB`/`#RGB` hex strings, used
    /// as-is — no legend (R's `scale_fill_identity`).
    pub fn scale_fill_identity(self) -> Self {
        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Fill);
        self.scale_fill(s)
    }

    pub fn scale_color_viridis(self) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        use crate::scale::palettes::PaletteName;
        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
            .with_named_palette(&PaletteName::Viridis);
        self.scale_color(s)
    }

    pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
        self.scale_color(s)
    }

    pub fn scale_color_gradient(
        self,
        low: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
    ) -> Self {
        use crate::scale::color::ScaleColorContinuous;
        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
        self.scale_color(s)
    }

    pub fn scale_fill_gradient(
        self,
        low: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
    ) -> Self {
        use crate::scale::color::ScaleColorContinuous;
        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
        self.scale_fill(s)
    }

    pub fn scale_color_gradient2(
        self,
        low: crate::scale::color::RGBAColor,
        mid: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
    ) -> Self {
        use crate::scale::gradient::ScaleColorGradient2;
        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
        self.scale_color(s)
    }

    pub fn scale_fill_gradient2(
        self,
        low: crate::scale::color::RGBAColor,
        mid: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
    ) -> Self {
        use crate::scale::gradient::ScaleColorGradient2;
        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
        self.scale_fill(s)
    }

    pub fn scale_fill_viridis(self) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        use crate::scale::palettes::PaletteName;
        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
            .with_named_palette(&PaletteName::Viridis);
        self.scale_fill(s)
    }

    /// Continuous viridis color scale (for numeric data).
    pub fn scale_color_viridis_c(self) -> Self {
        use crate::scale::gradient_n::ScaleColorGradientN;
        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
        self.scale_color(s)
    }

    /// Continuous viridis fill scale (for numeric data).
    pub fn scale_fill_viridis_c(self) -> Self {
        use crate::scale::gradient_n::ScaleColorGradientN;
        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
        self.scale_fill(s)
    }

    /// N-stop continuous color gradient.
    pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
        use crate::scale::gradient_n::ScaleColorGradientN;
        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
        self.scale_color(s)
    }

    /// N-stop continuous fill gradient.
    pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
        use crate::scale::gradient_n::ScaleColorGradientN;
        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
        self.scale_fill(s)
    }

    /// Binned (stepped) two-colour continuous colour scale — buckets the mapped
    /// variable into `n_bins` bins, each a discrete colour, with a stepped legend.
    pub fn scale_color_steps(
        self,
        low: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
        n_bins: usize,
    ) -> Self {
        let s = crate::scale::steps::ScaleColorSteps::two(
            crate::aes::Aesthetic::Color,
            (low.r, low.g, low.b),
            (high.r, high.g, high.b),
            n_bins,
        );
        self.scale_color(s)
    }

    /// Binned N-stop continuous colour scale.
    pub fn scale_color_stepsn(
        self,
        stops: Vec<crate::scale::color::RGBAColor>,
        n_bins: usize,
    ) -> Self {
        let s = crate::scale::steps::ScaleColorSteps::new(
            crate::aes::Aesthetic::Color,
            stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
            n_bins,
        );
        self.scale_color(s)
    }

    /// Binned ColorBrewer colour scale (R's `scale_color_fermenter`).
    pub fn scale_color_fermenter(
        self,
        name: crate::scale::palettes::PaletteName,
        n_bins: usize,
    ) -> Self {
        let stops = crate::scale::palettes::palette(&name)
            .iter()
            .map(|c| (c.r, c.g, c.b))
            .collect();
        let s =
            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
        self.scale_color(s)
    }

    /// Binned (stepped) two-colour continuous fill scale.
    /// `scale_colour_steps2(low, mid, high, midpoint)`: diverging binned
    /// colour scale (#408).
    pub fn scale_color_steps2(
        self,
        low: crate::scale::color::RGBAColor,
        mid: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
        midpoint: f64,
        n_bins: usize,
    ) -> Self {
        self.scale_color(crate::scale::steps::ScaleColorSteps::diverging(
            crate::aes::Aesthetic::Color,
            (low.r, low.g, low.b),
            (mid.r, mid.g, mid.b),
            (high.r, high.g, high.b),
            midpoint,
            n_bins,
        ))
    }

    /// `scale_fill_steps2(low, mid, high, midpoint)` — see
    /// [`scale_color_steps2`](Self::scale_color_steps2).
    pub fn scale_fill_steps2(
        self,
        low: crate::scale::color::RGBAColor,
        mid: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
        midpoint: f64,
        n_bins: usize,
    ) -> Self {
        self.scale_fill(crate::scale::steps::ScaleColorSteps::diverging(
            crate::aes::Aesthetic::Fill,
            (low.r, low.g, low.b),
            (mid.r, mid.g, mid.b),
            (high.r, high.g, high.b),
            midpoint,
            n_bins,
        ))
    }

    /// `scale_colour_viridis_b(option)`: binned viridis, `option` 'A'–'H'
    /// (#408).
    pub fn scale_color_viridis_b(self, option: char, n_bins: usize) -> Self {
        self.scale_color(crate::scale::steps::ScaleColorSteps::viridis(
            crate::aes::Aesthetic::Color,
            option,
            n_bins,
        ))
    }

    /// `scale_fill_viridis_b(option)` — see
    /// [`scale_color_viridis_b`](Self::scale_color_viridis_b).
    pub fn scale_fill_viridis_b(self, option: char, n_bins: usize) -> Self {
        self.scale_fill(crate::scale::steps::ScaleColorSteps::viridis(
            crate::aes::Aesthetic::Fill,
            option,
            n_bins,
        ))
    }

    pub fn scale_fill_steps(
        self,
        low: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
        n_bins: usize,
    ) -> Self {
        let s = crate::scale::steps::ScaleColorSteps::two(
            crate::aes::Aesthetic::Fill,
            (low.r, low.g, low.b),
            (high.r, high.g, high.b),
            n_bins,
        );
        self.scale_fill(s)
    }

    /// Binned fill scale with *explicit* class breaks (`n + 1` increasing
    /// edges, `n` colours interpolated `low`→`high`) — R's
    /// `scale_fill_steps(breaks = ...)`, backing a `::CLASSES` choropleth
    /// (sipemu/ggplot-rs#180). The legend shows each class's trained count
    /// (`"10–50 (12)"`) and, when any value is `Value::Na`, a "no data" key
    /// in `na_color` (default grey50) — see
    /// [`ScaleFillBinned`](crate::scale::binned::ScaleFillBinned) for the
    /// `.na_color(..)`/`.na_label(..)` builders. The break maths itself
    /// (quantile/Jenks/equal-width/custom edges) is the caller's job; this
    /// only bins against the edges it's given.
    pub fn scale_fill_binned(
        self,
        breaks: Vec<f64>,
        low: crate::scale::color::RGBAColor,
        high: crate::scale::color::RGBAColor,
    ) -> Self {
        let s = crate::scale::binned::ScaleFillBinned::two(
            crate::aes::Aesthetic::Fill,
            breaks,
            (low.r, low.g, low.b),
            (high.r, high.g, high.b),
        );
        self.scale_fill(s)
    }

    /// Like [`scale_fill_binned`](Self::scale_fill_binned), with an
    /// explicit colour per bin (`colors.len()` should be
    /// `breaks.len() - 1`) instead of a two-colour interpolation.
    pub fn scale_fill_binned_with(
        self,
        breaks: Vec<f64>,
        colors: Vec<crate::scale::color::RGBAColor>,
    ) -> Self {
        let s = crate::scale::binned::ScaleFillBinned::new(
            crate::aes::Aesthetic::Fill,
            breaks,
            colors.iter().map(|c| (c.r, c.g, c.b)).collect(),
        );
        self.scale_fill(s)
    }

    /// Binned ColorBrewer fill scale.
    pub fn scale_fill_fermenter(
        self,
        name: crate::scale::palettes::PaletteName,
        n_bins: usize,
    ) -> Self {
        let stops = crate::scale::palettes::palette(&name)
            .iter()
            .map(|c| (c.r, c.g, c.b))
            .collect();
        let s =
            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
        self.scale_fill(s)
    }

    /// Default discrete fill palette with levels in sorted order, so a level
    /// keeps its colour across charts regardless of data order. For a custom
    /// palette: `scale_fill(ScaleColorDiscrete::new(Aesthetic::Fill)
    /// .with_palette(p).sorted())`.
    pub fn scale_fill_discrete_sorted(self) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
    }

    /// Default discrete colour palette with levels in sorted order (see
    /// [`scale_fill_discrete_sorted`](Self::scale_fill_discrete_sorted)).
    pub fn scale_color_discrete_sorted(self) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
    }

    /// ggplot2's `scale_colour_hue(h, c, l, h.start, direction)`: hues evenly
    /// spaced for the number of levels — `HuePalette::default()` gives
    /// exactly ggplot2's default colours for any number of groups (#408).
    pub fn scale_color_hue(self, p: crate::scale::color::HuePalette) -> Self {
        self.scale_color(
            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
                .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
        )
    }

    /// `scale_fill_hue(...)` — see [`scale_color_hue`](Self::scale_color_hue).
    pub fn scale_fill_hue(self, p: crate::scale::color::HuePalette) -> Self {
        self.scale_fill(
            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
                .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
        )
    }

    /// `scale_colour_viridis_d(option, begin, end, direction)` for a
    /// categorical mapping: `option` 'A' magma … 'D' viridis … 'H' turbo.
    pub fn scale_color_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
        self.scale_color(
            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
                .with_generated(crate::scale::color::GeneratedPalette::Viridis {
                    option,
                    begin,
                    end,
                    direction,
                }),
        )
    }

    /// `scale_fill_viridis_d(...)` — see [`scale_color_viridis_d`](Self::scale_color_viridis_d).
    pub fn scale_fill_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
        self.scale_fill(
            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
                .with_generated(crate::scale::color::GeneratedPalette::Viridis {
                    option,
                    begin,
                    end,
                    direction,
                }),
        )
    }

    /// `scale_colour_distiller(palette, direction)`: a Brewer palette
    /// interpolated as a continuous gradient (ggplot2's default `direction
    /// = -1` puts the darkest colour at the low end — pass `-1` for that).
    pub fn scale_color_distiller(
        self,
        palette: crate::scale::palettes::PaletteName,
        direction: i32,
    ) -> Self {
        self.scale_color(distiller(crate::aes::Aesthetic::Color, &palette, direction))
    }

    /// `scale_fill_distiller(...)` — see [`scale_color_distiller`](Self::scale_color_distiller).
    pub fn scale_fill_distiller(
        self,
        palette: crate::scale::palettes::PaletteName,
        direction: i32,
    ) -> Self {
        self.scale_fill(distiller(crate::aes::Aesthetic::Fill, &palette, direction))
    }

    /// Force values into the x / y scales' ranges (ggplot2's
    /// `expand_limits(x = …, y = …)`), e.g. `expand_limits(&[0.0], &[])` to
    /// include 0. Adds an invisible `geom_blank` layer.
    pub fn expand_limits(self, x: &[f64], y: &[f64]) -> Self {
        let n = x.len().max(y.len());
        if n == 0 {
            return self;
        }
        let col =
            |v: &[f64]| -> Vec<Value> { (0..n).map(|i| Value::Float(v[i % v.len()])).collect() };
        let mut data = Vec::new();
        let mut aes = Aes::new();
        if !x.is_empty() {
            data.push(("x".to_string(), col(x)));
            aes = aes.x("x");
        }
        if !y.is_empty() {
            data.push(("y".to_string(), col(y)));
            aes = aes.y("y");
        }
        self.geom_blank().layer_data(data).layer_aes(aes)
    }

    pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
        use crate::scale::color::ScaleColorDiscrete;
        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
        self.scale_fill(s)
    }

    pub fn scale_linetype_manual(
        self,
        values: Vec<(&str, crate::render::backend::Linetype)>,
    ) -> Self {
        let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
        self.scale_color(s)
    }

    pub fn scale_shape_manual(
        self,
        values: Vec<(&str, crate::render::backend::PointShape)>,
    ) -> Self {
        let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
        self.scale_color(s)
    }

    pub fn scale_color_grey(self) -> Self {
        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
        self.scale_color(s)
    }

    pub fn scale_fill_grey(self) -> Self {
        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
        self.scale_fill(s)
    }

    pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
        self.scale_color(s)
    }

    pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
        self.scale_fill(s)
    }

    pub fn scale_x_reverse(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
    }

    pub fn scale_y_reverse(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
    }

    pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
        self.scales.push(Box::new(s));
        self
    }

    pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
        self.scales.push(Box::new(s));
        self
    }

    /// `scale_size_area(max_size)` (ggplot2, B3-6): size scale where
    /// *area*, not radius, is proportional to the value, and 0 maps to 0.
    /// See [`ScaleSizeContinuous::area`](crate::scale::size::ScaleSizeContinuous::area).
    pub fn scale_size_area(mut self, max_size: f64) -> Self {
        self.scales.push(Box::new(
            crate::scale::size::ScaleSizeContinuous::new().area(max_size),
        ));
        self
    }

    /// `scale_radius(range)` (ggplot2): point *radius*, not area,
    /// proportional to the value — ggplot-rs's default size mapping (#408).
    pub fn scale_radius(self, min: f64, max: f64) -> Self {
        self.scale_size(crate::scale::size::ScaleSizeContinuous::new().with_range(min, max))
    }

    /// ggplot2's `scale_size_binned(n.breaks = n)` (#408): sizes by bin.
    pub fn scale_size_binned(self, n: usize) -> Self {
        self.scale_color(crate::scale::values::ScaleValueBinned::new(
            crate::aes::Aesthetic::Size,
            n,
        ))
    }

    /// ggplot2's `scale_alpha_binned()` (#408).
    pub fn scale_alpha_binned(self, n: usize) -> Self {
        self.scale_color(crate::scale::values::ScaleValueBinned::new(
            crate::aes::Aesthetic::Alpha,
            n,
        ))
    }

    /// ggplot2's `scale_linewidth_binned()` (#408).
    pub fn scale_linewidth_binned(self, n: usize) -> Self {
        self.scale_color(crate::scale::values::ScaleValueBinned::new(
            crate::aes::Aesthetic::Linewidth,
            n,
        ))
    }

    /// ggplot2's `scale_shape_binned()` (#408): one shape per bin.
    pub fn scale_shape_binned(self, n: usize) -> Self {
        self.scale_color(crate::scale::values::ScaleValueBinned::new(
            crate::aes::Aesthetic::Shape,
            n,
        ))
    }

    /// ggplot2's `scale_linetype_binned()` (#408): one linetype per bin.
    pub fn scale_linetype_binned(self, n: usize) -> Self {
        self.scale_color(crate::scale::values::ScaleValueBinned::new(
            crate::aes::Aesthetic::Linetype,
            n,
        ))
    }

    /// `scale_size_manual(values)`: named levels → point sizes (#408).
    pub fn scale_size_manual(self, values: Vec<(&str, f64)>) -> Self {
        self.scale_color(crate::scale::values::ScaleValueManual::new(
            crate::aes::Aesthetic::Size,
            values,
        ))
    }

    /// `scale_alpha_manual(values)`: named levels → opacities (#408).
    pub fn scale_alpha_manual(self, values: Vec<(&str, f64)>) -> Self {
        self.scale_color(crate::scale::values::ScaleValueManual::new(
            crate::aes::Aesthetic::Alpha,
            values,
        ))
    }

    /// `scale_linewidth_manual(values)`: named levels → line widths (#408).
    pub fn scale_linewidth_manual(self, values: Vec<(&str, f64)>) -> Self {
        self.scale_color(crate::scale::values::ScaleValueManual::new(
            crate::aes::Aesthetic::Linewidth,
            values,
        ))
    }

    /// `scale_size_identity()`: the column already holds point sizes (#408).
    pub fn scale_size_identity(self) -> Self {
        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
            crate::aes::Aesthetic::Size,
        ))
    }

    /// `scale_alpha_identity()`: the column already holds opacities (#408).
    pub fn scale_alpha_identity(self) -> Self {
        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
            crate::aes::Aesthetic::Alpha,
        ))
    }

    /// `scale_linewidth_identity()`: the column already holds line widths
    /// (#408).
    pub fn scale_linewidth_identity(self) -> Self {
        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
            crate::aes::Aesthetic::Linewidth,
        ))
    }

    /// `scale_shape_identity()`: the column holds ggplot2 `pch` codes or
    /// shape names (`"triangle"`), drawn as the nearest shape (#408).
    pub fn scale_shape_identity(self) -> Self {
        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
            crate::aes::Aesthetic::Shape,
        ))
    }

    pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
        self.scales.push(Box::new(s));
        self
    }

    /// Continuous linewidth scale for the `linewidth` aesthetic (segment,
    /// curve, path, line) — see
    /// [`ScaleLinewidthContinuous`](crate::scale::linewidth::ScaleLinewidthContinuous).
    pub fn scale_linewidth(mut self, s: crate::scale::linewidth::ScaleLinewidthContinuous) -> Self {
        self.scales.push(Box::new(s));
        self
    }

    pub fn xlim(self, min: f64, max: f64) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
    }

    pub fn ylim(self, min: f64, max: f64) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
    }

    pub fn scale_x_log10(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
    }

    pub fn scale_y_log10(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
    }

    pub fn scale_x_sqrt(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
    }

    pub fn scale_y_sqrt(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
    }

    pub fn scale_x_log2(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
    }

    pub fn scale_y_log2(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
    }

    pub fn scale_x_ln(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
    }

    pub fn scale_y_ln(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
    }

    /// Logit-transformed x axis (for proportions in (0, 1)).
    pub fn scale_x_logit(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
    }

    pub fn scale_y_logit(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
    }

    /// Probit-transformed x axis (inverse normal CDF, for proportions in (0, 1)).
    pub fn scale_x_probit(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
    }

    pub fn scale_y_probit(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
    }

    /// Sign-preserving pseudo-log x axis (handles zero and negative values).
    pub fn scale_x_pseudo_log(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
    }

    pub fn scale_y_pseudo_log(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
    }

    /// Reciprocal (1/x) x axis.
    pub fn scale_x_reciprocal(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
    }

    pub fn scale_y_reciprocal(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
    }

    /// Exponential x axis (labels spaced logarithmically).
    pub fn scale_x_exp(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
    }

    pub fn scale_y_exp(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
    }

    /// Box–Cox x axis with the given lambda (x > 0).
    /// ggplot2's `scale_x_time()`: seconds of day on x, `HH:MM:SS` labels at
    /// round time steps (#408).
    pub fn scale_x_time(self) -> Self {
        self.scale_x_continuous(ScaleContinuous::time())
    }

    /// ggplot2's `scale_y_time()` — see [`scale_x_time`](Self::scale_x_time).
    pub fn scale_y_time(self) -> Self {
        self.scale_y_continuous(ScaleContinuous::time())
    }

    /// ggplot2's `scale_x_binned(n.breaks = n)` (#408): x cut into round
    /// bins between about `n` breaks, each value at its bin's midpoint before the stat —
    /// `geom_bar()` then draws a histogram, the axis breaks are the edges.
    pub fn scale_x_binned(self, n: usize) -> Self {
        self.scale_x_continuous(ScaleContinuous::binned(n))
    }

    /// ggplot2's `scale_y_binned()` — see [`scale_x_binned`](Self::scale_x_binned).
    pub fn scale_y_binned(self, n: usize) -> Self {
        self.scale_y_continuous(ScaleContinuous::binned(n))
    }

    pub fn scale_x_boxcox(self, lambda: f64) -> Self {
        self.scale_x_continuous(
            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
        )
    }

    pub fn scale_y_boxcox(self, lambda: f64) -> Self {
        self.scale_y_continuous(
            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
        )
    }

    // ─── Faceting ─────────────────────────────────────────────────

    pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
        self.facet = Facet::Wrap {
            var: var.to_string(),
            ncol,
            scales: FacetScales::Fixed,
            labeller: FacetLabeller::default(),
            levels: None,
            vertical: false,
            as_table: true,
            strip_position: crate::facet::StripPosition::Top,
            space: FacetSpace::Fixed,
        };
        self
    }

    pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
        self.facet = Facet::Wrap {
            var: var.to_string(),
            ncol,
            scales,
            labeller: FacetLabeller::default(),
            levels: None,
            vertical: false,
            as_table: true,
            strip_position: crate::facet::StripPosition::Top,
            space: FacetSpace::Fixed,
        };
        self
    }

    pub fn facet_wrap_labeller(
        mut self,
        var: &str,
        ncol: Option<usize>,
        labeller: FacetLabeller,
    ) -> Self {
        self.facet = Facet::Wrap {
            var: var.to_string(),
            ncol,
            scales: FacetScales::Fixed,
            labeller,
            levels: None,
            vertical: false,
            as_table: true,
            strip_position: crate::facet::StripPosition::Top,
            space: FacetSpace::Fixed,
        };
        self
    }

    /// Fill `facet_wrap` panels column by column (`vertical`, ggplot2's
    /// `dir = "v"`) and / or bottom-up (`as_table = false`, ggplot2's
    /// `as.table = FALSE`). Call after `facet_wrap*` (#412).
    pub fn facet_wrap_dir(mut self, vertical: bool, as_table: bool) -> Self {
        if let Facet::Wrap {
            vertical: v,
            as_table: a,
            ..
        } = &mut self.facet
        {
            *v = vertical;
            *a = as_table;
        }
        self
    }

    /// Draw axes on every facet panel, not just the outer ones (ggplot2's
    /// `facet_*(axes = "all" | "all_x" | "all_y", axis.labels = …)`; #412).
    pub fn facet_axes(mut self, axes: crate::facet::FacetAxes) -> Self {
        self.facet_axes = axes;
        self
    }

    /// Set the strip labeller of the current `facet_wrap` / `facet_grid`
    /// (ggplot2's `labeller =`, #412), e.g. `FacetLabeller::Template("n =
    /// {value}".into())` or `FacetLabeller::per_var(..)`.
    pub fn facet_labeller(mut self, l: FacetLabeller) -> Self {
        match &mut self.facet {
            Facet::Wrap { labeller, .. } | Facet::Grid { labeller, .. } => *labeller = l,
            Facet::None => {}
        }
        self
    }

    /// ggplot2 3.5's `facet_wrap(space = "free_x" | "free_y")` (#412):
    /// panel widths follow their x range in a single-row wrap (heights their
    /// y range in a single column); pair with free scales.
    pub fn facet_wrap_space(mut self, space: FacetSpace) -> Self {
        if let Facet::Wrap { space: s, .. } = &mut self.facet {
            *s = space;
        }
        self
    }

    /// Put each `facet_wrap` panel's strip on another side (ggplot2's
    /// `strip.position = "bottom" | "left" | "right"`). Call after
    /// `facet_wrap*` (#412).
    pub fn facet_strip_position(mut self, position: crate::facet::StripPosition) -> Self {
        if let Facet::Wrap { strip_position, .. } = &mut self.facet {
            *strip_position = position;
        }
        self
    }

    /// Fix a `facet_grid`'s row / column order and keep empty ones
    /// (ggplot2's factor levels with `drop = FALSE`, #412): `None` keeps the
    /// data's own levels for that direction. Call after `facet_grid*`.
    pub fn facet_grid_levels<S: AsRef<str>>(
        mut self,
        rows: Option<&[S]>,
        cols: Option<&[S]>,
    ) -> Self {
        let dedup = |l: &[S]| {
            let mut seen = Vec::<String>::new();
            for s in l {
                if !seen.iter().any(|x| x == s.as_ref()) {
                    seen.push(s.as_ref().to_string());
                }
            }
            seen
        };
        if let Facet::Grid {
            row_levels,
            col_levels,
            ..
        } = &mut self.facet
        {
            *row_levels = rows.map(dedup);
            *col_levels = cols.map(dedup);
        }
        self
    }

    /// Add an "(all)" row and column pooling the others (ggplot2's
    /// `facet_grid(margins = TRUE)`, #412). Stats are computed on the pooled
    /// data. Call after `facet_grid*`.
    pub fn facet_margins(mut self, on: bool) -> Self {
        if let Facet::Grid { margins, .. } = &mut self.facet {
            *margins = on;
        }
        self
    }

    /// Move `facet_grid` strips to the opposite side (ggplot2's `switch =
    /// "x" | "y" | "both"`): column strips below the grid, row strips on its
    /// left. Call after `facet_grid*` (#412).
    pub fn facet_switch(mut self, switch: crate::facet::FacetSwitch) -> Self {
        if let Facet::Grid { switch: s, .. } = &mut self.facet {
            *s = switch;
        }
        self
    }

    /// Fix a [`facet_wrap`](Self::facet_wrap)'s panel order and keep empty
    /// panels (ggplot2's factor levels with `drop = FALSE`, #329): one panel
    /// per entry of `levels`, in that order, whether or not any layer has
    /// rows for it; rows whose facet value isn't listed are dropped. A value
    /// matches a level by its displayed form (`1` for the integer 1). Call
    /// after `facet_wrap*`; no effect on other facets.
    pub fn facet_levels<S: AsRef<str>>(mut self, levels: &[S]) -> Self {
        if let Facet::Wrap { levels: l, .. } = &mut self.facet {
            let mut seen = Vec::<String>::new();
            for s in levels {
                if !seen.iter().any(|x| x == s.as_ref()) {
                    seen.push(s.as_ref().to_string());
                }
            }
            *l = Some(seen);
        }
        self
    }

    pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
        self.facet = Facet::Grid {
            row_var: row.map(String::from),
            col_var: col.map(String::from),
            scales: FacetScales::Fixed,
            labeller: FacetLabeller::default(),
            space: FacetSpace::Fixed,
            switch: crate::facet::FacetSwitch::None,
            row_levels: None,
            col_levels: None,
            margins: false,
        };
        self
    }

    pub fn facet_grid_free(
        mut self,
        row: Option<&str>,
        col: Option<&str>,
        scales: FacetScales,
    ) -> Self {
        self.facet = Facet::Grid {
            row_var: row.map(String::from),
            col_var: col.map(String::from),
            scales,
            labeller: FacetLabeller::default(),
            space: FacetSpace::Fixed,
            switch: crate::facet::FacetSwitch::None,
            row_levels: None,
            col_levels: None,
            margins: false,
        };
        self
    }

    /// `facet_grid` over **multiple** column variables (R's `rows ~ b + c`):
    /// the columns become the combination of the given variables' values.
    /// Also accepts free scales + proportional `space` for full parity.
    pub fn facet_grid_multi(
        mut self,
        row: Option<&str>,
        cols: &[&str],
        scales: FacetScales,
        space: FacetSpace,
    ) -> Self {
        let col_var = if cols.len() > 1 {
            // Build a synthetic column that is the interaction of the col vars.
            let n = self.data.nrows();
            let mut combined = Vec::with_capacity(n);
            for i in 0..n {
                let parts: Vec<String> = cols
                    .iter()
                    .map(|c| {
                        self.data
                            .column(c)
                            .and_then(|col| col.get(i))
                            .map(|v| v.to_group_key())
                            .unwrap_or_default()
                    })
                    .collect();
                combined.push(crate::data::Value::Str(parts.join(" . ")));
            }
            let name = "__facet_cols__".to_string();
            self.data.add_column(name.clone(), combined);
            Some(name)
        } else {
            cols.first().map(|s| s.to_string())
        };
        self.facet = Facet::Grid {
            row_var: row.map(String::from),
            col_var,
            scales,
            labeller: FacetLabeller::default(),
            space,
            switch: crate::facet::FacetSwitch::None,
            row_levels: None,
            col_levels: None,
            margins: false,
        };
        self
    }

    /// `facet_grid` with proportional panel sizing (R's `space =`): panels are
    /// sized to their data range. Typically paired with free scales.
    pub fn facet_grid_space(
        mut self,
        row: Option<&str>,
        col: Option<&str>,
        scales: FacetScales,
        space: FacetSpace,
    ) -> Self {
        self.facet = Facet::Grid {
            row_var: row.map(String::from),
            col_var: col.map(String::from),
            scales,
            labeller: FacetLabeller::default(),
            space,
            switch: crate::facet::FacetSwitch::None,
            row_levels: None,
            col_levels: None,
            margins: false,
        };
        self
    }

    pub fn facet_grid_labeller(
        mut self,
        row: Option<&str>,
        col: Option<&str>,
        labeller: FacetLabeller,
    ) -> Self {
        self.facet = Facet::Grid {
            row_var: row.map(String::from),
            col_var: col.map(String::from),
            scales: FacetScales::Fixed,
            labeller,
            space: FacetSpace::Fixed,
            switch: crate::facet::FacetSwitch::None,
            row_levels: None,
            col_levels: None,
            margins: false,
        };
        self
    }

    // ─── Coordinates ─────────────────────────────────────────────

    pub fn coord_flip(mut self) -> Self {
        self.coord = Box::new(CoordFlip);
        self
    }

    pub fn coord_fixed(mut self, ratio: f64) -> Self {
        self.coord = Box::new(CoordFixed::new(ratio));
        self
    }

    /// Spatial coordinate system (feature `sf`): equal aspect derived from the
    /// data extent, so projected geometry keeps its shape. Pair with a `geom_sf`
    /// projection (e.g. Mercator) for a conformal map.
    #[cfg(feature = "sf")]
    pub fn coord_sf(mut self) -> Self {
        self.coord = Box::new(crate::coord::sf::CoordSf::new());
        self
    }

    /// Spatial coordinate system with explicit settings (`xlim`/`ylim`/
    /// `expand`) — see [`CoordSf`](crate::coord::sf::CoordSf). Used by
    /// consumers overlaying a fragment on their own projected basemap: a
    /// fixed pixel window via `xlim`/`ylim` and `expand(false)`.
    #[cfg(feature = "sf")]
    pub fn coord_sf_with(mut self, coord: crate::coord::sf::CoordSf) -> Self {
        self.coord = Box::new(coord);
        self
    }

    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/
    /// `data-xdomain`/… (see [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
    /// Default `true`. A consumer that overlays a rendered fragment
    /// (`render_svg_native_at`) on its own basemap — which already has its
    /// own root attributes and window — turns this off so the fragment adds
    /// none of its own.
    pub fn svg_root_data(mut self, on: bool) -> Self {
        self.svg_root_data = on;
        self
    }

    /// Add one extra attribute to the root `<svg>` element — a host
    /// identifier, an ARIA label, a CSS hook, and so on. Allowed names:
    /// `data-*`, `aria-*`, `role`, `id`, `class`, `lang`; anything else, or
    /// a name ggplot-rs already writes to the root (`data-plot`,
    /// `data-domain`, …, or `data-warnings` when
    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on), is
    /// ignored with a build warning instead of being silently dropped or
    /// duplicated. Values are escaped on output. PlotGrid has the same API
    /// ([`PlotGrid::svg_attr`](crate::compose::PlotGrid::svg_attr)).
    pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.root_attrs.push((name.into(), value.into()));
        self
    }

    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
        self.root_attrs.extend(attrs);
        self
    }

    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
    /// of the build warnings (rows dropped for non-finite positions, an
    /// `svg_attr` name rejected, …), `[]` when there are none. Default off,
    /// and omitted entirely when off (byte-identical to not calling this).
    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
        self.svg_warnings_attr = on;
        self
    }

    /// Emit `data-fvalue`/`data-fx` on marks: the value aesthetic's raw
    /// data value (y for most geoms, fill for hex/tile) and the x value,
    /// each formatted through its scale (currency/locale numbers, ISO or
    /// locale dates — [`Scale::format_value`](crate::scale::Scale::format_value))
    /// rather than the plain display string `data-value`/`data-x` already
    /// carry. `data-fx` is omitted when it would just duplicate `data-x`.
    /// Default off, and omitted entirely when off (byte-identical to not
    /// calling this).
    /// Tag the SVG's non-data elements with stable semantic CSS classes
    /// (#465), so a page stylesheet can restyle them: `gg-plot-background`,
    /// `gg-panel-background`, `gg-panel-border`, `gg-grid` (+ `gg-grid-major`
    /// / `gg-grid-minor`), `gg-axis` (+ `gg-axis-x` / `gg-axis-y` and
    /// `gg-axis-line` / `gg-axis-tick` / `gg-axis-text`), `gg-axis-title`
    /// (+ `-x` / `-y`), `gg-legend` (+ `gg-legend-title` / `gg-legend-key`
    /// / `gg-legend-text` / `gg-legend-background`), `gg-strip` (+
    /// `gg-strip-background` / `gg-strip-text`), `gg-title`, `gg-subtitle`,
    /// `gg-caption`, `gg-tag`. Data marks always carry `gg-mark gg-<kind>`.
    /// Off by default (output unchanged).
    pub fn svg_semantic_classes(mut self, on: bool) -> Self {
        self.svg_classes = on;
        self
    }

    pub fn svg_formatted_values(mut self, on: bool) -> Self {
        self.svg_formatted_values = on;
        self
    }

    /// Give the rendered root `<svg>` an accessible name: a `<title>`
    /// written (escaped) as its first child, plus `role="img"` and
    /// `aria-labelledby` pointing at that `<title>`'s id — the SVG
    /// accessibility practice of naming an image via `role="img"` +
    /// `aria-labelledby`/`-describedby` rather than a bare `<title>`,
    /// which some screen readers treat as a tooltip instead of a name.
    /// Pairs with [`svg_desc`](Self::svg_desc) for a longer description;
    /// either may be set alone. Default off (`None`), so output stays
    /// byte-identical when this is never called.
    pub fn svg_title(mut self, title: impl Into<String>) -> Self {
        self.svg_title = Some(title.into());
        self
    }

    /// Give the rendered root `<svg>` an accessible description: a
    /// `<desc>` written (escaped) as a first child (after `<title>`, if
    /// [`svg_title`](Self::svg_title) is also set), plus `role="img"` and
    /// `aria-describedby` pointing at that `<desc>`'s id — e.g. a data
    /// summary like "4 regions; highest Bavaria (5.2); 1 without data".
    /// Default off (`None`), so output stays byte-identical when this is
    /// never called.
    pub fn svg_desc(mut self, desc: impl Into<String>) -> Self {
        self.svg_desc = Some(desc.into());
        self
    }

    /// Transform the coordinate space at draw time (R's `coord_trans`) — stats are
    /// computed on raw data but drawn on non-linear axes. Pass a per-axis
    /// [`ScaleTransform`] (e.g. `Some(ScaleTransform::Log10)`), `None` to leave an
    /// axis linear.
    pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
        self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
        self
    }

    /// ggplot2 4.0's name for [`coord_trans`](Self::coord_trans).
    pub fn coord_transform(self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
        self.coord_trans(x, y)
    }

    /// Plain longitude (`x`) / latitude (`y`) data with the aspect ratio of
    /// the middle latitude (ggplot2's `coord_quickmap()`).
    pub fn coord_quickmap(mut self) -> Self {
        self.coord = Box::new(crate::coord::map::CoordMap::new(
            crate::coord::map::MapProjection::Quick,
        ));
        self
    }

    /// Plain longitude / latitude data on a Mercator map (ggplot2's
    /// `coord_map("mercator")`); use `geom_sf` + `coord_sf` for other
    /// projections.
    pub fn coord_map(mut self) -> Self {
        self.coord = Box::new(crate::coord::map::CoordMap::new(
            crate::coord::map::MapProjection::Mercator,
        ));
        self
    }

    /// Use a configured [`CoordCartesian`] (zoom + reverse).
    pub fn coord_cartesian_with(mut self, coord: CoordCartesian) -> Self {
        self.coord = Box::new(coord);
        self
    }

    /// Whether the data layers are clipped to the panel — ggplot2's
    /// `coord_*(clip = "on")` (the default) or `clip = "off"` (`false`),
    /// which lets marks and labels at the edge draw past it (#411).
    pub fn coord_clip(mut self, on: bool) -> Self {
        self.clip = on;
        self
    }

    /// Mirror the panel in x and / or y (`coord_cartesian(reverse = …)`).
    pub fn coord_reverse(mut self, x: bool, y: bool) -> Self {
        self.coord = Box::new(CoordCartesian::new().reverse(x, y));
        self
    }

    /// ggplot2's `coord_radial(start, end, inner.radius)`: a polar coord
    /// whose theta runs from `start` to `end` radians (clockwise from 12
    /// o'clock) with a hole of `inner_radius` (0–1) — partial circles and
    /// donuts.
    pub fn coord_radial(mut self, start: f64, end: f64, inner_radius: f64) -> Self {
        let mut c = CoordPolar::new();
        c.start = start;
        c.span = end - start;
        c.inner_radius = inner_radius.clamp(0.0, 0.99);
        self.coord = Box::new(c);
        self
    }

    /// `coord_trans` on the y-axis only.
    pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
        self.coord_trans(None, Some(y))
    }

    /// `coord_trans` on the x-axis only.
    pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
        self.coord_trans(Some(x), None)
    }

    /// Zoom into a region without filtering data (unlike xlim/ylim which filter).
    pub fn coord_cartesian_zoom(
        mut self,
        xlim: Option<(f64, f64)>,
        ylim: Option<(f64, f64)>,
    ) -> Self {
        let mut c = CoordCartesian::new();
        if let Some((min, max)) = xlim {
            c = c.xlim(min, max);
        }
        if let Some((min, max)) = ylim {
            c = c.ylim(min, max);
        }
        self.coord = Box::new(c);
        self
    }

    pub fn coord_polar(mut self) -> Self {
        self.coord = Box::new(CoordPolar::new());
        self
    }

    /// Radar / spider chart coordinates: discrete `x` → spokes, `y` → distance
    /// from the centre, straight segments, ring/spoke guides. Pair with
    /// `geom_polygon` (closed series) and `geom_point`.
    pub fn coord_radar(mut self) -> Self {
        self.coord = Box::new(crate::coord::radar::CoordRadar::new());
        self
    }

    pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
        self.coord = Box::new(coord);
        self
    }

    pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
        self.coord = Box::new(coord);
        self
    }

    // ─── Theme ───────────────────────────────────────────────────

    /// Replace the theme. A `primary_color` set earlier is kept unless the new
    /// theme sets its own, so preset/`primary_color` call order doesn't matter.
    pub fn theme(mut self, theme: Theme) -> Self {
        self.apply_preset(theme);
        self
    }

    fn apply_preset(&mut self, theme: Theme) {
        let primary = self.theme.primary;
        self.theme = theme;
        if self.theme.primary.is_none() {
            self.theme.primary = primary;
        }
    }

    /// Rotate the x-axis tick labels by `degrees` (R's
    /// `guides(x = guide_axis(angle = ...))` / `axis.text.x = element_text(angle)`).
    /// Useful for long category labels. Call after any `theme_*()` preset.
    pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
        self.theme.axis_text_x.angle = degrees;
        self
    }

    /// Rotate the y-axis tick labels by `degrees`.
    pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
        self.theme.axis_text_y.angle = degrees;
        self
    }

    /// Stagger x-axis tick labels across `n` rows to avoid overlap (R's
    /// `guides(x = guide_axis(n.dodge = n))`). `1` = no dodging.
    pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
        self.theme.axis_text_x_dodge = n.max(1);
        self
    }

    /// Fix the panel's height:width ratio (R's `aspect.ratio`). Call after any
    /// `theme_*()` preset.
    pub fn aspect_ratio(mut self, ratio: f64) -> Self {
        self.theme.aspect_ratio = Some(ratio);
        self
    }

    /// Draw gridlines on top of the data layers (R's `panel.ontop`).
    pub fn panel_ontop(mut self) -> Self {
        self.theme.panel_ontop = true;
        self
    }

    /// Draw minor tick marks between major ticks (R's `axis.minor.ticks`).
    pub fn axis_minor_ticks(mut self) -> Self {
        self.theme.axis_minor_ticks = true;
        self
    }

    /// How an outer x-axis label that would cross the SVG edge is handled
    /// (B3-1, D6): [`AxisLabelFit::Reserve`](crate::theme::AxisLabelFit::Reserve) (default), `Shift`, or `Clip`
    /// (the 0.21 behaviour). Use `Shift` for panels that must stay
    /// pixel-aligned with other elements (e.g. a host's own aligned strip).
    pub fn axis_text_x_fit(mut self, fit: crate::theme::AxisLabelFit) -> Self {
        self.theme.axis_text_x_fit = fit;
        self
    }

    /// Thin crowded x-axis labels in ggplot2's `check.overlap` priority
    /// order (B3-1, D5). Off by default.
    pub fn axis_text_x_check_overlap(mut self, on: bool) -> Self {
        self.theme.axis_text_x_check_overlap = on;
        self
    }

    /// Align title/subtitle/caption to the panel or the whole plot width
    /// (R's `plot.title.position`).
    pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
        self.theme.title_position = pos;
        self
    }

    /// Corner for the `tag()` label (R's `plot.tag.position`).
    pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
        self.theme.tag_position = pos;
        self
    }

    /// Force the legend key layout direction (R's `legend.direction`).
    pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
        self.theme.legend_direction = Some(dir);
        self
    }

    /// Set the brand/primary color used as the default for single-series geoms
    /// that have no color/fill aesthetic mapped. Composes with any theme — one
    /// render process can serve different tenants' brands at render time.
    /// Place the legend inside the panel at panel-relative coordinates
    /// (0..1, 0..1) — `(0,0)` bottom-left, `(1,1)` top-right (R's
    /// `legend.position = c(x, y)`).
    pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
        self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
        self
    }

    /// Set the legend position (R's `legend.position`, e.g. `Top`/`Bottom`).
    pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
        self.theme.legend_position = pos;
        self
    }

    /// Move a [`Right`](crate::theme::LegendPosition::Right) legend to
    /// `Bottom` (drawn horizontally) when it would take more than `share`
    /// (0..1) of the panel's width — the width the panel has with no legend
    /// at all (#287). The band is roughly fixed in size, so on a narrow
    /// render it can take most of the panel; a render wide enough keeps
    /// `Right`, unchanged. Off by default; no effect on any other position.
    pub fn legend_bottom_when_narrow(mut self, share: f64) -> Self {
        self.legend_bottom_share = Some(share);
        self
    }

    /// Put the legend inside the panel, in an empty corner (#332): after
    /// layout, each corner's real legend box is tested against the drawn
    /// marks (polygons, lines, points, labels, corner furniture such as a
    /// scale bar), and the first corner it overlaps nothing in wins, in the
    /// order bottom-right, bottom-left, top-right, top-left. If every
    /// corner is taken the legend goes outside, `Top` or `Right`, whichever
    /// leaves the data area (e.g. a `coord_sf` map) larger. The choice is
    /// written as the root `data-legend-at` attribute (`inside-top-left`,
    /// `top`, …). Single-panel plots only; a faceted plot keeps its legend
    /// position. See [`legend_inside_auto_with`](Self::legend_inside_auto_with).
    pub fn legend_inside_auto(self) -> Self {
        self.legend_inside_auto_with(&crate::theme::LegendCorner::ALL, None)
    }

    /// [`legend_inside_auto`](Self::legend_inside_auto) with the candidate
    /// `corners` (in preference order) and an outside `fallback`
    /// (`Top`/`Right`/`Bottom`/`Left`; `None` = the larger of `Top` and
    /// `Right`).
    pub fn legend_inside_auto_with(
        mut self,
        corners: &[crate::theme::LegendCorner],
        fallback: Option<crate::theme::LegendPosition>,
    ) -> Self {
        use crate::theme::LegendPosition as P;
        let mut c = [None; 4];
        for (slot, corner) in c.iter_mut().zip(corners) {
            *slot = Some(*corner);
        }
        let fallback = match fallback {
            Some(P::Top) => Some(LegendSide::Top),
            Some(P::Right) => Some(LegendSide::Right),
            Some(P::Bottom) => Some(LegendSide::Bottom),
            Some(P::Left) => Some(LegendSide::Left),
            _ => None,
        };
        self.legend_auto = Some(LegendAuto {
            corners: c,
            fallback,
        });
        self
    }

    pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
        self.theme.primary = Some(color);
        self
    }

    pub fn theme_minimal(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_minimal());
        self
    }

    /// ggplot2's `theme_test()`: `theme_bw` without gridlines (#413).
    pub fn theme_test(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_test());
        self
    }

    pub fn theme_bw(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_bw());
        self
    }

    pub fn theme_gray(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_gray());
        self
    }

    pub fn theme_classic(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_classic());
        self
    }

    /// Apply the publication-ready `theme_pubr()` (ggpubr style).
    pub fn theme_pubr(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_pubr());
        self
    }

    pub fn theme_linedraw(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_linedraw());
        self
    }

    pub fn theme_light(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_light());
        self
    }

    pub fn theme_dark(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_dark());
        self
    }

    pub fn theme_void(mut self) -> Self {
        self.apply_preset(crate::theme::presets::theme_void());
        self
    }

    /// Apply incremental theme modifications on top of the current theme.
    /// Like R's `+ theme(axis.text.x = element_text(...))`.
    pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
        self.theme = self.theme.update(update);
        self
    }

    /// ggplot2's `%+replace%`: the elements `update` sets replace the
    /// current ones whole (#413) — the same as [`theme_update`](Self::theme_update),
    /// named for parity. For ggplot2's merging `+ theme(..)` (only the given
    /// properties change) use [`theme_with`](Self::theme_with).
    pub fn theme_replace(self, update: crate::theme::ThemeUpdate) -> Self {
        self.theme_update(update)
    }

    /// Change single theme properties in place (ggplot2's merging `+ theme(
    /// axis.text.x = element_text(size = 14))`, #413), e.g.
    /// `.theme_with(|t| t.axis_text_x.size = 14.0)`.
    pub fn theme_with(mut self, f: impl FnOnce(&mut Theme)) -> Self {
        f(&mut self.theme);
        self
    }

    // ─── Guides ──────────────────────────────────────────────────

    /// Configure legend guide (title, ncol, reverse).
    pub fn guides(mut self, mut guide: crate::guide::config::GuideLegend) -> Self {
        // Keep per-aesthetic settings made earlier (`guide_none` /
        // `guide_title` / `guide_reverse` / `guide_colourbar`) unless the
        // new guide sets its own.
        if guide.hidden.is_empty() {
            guide.hidden = std::mem::take(&mut self.guide_legend.hidden);
        }
        if guide.titles.is_empty() {
            guide.titles = std::mem::take(&mut self.guide_legend.titles);
        }
        if guide.reversed.is_empty() {
            guide.reversed = std::mem::take(&mut self.guide_legend.reversed);
        }
        if guide.colourbars.is_empty() {
            guide.colourbars = std::mem::take(&mut self.guide_legend.colourbars);
        }
        if guide.overrides.is_empty() {
            guide.overrides = std::mem::take(&mut self.guide_legend.overrides);
        }
        if guide.bins.is_empty() {
            guide.bins = std::mem::take(&mut self.guide_legend.bins);
        }
        if guide.plain_keys.is_empty() {
            guide.plain_keys = std::mem::take(&mut self.guide_legend.plain_keys);
        }
        if guide.custom.is_empty() {
            guide.custom = std::mem::take(&mut self.guide_legend.custom);
        }
        if guide.positions.is_empty() {
            guide.positions = std::mem::take(&mut self.guide_legend.positions);
        }
        self.guide_legend = guide;
        self
    }

    // ─── Labels ──────────────────────────────────────────────────

    pub fn labs(mut self, labels: Labels) -> Self {
        if labels.title.is_some() {
            self.labels.title = labels.title;
        }
        if labels.subtitle.is_some() {
            self.labels.subtitle = labels.subtitle;
        }
        if labels.x.is_some() {
            self.labels.x = labels.x;
        }
        if labels.y.is_some() {
            self.labels.y = labels.y;
        }
        if labels.caption.is_some() {
            self.labels.caption = labels.caption;
        }
        if labels.tag.is_some() {
            self.labels.tag = labels.tag;
        }
        self
    }

    pub fn title(mut self, title: &str) -> Self {
        self.labels.title = Some(title.to_string());
        self
    }

    /// Corner tag label (R's `labs(tag = ...)`), drawn at the top-left — handy
    /// for labelling figure panels ("A", "B", …).
    pub fn tag(mut self, tag: &str) -> Self {
        self.labels.tag = Some(tag.to_string());
        self
    }

    pub fn subtitle(mut self, subtitle: &str) -> Self {
        self.labels.subtitle = Some(subtitle.to_string());
        self
    }

    pub fn xlab(mut self, label: &str) -> Self {
        self.labels.x = Some(label.to_string());
        self
    }

    pub fn ylab(mut self, label: &str) -> Self {
        self.labels.y = Some(label.to_string());
        self
    }

    pub fn caption(mut self, caption: &str) -> Self {
        self.labels.caption = Some(caption.to_string());
        self
    }

    // ─── Annotations ──────────────────────────────────────────────

    /// Add an annotation to the plot.
    pub fn annotate(mut self, annotation: Annotation) -> Self {
        self.annotations.push(annotation);
        self
    }

    /// Add a text annotation at data coordinates.
    pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
        self.annotate(Annotation::text(label, x, y))
    }

    /// Add a rectangle annotation at data coordinates.
    pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
        self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
    }

    /// Add a segment annotation between data coordinates.
    pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
        self.annotate(Annotation::segment(x, y, xend, yend))
    }

    /// Log-10 tick marks on the panel `sides` (`"bl"`, `"trbl"`, …) —
    /// ggplot2's `annotation_logticks()`; pair with `scale_x_log10()` etc.
    pub fn annotation_logticks(self, sides: &str) -> Self {
        self.annotate(Annotation::logticks(sides))
    }

    /// An encoded PNG / JPEG image over a data rectangle (`annotation_raster`);
    /// `f64::INFINITY` / `NEG_INFINITY` bounds mean the panel edges.
    pub fn annotation_raster(
        self,
        image: Vec<u8>,
        xmin: f64,
        xmax: f64,
        ymin: f64,
        ymax: f64,
    ) -> Self {
        self.annotate(Annotation::raster(image, xmin, xmax, ymin, ymax))
    }

    /// An RGBA pixel buffer (`width × height × 4`, row-major) over a data
    /// rectangle (`annotation_raster` with a colour matrix; feature `png`).
    #[cfg(feature = "png")]
    pub fn annotation_raster_rgba(
        self,
        (width, height): (u32, u32),
        rgba: &[u8],
        (xmin, xmax, ymin, ymax): (f64, f64, f64, f64),
    ) -> Self {
        use image::ImageEncoder;
        let mut png = Vec::new();
        let ok = image::codecs::png::PngEncoder::new(&mut png)
            .write_image(rgba, width, height, image::ColorType::Rgba8)
            .is_ok();
        if !ok {
            return self;
        }
        self.annotation_raster(png, xmin, xmax, ymin, ymax)
    }

    /// Draw another plot as an inset into a data rectangle — ggplot2's
    /// `annotation_custom(ggplotGrob(p), xmin, xmax, ymin, ymax)`.
    /// `f64::INFINITY` / `NEG_INFINITY` bounds mean the panel edges.
    pub fn annotation_custom(
        self,
        inset: GGPlot,
        xmin: f64,
        xmax: f64,
        ymin: f64,
        ymax: f64,
    ) -> Self {
        self.annotate(Annotation::inset(inset, xmin, xmax, ymin, ymax))
    }

    /// Default [`Locale`](crate::locale::Locale) for the plot's axis and
    /// legend labels: every continuous position / colour / size / alpha scale
    /// labels its default breaks with the locale's decimal and thousands marks
    /// (`1.000`, `2,5` in de-DE), and date/datetime scales use its month names
    /// and date formats (`Okt. 2026`, `15. Okt. 2026`). A scale's own
    /// `with_locale` and custom `label_*` formatters take precedence.
    /// Without this call labels are unchanged (`.` decimal mark, no grouping,
    /// ISO dates).
    ///
    /// ```
    /// use ggplot_rs::prelude::*;
    /// let svg = GGPlot::new(vec![
    ///         ("x".to_string(), vec![Value::Float(0.0), Value::Float(3000.0)]),
    ///         ("y".to_string(), vec![Value::Float(0.5), Value::Float(2.5)]),
    ///     ])
    ///     .aes(Aes::new().x("x").y("y"))
    ///     .geom_point()
    ///     .locale(Locale::from_tag("de-DE"))
    ///     .render_svg_native()
    ///     .unwrap();
    /// assert!(svg.contains(">1.000<") && svg.contains(">1,5<"));
    /// ```
    pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
        self.locale = Some(locale);
        self
    }

    // ─── Build and Render ────────────────────────────────────────

    /// Build the plot without rendering, returning errors on validation failure.
    pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
        PlotBuilder::build(self)
    }

    /// Build the plot without rendering (analogous to R's ggplot_build()).
    /// Returns the fully computed BuiltPlot with layer data ready for inspection.
    /// Panics on validation errors — use `try_build()` for error handling.
    pub fn build(self) -> crate::build::BuiltPlot {
        self.try_build().expect("plot build failed")
    }

    /// Build and save the plot to a file. Format determined by extension.
    /// (Requires the `plotters` feature, on by default; native only — wasm has
    /// no filesystem/plotters backend.)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn save(self, path: &str) -> Result<(), GGError> {
        self.save_with_size(path, 800, 600)
    }

    /// Build and save with custom dimensions. (Feature `plotters`; native only.)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
        // Determine backend from file extension
        let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
        #[cfg(feature = "pdf")]
        if ext == "pdf" {
            let bytes = self.render_pdf_with_size(w, h)?;
            return std::fs::write(path, bytes).map_err(|e| GGError::Render(e.into()));
        }
        let (built, layout) = self.prepare(w, h)?;

        match ext.as_str() {
            "svg" => {
                let backend = plotters::prelude::SVGBackend::new(path, (w, h));
                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
            }
            "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
                let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
            }
            _ => {
                return Err(GGError::UnsupportedFormat(ext));
            }
        }

        Ok(())
    }

    /// Render the plot to an in-memory SVG document (default 800x600).
    ///
    /// Unlike [`save`](Self::save), this writes nothing to disk — handy for
    /// serving charts from a web/MCP service. Requires the `plotters` feature
    /// (on by default); without it use [`render_svg_native`](Self::render_svg_native).
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn render_svg(self) -> Result<String, GGError> {
        self.render_svg_with_size(800, 600)
    }

    /// Render the plot to an in-memory SVG document with custom dimensions.
    /// (Feature `plotters`; native only — on wasm or without `plotters` use
    /// [`render_svg_native_with_size`](Self::render_svg_native_with_size).)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
        let (built, layout) = self.prepare(w, h)?;
        let mut buf = String::new();
        {
            let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
        }
        Ok(buf)
    }

    /// Render to SVG through the self-contained [`SvgBackend`](crate::render::svg_backend::SvgBackend)
    /// — a plotters-free path that drives the same `PlotRenderer`, proving the
    /// `DrawBackend` abstraction (and needing no glyph rasterization).
    pub fn render_svg_native(self) -> Result<String, GGError> {
        self.render_svg_native_with_size(800, 600)
    }

    /// [`render_svg_native`](Self::render_svg_native) with an explicit size.
    ///
    /// The root `<svg>` carries `data-plot="x y w h"` (the panel rect) and the
    /// trained position domains (`data-domain`, `data-xdomain`, `data-ydomain`,
    /// `data-xlevels`, `data-ylevels` — see
    /// [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
    /// Hoverable marks carry `data-x`, `data-series` and `data-value`.
    pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
        Ok(self.render_native(w, h)?.0.finish())
    }

    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
    /// but also returns the build warnings (rows dropped for non-finite
    /// positions, layers whose stat produced no data, …) — see
    /// [`BuiltPlot::warnings`](crate::build::BuiltPlot::warnings).
    pub fn render_svg_native_with_warnings(
        self,
        w: u32,
        h: u32,
    ) -> Result<(String, Vec<String>), GGError> {
        let (backend, warnings, _) = self.render_native(w, h)?;
        Ok((backend.finish(), warnings))
    }

    /// Render a `w`×`h` chart as a *nested* `<svg x=.. y=.. width=.. height=..
    /// viewBox="0 0 w h">` fragment for composition into a larger SVG (a
    /// dashboard): no `xmlns` (inherited from the parent), positioned at
    /// `(x, y)` in the parent's user space. No string surgery needed:
    ///
    /// ```ignore
    /// let mut page = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="900" height="400">"#);
    /// page += &plot_a.render_svg_native_at(0.0, 0.0, 450, 400)?;
    /// page += &plot_b.render_svg_native_at(450.0, 0.0, 450, 400)?;
    /// page += "</svg>";
    /// ```
    pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
        Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
    }

    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
    /// but also returns the panel rect in pixels `[x, y, w, h]` — enough to
    /// overlay a WebGL/canvas layer that draws marks in data coordinates.
    pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
        let (backend, _, pa) = self.render_native(w, h)?;
        Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
    }

    /// Shared native-SVG pipeline: build, lay out, render into an
    /// [`SvgBackend`](crate::render::svg_backend::SvgBackend) (not yet
    /// finished), returning it with the build warnings and the panel rect.
    fn render_native(
        self,
        w: u32,
        h: u32,
    ) -> Result<
        (
            crate::render::svg_backend::SvgBackend,
            Vec<String>,
            crate::render::Rect,
        ),
        GGError,
    > {
        let svg_root_data = self.svg_root_data;
        let root_attrs = self.root_attrs.clone();
        let svg_warnings_attr = self.svg_warnings_attr;
        let svg_formatted_values = self.svg_formatted_values;
        let svg_title = self.svg_title.clone();
        let svg_desc = self.svg_desc.clone();
        let (built, layout) = self.prepare(w, h)?;
        let pa = layout.plot_area.clone();
        let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
        backend.set_formatted_values(svg_formatted_values);
        backend.set_svg_title(svg_title.clone());
        backend.set_svg_desc(svg_desc.clone());
        let existing_root_attrs = if svg_root_data {
            let attrs = crate::render::svg_backend::root_data_attrs(&built);
            backend.set_root_attrs(attrs.clone());
            // `data-plot` itself is a literal in `root_open`, not part of
            // `root_data_attrs`'s output, but it is written whenever
            // `svg_root_data` is on — reserve it too.
            let mut reserved = attrs;
            // `data-viewport`/`data-panels` likewise come from the backend
            // (a letterboxing coord / fixed-aspect facets).
            for name in ["data-plot", "data-viewport", "data-panels"] {
                reserved.push((name.to_string(), String::new()));
            }
            reserved
        } else {
            backend.without_plot_attr();
            Vec::new()
        };
        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
        let mut warnings = built.warnings;
        warnings.extend(backend.take_warnings());

        let mut reserved = existing_root_attrs;
        if svg_warnings_attr {
            reserved.push(("data-warnings".to_string(), String::new()));
        }
        // #255: `role`/`aria-labelledby`/`aria-describedby` are written
        // directly by `SvgBackend::root_open` when a title/desc was set —
        // reserve them so a colliding `svg_attr` call is dropped with a
        // warning instead of duplicating the attribute.
        if svg_title.is_some() || svg_desc.is_some() {
            reserved.push(("role".to_string(), String::new()));
        }
        if svg_title.is_some() {
            reserved.push(("aria-labelledby".to_string(), String::new()));
        }
        if svg_desc.is_some() {
            reserved.push(("aria-describedby".to_string(), String::new()));
        }
        let extra = crate::render::svg_backend::validate_root_attrs(
            &root_attrs,
            &reserved,
            "plot",
            &mut warnings,
        );
        backend.extend_root_attrs(extra);
        if svg_warnings_attr {
            backend.extend_root_attrs(vec![(
                "data-warnings".to_string(),
                crate::render::svg_backend::warnings_json(&warnings),
            )]);
        }
        Ok((backend, warnings, pa))
    }

    /// Render to a raw RGBA pixel buffer via the self-contained raster
    /// [`PixelBackend`](crate::render::pixel_backend::PixelBackend) (feature
    /// `canvas`) — fast for large-N and wasm-compatible. Returns `(w, h, rgba)`,
    /// ready for a `<canvas>` `putImageData`.
    #[cfg(feature = "canvas")]
    pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
        let (built, layout) = self.prepare(w, h)?;
        let mut backend =
            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
        let (ow, oh) = backend.dimensions();
        Ok((ow, oh, backend.into_rgba()))
    }

    /// Render to a vector PDF (feature `pdf`, #467): one page of `w` × `h`
    /// points (1 px = 1 pt), real selectable text in the bundled DejaVu
    /// fonts (embedded as subsets).
    #[cfg(feature = "pdf")]
    pub fn render_pdf_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
        let (built, layout) = self.prepare(w, h)?;
        let mut backend =
            crate::render::pdf_backend::PdfBackend::new(w, h, layout.plot_area.clone());
        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
        backend.finish().map_err(GGError::Render)
    }

    /// [`render_pdf_with_size`](Self::render_pdf_with_size) at 800 × 600.
    #[cfg(feature = "pdf")]
    pub fn render_pdf(self) -> Result<Vec<u8>, GGError> {
        self.render_pdf_with_size(800, 600)
    }

    /// Like [`render_rgba_with_size`](Self::render_rgba_with_size), but also
    /// returns the panel rect in pixels `[x, y, w, h]` — enough to map a canvas
    /// pixel back to data coordinates for interactive hover.
    #[cfg(feature = "canvas")]
    pub fn render_rgba_area_with_size(
        self,
        w: u32,
        h: u32,
    ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
        let (built, layout) = self.prepare(w, h)?;
        let pa = layout.plot_area.clone();
        let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
        Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
    }

    /// Render to PNG bytes via the raster [`PixelBackend`](crate::render::pixel_backend::PixelBackend)
    /// (feature `canvas`). Unlike [`render_png`](Self::render_png) this needs no
    /// plotters bitmap backend, so it also works on wasm.
    #[cfg(feature = "canvas")]
    pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
        let (built, layout) = self.prepare(w, h)?;
        let mut backend =
            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
        backend.into_png().map_err(GGError::Render)
    }

    /// Render the plot to in-memory PNG bytes (default 800x600).
    ///
    /// Returns a fully-encoded PNG, ready to write to an HTTP response or
    /// embed as a data URI — no temp files involved. Requires the `plotters`
    /// feature (on by default); see also `render_png_raster_with_size`
    /// (feature `canvas`).
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn render_png(self) -> Result<Vec<u8>, GGError> {
        self.render_png_with_size(800, 600)
    }

    /// Render the plot to in-memory PNG bytes with custom dimensions. (Feature
    /// `plotters`; native only — PNG needs the plotters bitmap backend.)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
        let (built, layout) = self.prepare(w, h)?;

        // plotters' BitMapBackend draws into a raw RGB buffer; we then encode
        // that buffer to PNG via the `image` crate.
        let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
        {
            let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
        }

        let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
            GGError::Render(RenderError::BackendError(
                "PNG buffer size mismatch".to_string(),
            ))
        })?;
        let mut out = std::io::Cursor::new(Vec::new());
        img.write_to(&mut out, image::ImageOutputFormat::Png)
            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
        Ok(out.into_inner())
    }

    /// Shared pipeline: build the plot, apply label overrides, compute layout.
    pub(crate) fn prepare(
        self,
        w: u32,
        h: u32,
    ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
        let (mut built, meta) = self.build_for_render()?;
        let layout = Self::layout_built(&mut built, &meta, w, h);
        Ok((built, layout))
    }

    /// The size-independent half of [`prepare`](Self::prepare): build the plot,
    /// resolve theme inheritance and apply axis-label overrides.
    pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
        let plot = self;

        let has_title = plot.labels.title.is_some();
        let has_subtitle = plot.labels.subtitle.is_some();
        let has_caption = plot.labels.caption.is_some();
        let has_legend = plot.has_legend_mapping();
        let legend_bottom_share = plot.legend_bottom_share;
        let legend_auto = plot.legend_auto;
        let x_label = plot.labels.x.clone();
        let y_label = plot.labels.y.clone();
        let guide_titles = plot.guide_legend.titles.clone();

        let mut built = PlotBuilder::build(plot)?;

        // #409: per-aesthetic legend titles name their scales.
        for (aes, title) in &guide_titles {
            if let Some(s) = built.scales.get_mut(aes) {
                s.set_name(title);
            }
        }

        // Resolve R-style theme inheritance (root `text` → child text elements).
        built.theme.resolve_inheritance();

        // #411: a fixed-aspect coord (coord_fixed / coord_sf / coord_map /
        // coord_quickmap) shrinks the single panel to its aspect — the
        // background, grid and axes hug the data, as in ggplot2 — instead
        // of letterboxing the data inside a full-size panel.
        if built.facet.is_none() && built.theme.aspect_ratio.is_none() {
            if let Some(a) = built
                .coord
                .fixed_aspect()
                .filter(|a| a.is_finite() && *a > 0.0)
            {
                built.theme.aspect_ratio = Some(a);
            }
        }

        // Apply user label overrides to scales
        if let Some(ref label) = x_label {
            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
                s.set_name(label);
            }
        }
        if let Some(ref label) = y_label {
            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
                s.set_name(label);
            }
        }

        Ok((
            built,
            RenderMeta {
                has_title,
                has_subtitle,
                has_caption,
                has_legend,
                legend_bottom_share,
                legend_auto,
            },
        ))
    }

    /// The size-dependent half of [`prepare`](Self::prepare): auto-tune axis
    /// labels for `w`×`h` and compute the layout.
    pub(crate) fn layout_built(
        built: &mut crate::build::BuiltPlot,
        meta: &RenderMeta,
        w: u32,
        h: u32,
    ) -> PlotLayout {
        match meta.legend_auto {
            Some(auto) if meta.has_legend && built.panels.is_empty() => {
                Self::layout_legend_auto(built, meta, auto, w, h)
            }
            _ => Self::layout_built_inner(built, meta, w, h),
        }
    }

    /// #332: try each candidate corner for an inside legend against the
    /// marks a dry render draws; fall back outside when none is free.
    fn layout_legend_auto(
        built: &mut crate::build::BuiltPlot,
        meta: &RenderMeta,
        auto: LegendAuto,
        w: u32,
        h: u32,
    ) -> PlotLayout {
        use crate::render::probe::Probe;
        use crate::theme::LegendPosition as P;
        let total = crate::render::Rect {
            x: 0.0,
            y: 0.0,
            width: w as f64,
            height: h as f64,
        };
        // `layout_built_inner` may rotate axis labels and push warnings:
        // every trial starts from the same state.
        let (theme0, n_warnings) = (built.theme.clone(), built.warnings.len());
        let reset = |built: &mut crate::build::BuiltPlot, pos: P| {
            built.theme = theme0.clone();
            built.theme.legend_position = pos;
            built.warnings.truncate(n_warnings);
        };

        reset(built, P::Inside(1.0, 0.0));
        let layout = Self::layout_built_inner(built, meta, w, h);
        let pa = layout.plot_area.clone();
        let mut marks = Probe::new(pa.clone(), total.clone());
        for layer in built.layers.iter().filter(|l| l.data.nrows() > 0) {
            let _ = layer.geom.draw(
                &layer.data,
                built.coord.as_ref(),
                &built.scales,
                &built.theme,
                &mut marks,
            );
        }
        for corner in auto.corners.iter().flatten() {
            built.theme.legend_position = corner.inside();
            let mut legend = Probe::new(pa.clone(), total.clone());
            let drawn = crate::guide::legend::draw_legend_planned(
                &built.scales,
                &built.theme,
                &pa,
                pa.width,
                &mut legend,
                &built.guide_legend,
                &built.suppressed_aes,
                &built.legend_plans,
            );
            let Some((x0, y0, x1, y1)) = legend.extent().filter(|_| drawn.is_ok()) else {
                continue;
            };
            const PAD: f64 = 2.0;
            if !marks.hits((x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD)) {
                built.legend_at = Some(format!("inside-{}", corner.name()));
                return layout;
            }
        }

        // Outside: the given side, else whichever of Top/Right leaves the
        // data area (a fixed-aspect map's letterboxed rect) larger.
        let sides = match auto.fallback {
            Some(side) => vec![side],
            None => vec![LegendSide::Top, LegendSide::Right],
        };
        let data_area = |built: &crate::build::BuiltPlot, layout: &PlotLayout| {
            let r = built
                .coord
                .data_rect(&layout.plot_area)
                .unwrap_or_else(|| layout.plot_area.clone());
            r.width.max(0.0) * r.height.max(0.0)
        };
        let mut best = (sides[0], f64::MIN);
        for &side in &sides {
            reset(built, side.position());
            let trial = Self::layout_built_inner(built, meta, w, h);
            let area = data_area(built, &trial);
            if area > best.1 {
                best = (side, area);
            }
        }
        reset(built, best.0.position());
        let layout = Self::layout_built_inner(built, meta, w, h);
        built.legend_at = Some(
            match built.theme.legend_position {
                P::Top => "top",
                P::Right => "right",
                P::Bottom => "bottom",
                _ => "left",
            }
            .to_string(),
        );
        layout
    }

    fn layout_built_inner(
        built: &mut crate::build::BuiltPlot,
        meta: &RenderMeta,
        w: u32,
        h: u32,
    ) -> PlotLayout {
        let RenderMeta {
            has_title,
            has_subtitle,
            has_caption,
            has_legend,
            legend_bottom_share,
            legend_auto: _,
        } = *meta;
        let x_axis_top = built
            .scales
            .get(&crate::aes::Aesthetic::X)
            .map(|s| s.axis_position_opposite())
            .unwrap_or(false);

        // #287: decided first, so every legend pass below plans for the
        // position actually drawn, on this render's own layout.
        if let Some(share) = legend_bottom_share {
            if has_legend
                && matches!(
                    built.theme.legend_position,
                    crate::theme::LegendPosition::Right
                )
            {
                let panel_width = |pos| {
                    let mut theme = built.theme.clone();
                    theme.legend_position = pos;
                    PlotLayout::compute_with_extras(
                        w as f64,
                        h as f64,
                        &theme,
                        has_title,
                        has_subtitle,
                        has_caption,
                        has_legend,
                        x_axis_top,
                        None,
                        None,
                        crate::render::layout::LayoutExtras::default(),
                    )
                    .plot_area
                    .width
                };
                // Against the panel it would have with no legend at all
                // (the clamped minimum panel width hides the real band).
                let free = panel_width(crate::theme::LegendPosition::None);
                if panel_width(crate::theme::LegendPosition::Right) < (1.0 - share) * free {
                    built.theme.legend_position = crate::theme::LegendPosition::Bottom;
                }
            }
        }

        // Auto-tune categorical axis labels so they stay legible. A flip swaps
        // which trained scale sits on each visual axis: the bottom (x) axis reads
        // the Y scale when flipped, the left (y) axis reads the X scale.
        let flipped = built.coord.is_flipped();
        let h_aes = if flipped {
            crate::aes::Aesthetic::Y
        } else {
            crate::aes::Aesthetic::X
        };
        let v_aes = if flipped {
            crate::aes::Aesthetic::X
        } else {
            crate::aes::Aesthetic::Y
        };

        // The bottom-axis break labels that are actually drawn — a
        // `with_labels` override can blank some entries ("" ) to thin a
        // crowded discrete axis while keeping every position (sipemu/
        // ggplot-rs#162); a blanked entry is never drawn, so it never
        // competes for horizontal room or vertical drop below. Shared by
        // the auto-rotate decision and the rotated-label height reservation
        // just below, so both agree on what's actually on the canvas.
        let drawn_x_labels: Vec<(f64, String)> = built
            .scales
            .get(&h_aes)
            .map(|hs| {
                hs.breaks()
                    .into_iter()
                    .filter(|(_, label)| !label.is_empty())
                    .collect()
            })
            .unwrap_or_default();
        let h_is_discrete = built
            .scales
            .get(&h_aes)
            .map(|hs| hs.is_discrete())
            .unwrap_or(false);

        // Crowded discrete bottom-axis labels overlap when drawn flat. Rotate
        // them — −45° if that de-collides, otherwise vertical (270°) — only
        // when no explicit angle was set (angle.abs() < 1.0 reads as
        // "unset"). Sized from the real, measured widths of the labels that
        // are actually drawn (`render::text::text_width`), both for the
        // label-width estimate and the crowding count `n` — #162's bug was
        // counting every break, blanked or not, which over-triggered the
        // rotation. −45° (not +45°) is ggplot2's own idiom (`angle = 45,
        // hjust = 1`, mirrored to this library's angle sign, sipemu/
        // ggplot-rs#163): it ends each label at its own tick and slants
        // down-left, rather than +45°'s down-right slant, which — anchored
        // the same way — would start under the *previous* category.
        if built.theme.axis_text_x.visible
            && built.theme.axis_text_x.angle.abs() < 1.0
            && h_is_discrete
            && !drawn_x_labels.is_empty()
        {
            let font = built.theme.axis_text_x.size;
            let max_w = drawn_x_labels
                .iter()
                .map(|(_, l)| crate::render::text::text_width(l, font))
                .fold(0.0_f64, f64::max);
            let n = drawn_x_labels.len() as f64;
            let spacing = 0.9 * w as f64 / n; // ~px between adjacent *drawn* labels
            if max_w > spacing {
                // 45° shrinks the horizontal footprint by cos45; if that
                // still doesn't fit, go vertical (270° = reads bottom-to-
                // top, hanging below the axis like the y-axis title).
                let vertical = max_w * std::f64::consts::FRAC_1_SQRT_2 > spacing;
                built.theme.axis_text_x.angle = if vertical { 270.0 } else { -45.0 };
            }
        }

        // Whenever the bottom-axis labels end up rotated — by the
        // auto-rotate decision just above, or by an explicit
        // `axis_text_x_angle` call — reserve the real bottom space their
        // rotated bounding boxes need, so they never overlap the panel
        // (#162 also asked for this: an explicit angle reserved nothing).
        // `rotated_label_rise_fall` is the same helper `draw_x_axis` calls
        // to place its rotation anchor — `rise` must be reserved (as well
        // as placed) or a long enough label's far end swings right back up
        // over the panel regardless of how much height is reserved here;
        // `fall` just needs reserving so the label stays on-canvas. Both
        // here and in `draw_x_axis`, the anchor fraction must come from
        // `rotated_anchor_frac(angle, dir)` (sipemu/ggplot-rs#163) — not a
        // blind `1.0` — or the reservation is sized for the wrong end of
        // the label; `dir` matches `draw_x_axis`'s own tick direction.
        let x_label_height = if built.theme.axis_text_x.visible
            && built.theme.axis_text_x.angle.abs() > 10.0
            && !drawn_x_labels.is_empty()
        {
            let font = built.theme.axis_text_x.size;
            let angle = built.theme.axis_text_x.angle;
            let dir = if x_axis_top { -1.0 } else { 1.0 };
            let (rise, fall) = crate::render::text::rotated_label_rise_fall(
                drawn_x_labels.iter().map(|(_, l)| l.as_str()),
                font,
                angle,
                crate::render::text::rotated_anchor_frac(angle, dir),
            );
            Some(built.theme.legend_spacing / 2.0 + font / 2.0 + rise + fall)
        } else {
            None
        };

        // Reserve the left-axis width from the actual label lengths so long
        // category names (a flipped bar chart's rows) aren't clipped. Never
        // shrinks below the default; grows up to 35% of the width.
        let y_label_width = if built.theme.axis_text_y.visible {
            built.scales.get(&v_aes).map(|vs| {
                crate::guide::axis::y_label_reserve(&built.theme, &vs.breaks()).min(0.35 * w as f64)
            })
        } else {
            None
        };

        // B3-1 (D6): reserve just enough left/right panel margin to keep
        // the outer x-axis labels on-canvas under `AxisLabelFit::Reserve`,
        // for a single (non-faceted) panel on a coord that supports it
        // (not polar/radar/sf, where a label bbox doesn't map to a simple
        // panel margin). A faceted plot skips the layout-level reservation
        // and relies on `draw_x_axis`'s own draw-time shift instead — so
        // does `AxisLabelFit::Shift` (the panel must keep its size) and
        // `Clip` (the 0.21 behaviour, no correction at all). A plot whose
        // outer labels already fit never grows `extras`, so it stays
        // byte-identical.
        // #409: legends moved to another side (`guide_position`) reserve
        // that side's band too.
        let mut extras = crate::render::layout::LayoutExtras {
            extra_legend_sides: crate::guide::legend::extra_legend_sides(
                &built.scales,
                &built.suppressed_aes,
                &built.guide_legend,
                &built.theme.legend_position,
            ),
            ..Default::default()
        };
        // A secondary y axis draws its ticks, labels and title right of the
        // panel: reserve that width so they stay on-canvas (and clear of a
        // right-hand legend).
        if let (Some(vs), Some(sec)) = (
            built.scales.get(&crate::aes::Aesthetic::Y),
            built.scales.sec_axis(&crate::aes::Aesthetic::Y),
        ) {
            let theme = &built.theme;
            let max_ch = match sec.own_ticks(vs) {
                Some(t) => t.iter().map(|(_, l)| l.chars().count()).max(),
                None => vs.breaks().iter().map(|(_, l)| l.chars().count() + 2).max(),
            }
            .unwrap_or(0);
            let text = if theme.axis_text_y.visible {
                (max_ch as f64 * theme.axis_text_y.size * 0.6).max(theme.axis_text_y.size * 3.5)
            } else {
                0.0
            };
            let title = if !sec.name.is_empty() && theme.axis_title_y.visible {
                theme.axis_title_y.size * 1.5
            } else {
                0.0
            };
            extras.right += theme.axis_ticks_length + theme.legend_spacing + text + title;
        }
        // …and a secondary x axis its height above the panel (#409).
        if let Some(sec) = built
            .scales
            .get(&h_aes)
            .filter(|s| !s.axis_position_opposite())
            .and_then(|s| s.sec_axis())
        {
            extras.top += crate::guide::axis::sec_x_axis_height(&built.theme, sec);
        }
        let can_reserve = built.facet.is_none()
            && built.theme.axis_text_x.visible
            && built.theme.axis_text_x_fit == crate::theme::AxisLabelFit::Reserve
            && !built.coord.is_polar()
            && built.coord.supports_axis_reserve();
        if can_reserve {
            if let Some(hs) = built.scales.get(&h_aes) {
                let breaks = hs.breaks();
                if let (Some(first), Some(last)) = (breaks.first(), breaks.last()) {
                    let angle = built.theme.axis_text_x.angle;
                    let anchor = if angle.abs() > 10.0 {
                        let dir = if x_axis_top { -1.0 } else { 1.0 };
                        crate::render::text::rotated_anchor_frac(angle, dir)
                    } else {
                        0.5
                    };
                    let size = built.theme.axis_text_x.size;
                    const EDGE: f64 = 1.0;
                    for _ in 0..2 {
                        let layout = PlotLayout::compute_with_extras(
                            w as f64,
                            h as f64,
                            &built.theme,
                            has_title,
                            has_subtitle,
                            has_caption,
                            has_legend,
                            x_axis_top,
                            y_label_width,
                            x_label_height,
                            extras,
                        );
                        let area = &layout.plot_area;
                        let edge_y = area.y + area.height;
                        let to_point = |pos: f64| if flipped { (0.0, pos) } else { (pos, 0.0) };
                        let px_first = built.coord.transform(to_point(first.0), area).0;
                        let px_last = built.coord.transform(to_point(last.0), area).0;
                        let bbox_first = crate::render::text::label_bbox(
                            &first.1, size, px_first, edge_y, angle, anchor,
                        );
                        let bbox_last = crate::render::text::label_bbox(
                            &last.1, size, px_last, edge_y, angle, anchor,
                        );
                        let deficit_left = (EDGE - bbox_first[0]).max(0.0);
                        let deficit_right = (bbox_last[2] - (w as f64 - EDGE)).max(0.0);
                        if deficit_left <= 0.0 && deficit_right <= 0.0 {
                            break;
                        }
                        // Growing the left margin by `eL` (holding `eR` fixed)
                        // shifts a label at normalized position `p` right by
                        // `eL·(1 − p)`; growing the right margin by `eR`
                        // shifts it left by `eR·p` (the panel maps [0, 1] to
                        // [plot_x + eL, plot_x + width − eR]). Review #158
                        // finding 1: the original code divided by `p_first`
                        // and `1 − p_last` — inverted, which over-reserved
                        // by about `1/p_last` (≈20× at a typical p_last≈0.95).
                        let (p_first, p_last) = (first.0, last.0);
                        if deficit_left > 0.0 && deficit_right > 0.0 {
                            // Both ends overflow: solve the 2×2 system so
                            // each margin accounts for its effect on *both*
                            // labels, rather than correcting them
                            // independently and overshooting.
                            let (a, b, c, d) = (1.0 - p_first, p_first, 1.0 - p_last, p_last);
                            let det = a * d - b * c;
                            if det.abs() > 0.01 {
                                extras.left +=
                                    ((deficit_left * d + deficit_right * b) / det).max(0.0);
                                extras.right +=
                                    ((deficit_right * a + deficit_left * c) / det).max(0.0);
                            } else {
                                // Degenerate (first and last break nearly
                                // coincide in normalized space): fall back
                                // to the independent, clamped formulas.
                                extras.left += deficit_left / (1.0 - p_first).max(0.05);
                                extras.right += deficit_right / p_last.max(0.05);
                            }
                        } else if deficit_left > 0.0 {
                            extras.left += deficit_left / (1.0 - p_first).max(0.05);
                        } else if deficit_right > 0.0 {
                            extras.right += deficit_right / p_last.max(0.05);
                        }
                        // Cap the total reservation so the panel can never
                        // start beyond the canvas or be squeezed past the
                        // same minimum width `compute_with_extras` already
                        // floors it to (review #158's second re-review,
                        // LOW): a single, centred break whose label is
                        // wider than the whole canvas has `p_first ==
                        // p_last == 0.5`, so both `eL` and `eR` grow by
                        // roughly the same (large) deficit independently,
                        // and together they could place `plot_x` past `w`
                        // entirely. Past this cap, Reserve simply stops
                        // growing and `draw_x_axis`'s own draw-time shift
                        // — which always runs for Reserve, the same as for
                        // `Shift` — takes over for whatever's still
                        // outside, exactly as D6 already documents.
                        const MIN_PANEL_WIDTH: f64 = 50.0;
                        let cap = (w as f64 - MIN_PANEL_WIDTH).max(0.0);
                        if extras.left + extras.right > cap {
                            let scale = if extras.left + extras.right > 0.0 {
                                cap / (extras.left + extras.right)
                            } else {
                                0.0
                            };
                            extras.left *= scale;
                            extras.right *= scale;
                        }
                    }
                }
            }
        }

        // B3-2 (D7): a discrete legend's `nrow`/`ncol` grid, or an
        // overflowing horizontal legend's auto-wrap, reserves extra legend
        // rows/width. Several simultaneous discrete guides (e.g. `colour`
        // and `shape` both mapped to discrete variables) each get their
        // own independent plan (sipemu/ggplot-rs#155) — previously this
        // only ran for exactly one discrete guide.
        if has_legend
            && !matches!(
                built.theme.legend_position,
                crate::theme::LegendPosition::None
            )
        {
            let legend_aes =
                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
            // #236: a mapped `size` legend's largest key can need a bigger
            // box than the theme's flat defaults — independent of B3-2's
            // discrete-guide wrap planning below, so computed unconditionally.
            extras.legend_max_key_size = legend_aes
                .iter()
                .filter_map(|aes| {
                    let scale = built.scales.get(aes)?;
                    let breaks = scale.breaks();
                    Some(crate::guide::legend::size_key_diameter(
                        aes,
                        &built.scales,
                        scale,
                        &breaks,
                    ))
                })
                .fold(0.0_f64, f64::max);
            // #545: a continuous, non-colourbar guide (`Size`/
            // `Linewidth`/… sampled breaks) needs the same B3-2 wrap/grid
            // reservation pass a discrete guide gets — only a true
            // colourbar (continuous `Color`/`Fill`) is exempt, since it
            // draws as a fixed-width bar instead of sampled keys.
            // Previously this gate only fired for a discrete guide, so a
            // plot mapping *only* a continuous `Size`/`Linewidth` (no
            // discrete guide alongside it) skipped the whole reservation
            // pass and its legend could run straight off the panel/canvas
            // with no wrap, shrink, or "+N more" to catch it.
            let has_wrap_guide = legend_aes.iter().any(|a| {
                let is_discrete = built
                    .scales
                    .get(a)
                    .map(|s| s.is_discrete())
                    .unwrap_or(false);
                is_discrete || !crate::guide::legend::is_colorbar_aesthetic(a)
            });
            if has_wrap_guide {
                let layout0 = PlotLayout::compute_with_extras(
                    w as f64,
                    h as f64,
                    &built.theme,
                    has_title,
                    has_subtitle,
                    has_caption,
                    has_legend,
                    x_axis_top,
                    y_label_width,
                    x_label_height,
                    extras,
                );
                // `y` is unused here (only `legend_x0`/`is_horizontal` feed
                // the avail-width check below), so #233's `Top` row-count
                // parameter can't matter — `extras.legend_extra_rows` isn't
                // even known yet at this point in the pass. Likewise #225's
                // `Inside` justification only matters when `legend_x0` is
                // actually used for an `Inside` position combined with an
                // explicit `nrow`/`ncol` grid (`Inside` otherwise never
                // reaches this discrete-guide-wrap check), too rare to
                // bother estimating a real size hint for here.
                let (legend_x0, _, mut is_horizontal) = crate::guide::legend::legend_position(
                    &built.theme,
                    &layout0.plot_area,
                    extras.legend_extra_rows,
                    (0.0, 0.0),
                    0.0,
                    &layout0.total,
                );
                if let Some(dir) = built.theme.legend_direction {
                    is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
                }
                let avail_width =
                    (layout0.plot_area.x + layout0.plot_area.width - legend_x0).max(0.0);
                let mut legend_warnings = Vec::new();
                let mut plans = crate::guide::legend::plan_all_legends(
                    &built.scales,
                    &built.guide_legend,
                    &built.theme,
                    &built.suppressed_aes,
                    avail_width,
                    layout0.plot_area.height,
                    is_horizontal,
                    &mut legend_warnings,
                );
                built.warnings.extend(legend_warnings);

                if !plans.is_empty() {
                    // Guides laid out side by side (a horizontal legend
                    // position) share one row band — its height is set
                    // by whichever guide wrapped to the most rows.
                    // Guides stacked vertically each add their own full
                    // height, so their extra rows sum.
                    extras.legend_extra_rows = if is_horizontal {
                        plans
                            .values()
                            .map(|p| p.rows.saturating_sub(1))
                            .max()
                            .unwrap_or(0)
                    } else {
                        plans.values().map(|p| p.rows.saturating_sub(1)).sum()
                    };
                    // Review #158 finding 3: a vertical explicit grid
                    // with ncol > 1 needs extra legend band width for
                    // its later columns, or they run off the canvas
                    // (cols is always 1, col_pitch 0, for the horizontal
                    // auto-wrap path, so this is a no-op there). Several
                    // guides take the widest requirement among them.
                    extras.legend_extra_width = plans
                        .values()
                        .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
                        .fold(0.0_f64, f64::max);

                    // #159: a vertical multi-column grid that still runs
                    // off the canvas even after reserving the extra width
                    // above now (1) tries reducing its column count
                    // toward 1 — the first count that fits wins; (2) if
                    // even one column still overflows, truncates labels
                    // with an ellipsis (keeping the full label available
                    // via a `<title>`); and only (3) warns if it still
                    // doesn't fit after both. A grid that already fits is
                    // untouched — no reduction, no truncation, no warning
                    // (review #158's second re-review, LOW, is the
                    // original "warn only" version of this check).
                    if !is_horizontal {
                        let final_layout = PlotLayout::compute_with_extras(
                            w as f64,
                            h as f64,
                            &built.theme,
                            has_title,
                            has_subtitle,
                            has_caption,
                            has_legend,
                            x_axis_top,
                            y_label_width,
                            x_label_height,
                            extras,
                        );
                        // `y` is unused here too, but `extras` is final by
                        // this point, so pass its real `legend_extra_rows`
                        // for consistency with #233's `Top` formula. #225's
                        // `Inside` size hint is skipped here for the same
                        // reason as the pass above.
                        let (legend_x_final, _, _) = crate::guide::legend::legend_position(
                            &built.theme,
                            &final_layout.plot_area,
                            extras.legend_extra_rows,
                            (0.0, 0.0),
                            0.0,
                            &final_layout.total,
                        );
                        let swatch_and_gap =
                            built.theme.legend_key_width + built.theme.legend_spacing;
                        let text_size = built.theme.legend_text.size;
                        // A plain fn, not a closure: #168's retightening
                        // pass below re-runs this same check at a second
                        // `legend_x` (the narrower reservation's), so
                        // `legend_x` has to be a parameter rather than
                        // captured.
                        fn right_edge_of(
                            legend_x: f64,
                            swatch_and_gap: f64,
                            text_size: f64,
                            plan: &crate::guide::legend::LegendPlan,
                            breaks: &[(f64, String)],
                        ) -> f64 {
                            plan.entries
                                .iter()
                                .filter_map(|e| breaks.get(e.break_idx).map(|(_, l)| (e, l)))
                                .map(|(e, label)| {
                                    let text =
                                        e.label_override.as_deref().unwrap_or(label.as_str());
                                    legend_x
                                        + e.x_offset
                                        + swatch_and_gap
                                        + crate::render::text::text_width(text, text_size)
                                })
                                .fold(0.0_f64, f64::max)
                        }

                        let mut updates: Vec<(
                            crate::aes::Aesthetic,
                            crate::guide::legend::LegendPlan,
                        )> = Vec::new();
                        // #168: guides narrowed below by *column
                        // reduction* (not label truncation) are
                        // candidates for the retightening pass after this
                        // loop — a truncated guide already picked the
                        // narrowest column count, so there's no reserved
                        // width left to give back.
                        let mut reduced_aes: Vec<crate::aes::Aesthetic> = Vec::new();
                        for (aes, plan) in &plans {
                            if plan.cols <= 1 {
                                continue;
                            }
                            let Some(scale) = built.scales.get(aes) else {
                                continue;
                            };
                            let breaks = scale.breaks();
                            if right_edge_of(
                                legend_x_final,
                                swatch_and_gap,
                                text_size,
                                plan,
                                &breaks,
                            ) <= w as f64
                            {
                                continue; // already fits — untouched.
                            }

                            // Step 1: reduce columns toward 1; the first
                            // count that fits wins.
                            let n = breaks.len();
                            let mut reduced: Vec<crate::guide::legend::LegendPlan> = Vec::new();
                            for c in (1..plan.cols).rev() {
                                let mut candidate_guide = built.guide_legend.clone();
                                candidate_guide.ncol = Some(c);
                                candidate_guide.nrow = None;
                                let mut tmp_warnings = Vec::new();
                                let candidate_guide =
                                    candidate_guide.validated(n, &mut tmp_warnings);
                                if let Some(cand) = crate::guide::legend::plan_legend(
                                    &breaks,
                                    &candidate_guide,
                                    &built.theme,
                                    avail_width,
                                    layout0.plot_area.height,
                                    false,
                                ) {
                                    reduced.push(cand);
                                }
                            }
                            if let Some(fits) = reduced.iter().find(|c| {
                                right_edge_of(legend_x_final, swatch_and_gap, text_size, c, &breaks)
                                    <= w as f64
                            }) {
                                extras.legend_extra_rows =
                                    extras.legend_extra_rows.max(fits.rows.saturating_sub(1));
                                updates.push((aes.clone(), fits.clone()));
                                reduced_aes.push(aes.clone());
                                continue;
                            }

                            // Step 2: no column count fit — truncate
                            // labels (starting from the narrowest, 1-
                            // column, candidate) with an ellipsis, each
                            // to whatever room its own position leaves.
                            let base = reduced.last().cloned().unwrap_or_else(|| plan.clone());
                            extras.legend_extra_rows =
                                extras.legend_extra_rows.max(base.rows.saturating_sub(1));
                            let mut truncated = base.clone();
                            for e in &mut truncated.entries {
                                let Some((_, label)) = breaks.get(e.break_idx) else {
                                    continue;
                                };
                                let avail = (w as f64
                                    - (legend_x_final + e.x_offset + swatch_and_gap))
                                    .max(0.0);
                                if let Some(short) =
                                    crate::render::text::truncate_to_width(label, avail, text_size)
                                {
                                    e.label_override = Some(short);
                                }
                            }

                            // Step 3: only warn if it still doesn't fit
                            // after both the reduction and the
                            // truncation above.
                            let truncated_edge = right_edge_of(
                                legend_x_final,
                                swatch_and_gap,
                                text_size,
                                &truncated,
                                &breaks,
                            );
                            if truncated_edge > w as f64 {
                                built.warnings.push(format!(
                                    "legend: the {}-column grid still doesn't fit the {w}px chart (needs about {} px)",
                                    truncated.cols,
                                    truncated_edge.ceil() as i64
                                ));
                            }
                            updates.push((aes.clone(), truncated));
                        }
                        for (aes, new_plan) in &updates {
                            plans.insert(aes.clone(), new_plan.clone());
                        }

                        // #168: `extras.legend_extra_width` above still
                        // reserves the *original*, pre-reduction column
                        // count's width — that stale, wider reservation
                        // is an accident of ordering (reserve → layout →
                        // fit? → reduce), not a requirement, so the panel
                        // stays narrower than it needs to be once a guide
                        // above got fewer columns.
                        //
                        // Tighten it to the reduced guides' new column
                        // counts and re-check fit once more at the
                        // narrower reservation (a bounded retry, not an
                        // unbounded fixed point: a tighter reservation
                        // moves `legend_x_final` right — less headroom
                        // before the canvas edge — which could in
                        // principle call for yet another round of
                        // reduction; rather than chase reserve → layout →
                        // fit → reduce → reserve → … indefinitely, this
                        // keeps the tighter reservation only if every
                        // guide still fits under it, and falls back to
                        // the wider, already-proven-safe reservation
                        // otherwise — so retightening can only ever
                        // help, never regress a plot that fit before
                        // this pass existed).
                        //
                        // Review #167 finding 1 on #171 (HIGH, fixed):
                        // the retry must re-check *every* plan in
                        // `plans`, not just `reduced_aes`. `legend_x`
                        // moves for every guide sharing the row, not
                        // only the one(s) that got reduced — a second
                        // guide that already fit at the old, wider
                        // `legend_x_final` (its own width is a fixed
                        // `6·text_size` estimate, unrelated to the
                        // reduced guide's labels) or whose labels were
                        // truncated against that old `legend_x_final`
                        // shifts right by the same amount and was never
                        // re-checked, so it could run off the canvas
                        // with no warning (the warnings were computed
                        // against the old x too). `reduced_aes` is kept
                        // only to gate *entering* this block at all —
                        // nothing to reclaim if nothing was reduced.
                        if !reduced_aes.is_empty() {
                            let original_reserve = extras.legend_extra_width;
                            let tighter_reserve = plans
                                .values()
                                .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
                                .fold(0.0_f64, f64::max);
                            if tighter_reserve < original_reserve {
                                let mut retry_extras = extras;
                                retry_extras.legend_extra_width = tighter_reserve;
                                let retry_layout = PlotLayout::compute_with_extras(
                                    w as f64,
                                    h as f64,
                                    &built.theme,
                                    has_title,
                                    has_subtitle,
                                    has_caption,
                                    has_legend,
                                    x_axis_top,
                                    y_label_width,
                                    x_label_height,
                                    retry_extras,
                                );
                                // `y` is unused here too; `retry_extras`
                                // only tightened `legend_extra_width`, so
                                // its `legend_extra_rows` is still the same
                                // real value. #225's `Inside` size hint is
                                // skipped for the same reason as above.
                                let (retry_x, _, _) = crate::guide::legend::legend_position(
                                    &built.theme,
                                    &retry_layout.plot_area,
                                    retry_extras.legend_extra_rows,
                                    (0.0, 0.0),
                                    0.0,
                                    &retry_layout.total,
                                );
                                let all_still_fit = plans.iter().all(|(aes, plan)| {
                                    let Some(scale) = built.scales.get(aes) else {
                                        return true;
                                    };
                                    let breaks = scale.breaks();
                                    right_edge_of(retry_x, swatch_and_gap, text_size, plan, &breaks)
                                        <= w as f64
                                });
                                if all_still_fit {
                                    extras.legend_extra_width = tighter_reserve;
                                }
                            }
                        }
                    }
                    for (aes, plan) in &plans {
                        if let Some(ov) = &plan.overflow {
                            let n = built
                                .scales
                                .get(aes)
                                .map(|s| s.breaks().len())
                                .unwrap_or(ov.dropped);
                            let shown = n.saturating_sub(ov.dropped);
                            built.warnings.push(format!(
                                "legend: {} of {n} entries don't fit the chart; the legend shows {shown} and \"+{} more\"",
                                ov.dropped, ov.dropped
                            ));
                        }
                    }
                }
                // Review #158 finding 2: store these exact plans so
                // `draw_legend_planned` draws them verbatim instead of
                // recomputing against the (shorter) post-reservation
                // panel height, which could warn "+7 more" while
                // drawing "+15 more".
                built.legend_plans = plans;
            }
        }

        // #409: a `guide_colourbar(bar_width)` wider than a legend key
        // widens a side legend's reserved band by the difference.
        if has_legend
            && matches!(
                built.theme.legend_position,
                crate::theme::LegendPosition::Left | crate::theme::LegendPosition::Right
            )
            && !matches!(
                built.theme.legend_direction,
                Some(crate::theme::LegendDirection::Horizontal)
            )
        {
            let key_w = built.theme.legend_key_width.max(extras.legend_max_key_size);
            let extra =
                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes)
                    .iter()
                    .filter(|aes| {
                        crate::guide::legend::is_colorbar_aesthetic(aes)
                            && built.scales.get(aes).is_some_and(|s| !s.is_discrete())
                    })
                    .filter_map(|aes| built.guide_legend.colourbar_for(aes).bar_width)
                    .map(|w| (w - key_w).max(0.0))
                    .fold(0.0_f64, f64::max);
            extras.legend_extra_width = extras.legend_extra_width.max(extra);
            // #409: a custom guide wider than a key + its label column.
            let text_col = key_w + built.theme.legend_spacing + built.theme.legend_text.size * 6.0;
            let custom = built
                .guide_legend
                .custom
                .iter()
                .map(|g| (g.width - text_col).max(0.0))
                .fold(0.0_f64, f64::max);
            extras.legend_extra_width = extras.legend_extra_width.max(custom);
        }

        // #211: a continuous colourbar at `Top`/`Bottom` (or
        // `legend_direction(Horizontal)`) draws wide × short instead of
        // its usual tall × narrow bar (see `draw_continuous_legend_at`),
        // with its tick labels below rather than beside it — reserve the
        // extra band height that needs beyond the flat discrete-row
        // height `legend_band` already assumes. Independent of the
        // `has_wrap_guide` block above (a plot can have a continuous
        // colourbar with no other guide at all), so computed
        // unconditionally here, right before the layout that actually
        // matters reads `extras`.
        if has_legend
            && !matches!(
                built.theme.legend_position,
                crate::theme::LegendPosition::None
            )
        {
            let is_horizontal = match built.theme.legend_direction {
                Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
                None => matches!(
                    built.theme.legend_position,
                    crate::theme::LegendPosition::Top | crate::theme::LegendPosition::Bottom
                ),
            };
            if is_horizontal {
                let legend_aes =
                    crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
                let continuous_colourbar = legend_aes.iter().find_map(|aes| {
                    if !matches!(
                        aes,
                        crate::aes::Aesthetic::Color | crate::aes::Aesthetic::Fill
                    ) {
                        return None;
                    }
                    let scale = built.scales.get(aes)?;
                    if scale.is_discrete() {
                        return None;
                    }
                    Some(scale)
                });
                if let Some(scale) = continuous_colourbar {
                    let title = built
                        .guide_legend
                        .title
                        .as_deref()
                        .unwrap_or_else(|| scale.name());
                    let bar_height = crate::guide::legend::continuous_horizontal_bar_height(
                        &built.theme,
                        !title.is_empty(),
                        &built.guide_legend.colourbar_for(&scale.aesthetic()),
                    );
                    let key_h = built
                        .theme
                        .legend_key_height
                        .max(extras.legend_max_key_size);
                    extras.continuous_horizontal_legend_extra_height =
                        (bar_height - key_h).max(0.0);
                }
                // #409: a custom guide taller than a key row.
                let key_h = built
                    .theme
                    .legend_key_height
                    .max(extras.legend_max_key_size);
                let custom = built
                    .guide_legend
                    .custom
                    .iter()
                    .map(|g| (g.title_offset(&built.theme) + g.height - key_h).max(0.0))
                    .fold(0.0_f64, f64::max);
                extras.continuous_horizontal_legend_extra_height =
                    extras.continuous_horizontal_legend_extra_height.max(custom);
            }
        }

        PlotLayout::compute_with_extras(
            w as f64,
            h as f64,
            &built.theme,
            has_title,
            has_subtitle,
            has_caption,
            has_legend,
            x_axis_top,
            y_label_width,
            x_label_height,
            extras,
        )
    }

    /// Fill the background, render the built plot, and flush — for any plotters
    /// backend. (Native only.)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    fn render_into<DB>(
        area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
        built: &crate::build::BuiltPlot,
        layout: &PlotLayout,
    ) -> Result<(), GGError>
    where
        DB: plotters::prelude::DrawingBackend,
        DB::ErrorType: 'static,
    {
        area.fill(&plotters::prelude::WHITE)
            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
        let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
        PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
        area.present()
            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
        Ok(())
    }

    /// Save with physical dimensions (inches) and DPI. (Feature `plotters`;
    /// native only.)
    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
    pub fn ggsave(
        self,
        path: &str,
        width_inches: f64,
        height_inches: f64,
        dpi: f64,
    ) -> Result<(), GGError> {
        let w = (width_inches * dpi) as u32;
        let h = (height_inches * dpi) as u32;
        self.save_with_size(path, w, h)
    }

    /// Does this plot have a legend to make room for? (#201) A plot-level
    /// `.aes(...)` mapping always counts; so does a *layer's own*
    /// `.layer_aes(...)` mapping — e.g. `geom_hex`'s usual pattern of
    /// mapping `fill` to a raw column only on that one layer, via
    /// `StatIdentity` after pre-binning, rather than on the plot as a
    /// whole. Checking only `self.mapping` (as before) missed that case
    /// entirely: the legend still drew (the render path always draws
    /// whatever guides the trained scales produce, regardless of this
    /// flag), just with no panel margin ever reserved for it, so it ran
    /// straight off the canvas edge. A layer that opts out with
    /// `show_legend(false)` doesn't count towards its own mapping, mirroring
    /// `PlotBuilder::compute_suppressed_aes`'s later, more precise
    /// (post-build, cross-layer) suppression check — this one only needs to
    /// decide *whether to reserve space at all*, not exactly how much.
    fn has_legend_mapping(&self) -> bool {
        // #241: delegates to `guide::legend::is_legend_aesthetic` (the
        // same list `draw_legend_planned` itself draws from) rather than
        // keeping its own copy — a second, independently-maintained list
        // here had drifted out of sync, missing `Linewidth`.
        use crate::guide::legend::is_legend_aesthetic;
        let plot_level = self
            .mapping
            .mappings
            .iter()
            .any(|m| is_legend_aesthetic(&m.aesthetic));
        // #409: a custom guide needs the legend band even with no mapping.
        !self.guide_legend.custom.is_empty()
            || plot_level
            || self.layers.iter().any(|layer| {
                if layer.show_legend == Some(false) {
                    return false;
                }
                let effective = if layer.geom.inherit_aes() {
                    self.mapping.merge(&layer.mapping)
                } else {
                    layer.mapping.clone()
                };
                effective
                    .mappings
                    .iter()
                    .any(|m| is_legend_aesthetic(&m.aesthetic))
            })
    }
}

/// Size-independent facts about a built plot that its layout needs.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RenderMeta {
    pub(crate) has_title: bool,
    pub(crate) has_subtitle: bool,
    pub(crate) has_caption: bool,
    pub(crate) has_legend: bool,
    pub(crate) legend_bottom_share: Option<f64>,
    pub(crate) legend_auto: Option<LegendAuto>,
}

/// [`GGPlot::legend_inside_auto_with`]'s settings (#332).
#[derive(Clone, Copy, Debug)]
pub(crate) struct LegendAuto {
    corners: [Option<crate::theme::LegendCorner>; 4],
    fallback: Option<LegendSide>,
}

/// An outside legend side (a `Copy` subset of `LegendPosition`).
#[derive(Clone, Copy, Debug)]
enum LegendSide {
    Top,
    Right,
    Bottom,
    Left,
}

impl LegendSide {
    fn position(self) -> crate::theme::LegendPosition {
        use crate::theme::LegendPosition as P;
        match self {
            LegendSide::Top => P::Top,
            LegendSide::Right => P::Right,
            LegendSide::Bottom => P::Bottom,
            LegendSide::Left => P::Left,
        }
    }
}

/// Top-level error type.
#[derive(Debug)]
#[non_exhaustive]
pub enum GGError {
    Render(RenderError),
    UnsupportedFormat(String),
    Io(std::io::Error),
    ValidationError(String),
}

impl std::fmt::Display for GGError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GGError::Render(e) => write!(f, "Render error: {e}"),
            GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
            GGError::Io(e) => write!(f, "IO error: {e}"),
            GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
        }
    }
}

impl std::error::Error for GGError {}

/// A Brewer palette as a continuous gradient (`scale_*_distiller`).
fn distiller(
    aes: crate::aes::Aesthetic,
    palette: &crate::scale::palettes::PaletteName,
    direction: i32,
) -> crate::scale::gradient_n::ScaleColorGradientN {
    let mut colors = crate::scale::palettes::palette(palette).to_vec();
    if direction < 0 {
        colors.reverse();
    }
    let n = colors.len().max(2) - 1;
    let stops = colors
        .into_iter()
        .enumerate()
        .map(|(i, c)| (i as f64 / n as f64, c))
        .collect();
    crate::scale::gradient_n::ScaleColorGradientN::new(aes, stops)
}