Skip to content

Scenes & multi-panel figures (matplotlib)#

Scene is the static tier's base host: one matplotlib figure, one axes, and the list of layers drawn onto it. Map is a Scene with a display CRS on top, so everything on this page — the layer list, the colour keys, the title, save/show/close and with — is also how a Map behaves.

import matplotlib.pyplot as plt
from digitalearth.static import Scene

fig, ax = plt.subplots()
with Scene(ax=ax, fig=fig) as scene:
    scene.set_title("Composed on an axes of my own")
    scene.save("scene.png")

One scene per axes#

A scene may be handed an axes, to place it inside a figure you are laying out yourself, but two scenes must not share one axes: each keeps its own record of what it has drawn, and the second one's first render clears what the first drew while the first goes on describing it. Give every scene its own axes — which is what grid does.

Several panels in one figure#

grid(nrows, ncols, crs=...) builds the matplotlib subplot grid and binds a Map to each cell, returning (fig, maps) in row-major order. The panels share one figure, so one savefig writes them all and shared_colorbar(fig, mappable, maps) adds a single bar spanning the panels you name.

from digitalearth.static import grid, shared_colorbar

fig, maps = grid(1, 2, crs=4326)
left = maps[0].field(rain_2023)
maps[1].field(rain_2024)
shared_colorbar(fig, left, maps, label="mm")
fig.savefig("rain.png")

Because the panels share that figure, closing one panel closes the figure for all of them — do not wrap a single grid panel in with; save the figure and close it once.

Skipping or raising on an empty layer#

strict=False (the default) skips a layer that has nothing to draw — data entirely outside the view, or a band with no finite values — and logs a warning naming it, so one bad frame does not abort a batch. strict=True raises instead, for a pipeline that must not publish a figure with a layer missing.

digitalearth.static.core.scene.Scene #

Bases: WatermarkMixin

A shared-axes host for composing cleopatra glyph layers into one figure.

Inherits cleopatra's WatermarkMixin, whose surface comes with it as-is: :meth:stamp below is this package's documented spelling for the logo stamp, and stamp_watermark(text) (diagonal brand text with an optional credit line) is available unchanged from upstream, documented there rather than here.

One scene per axes. A scene may be handed an axes to draw on — to place a map inside a figure you are laying out yourself — but two scenes sharing one axes is not supported. Each keeps its own record of what it has drawn and its own "have I drawn here yet" flag, and a cleopatra glyph clears the axes on a scene's first render: so the second scene wipes the first one's drawing while the first goes on describing it, and the figure it reports names a layer whose artist is gone. Lay several maps out as several axes (:func:~digitalearth.static.panels.figure.grid does), and give each its own.

Parameters:

Name Type Description Default
ax Axes | None

An existing axes to draw on. When None a new figure/axes is created. One axes, one scene — see above.

None
fig Figure | None

The figure owning ax. Ignored unless ax is also given.

None
figsize tuple[float, float]

Size of the new figure when one is created ((width, height) in inches).

(8, 8)
strict bool

How a layer with nothing to draw is handled. False (default) skips it and logs a warning naming the layer and why; True raises instead, so a pipeline that must not silently produce an empty figure fails where the layer was added.

False

Attributes:

Name Type Description
fig Figure

The matplotlib figure.

ax Axes

The matplotlib axes all layers render onto.

layers list[tuple[Any, Any]]

Registered (glyph, mappable) pairs, in draw order. A colour key is addressed by layer id rather than by position here (order 24); what this list is still read for is the default title filed beside each pair — see :meth:_registered_index.

strict bool

Whether a layer that draws nothing raises instead of being skipped.

Examples:

  • Create a scene; it owns exactly one axes until a colorbar is added, and describes nothing yet:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Scene
    >>> scene = Scene()
    >>> len(scene.fig.axes)
    1
    >>> scene.layers
    []
    >>> scene.layer_ids
    []
    >>> scene.close()
    
  • Wrap a caller-supplied figure/axes instead of creating one:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static import Scene
    >>> fig, ax = plt.subplots()
    >>> scene = Scene(ax=ax, fig=fig)
    >>> scene.ax is ax
    True
    >>> Scene(ax=ax).fig is fig
    True
    >>> plt.close(fig)
    
  • A fig the axes does not belong to is refused rather than stored, so a scene is never split across two figures:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static import Scene
    >>> fig, ax = plt.subplots()
    >>> elsewhere = plt.figure()
    >>> Scene(ax=ax, fig=elsewhere)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: the given fig= is not the figure that owns ax=, ...
    >>> plt.close(elsewhere)
    >>> plt.close(fig)
    
Source code in src/digitalearth/static/core/scene.py
 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
class Scene(WatermarkMixin):
    """A shared-axes host for composing cleopatra glyph layers into one figure.

    Inherits cleopatra's ``WatermarkMixin``, whose surface comes with it as-is: :meth:`stamp` below is this
    package's documented spelling for the logo stamp, and ``stamp_watermark(text)`` (diagonal brand text
    with an optional credit line) is available unchanged from upstream, documented there rather than here.

    **One scene per axes.** A scene may be handed an axes to draw on — to place a map inside a figure you
    are laying out yourself — but **two scenes sharing one axes is not supported**. Each keeps its own
    record of what it has drawn and its own "have I drawn here yet" flag, and a cleopatra glyph clears the
    axes on a scene's first render: so the second scene wipes the first one's drawing while the first goes
    on describing it, and the figure it reports names a layer whose artist is gone. Lay several maps out as
    several axes (:func:`~digitalearth.static.panels.figure.grid` does), and give each its own.

    Args:
        ax: An existing axes to draw on. When ``None`` a new figure/axes is created. One axes, one scene —
            see above.
        fig: The figure owning ``ax``. Ignored unless ``ax`` is also given.
        figsize: Size of the new figure when one is created (``(width, height)`` in inches).
        strict: How a layer with nothing to draw is handled. ``False`` (default) skips it and logs a
            warning naming the layer and why; ``True`` raises instead, so a pipeline that must not
            silently produce an empty figure fails where the layer was added.

    Attributes:
        fig: The matplotlib figure.
        ax: The matplotlib axes all layers render onto.
        layers: Registered ``(glyph, mappable)`` pairs, in draw order. A colour key is addressed by layer
            **id** rather than by position here (order 24); what this list is still read for is the default
            title filed beside each pair — see :meth:`_registered_index`.
        strict: Whether a layer that draws nothing raises instead of being skipped.

    Examples:
        - Create a scene; it owns exactly one axes until a colorbar is added, and describes nothing yet:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Scene
            >>> scene = Scene()
            >>> len(scene.fig.axes)
            1
            >>> scene.layers
            []
            >>> scene.layer_ids
            []
            >>> scene.close()

            ```
        - Wrap a caller-supplied figure/axes instead of creating one:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static import Scene
            >>> fig, ax = plt.subplots()
            >>> scene = Scene(ax=ax, fig=fig)
            >>> scene.ax is ax
            True
            >>> Scene(ax=ax).fig is fig
            True
            >>> plt.close(fig)

            ```
        - A `fig` the axes does not belong to is refused rather than stored, so a scene is never split
          across two figures:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static import Scene
            >>> fig, ax = plt.subplots()
            >>> elsewhere = plt.figure()
            >>> Scene(ax=ax, fig=elsewhere)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: the given fig= is not the figure that owns ax=, ...
            >>> plt.close(elsewhere)
            >>> plt.close(fig)

            ```
    """

    def __init__(
        self,
        ax: Axes | None = None,
        fig: Figure | None = None,
        figsize: tuple[float, float] = (8, 8),
        strict: bool = False,
    ):
        """Build the shared figure/axes host that layers render onto.

        Args:
            ax: An existing axes to draw on — pass one to compose a Digital-Earth layer into a figure you are
                laying out yourself. **That figure is spared on exit**: a scene built with ``ax=`` does not
                own its figure (``_owns_fig`` is ``False``), so :meth:`close` and a ``with`` block leave the
                caller's figure open and release only this scene's own state — the object table and the pick
                handler it connected. This is #371, **resolved** (R2-L12): the old code stored the `None` it
                was passed and reached ``pyplot.close(None)``, closing whichever figure was *current*, so a
                borrowed figure was spared or closed only by luck; now it is spared on purpose, the way
                :meth:`~digitalearth.static.globe.textured_globe.TexturedGlobe.close` always has. Give each scene
                an axes of its own all the same: a second scene on the same axes clears what the first drew
                on its opening render, and the first still describes it (see the class docstring).
            fig: The figure `ax` belongs to; taken from `ax` when omitted — its **root** figure, for an
                axes inside a ``SubFigure``, since :meth:`save` and :meth:`close` hand the figure to
                ``savefig`` and ``pyplot.close`` and neither takes a subfigure. It is a **confirmation of
                the axes' own figure, not an override**: naming a different one is refused, and naming one
                without an `ax` is refused too. `grid` passes `ax=ax, fig=fig` for every panel and that is
                the shape this argument exists for. Storing a figure that disagreed split the scene across
                two — layers on `ax` in one, :meth:`save`, :meth:`close` and :attr:`figure_spec` on the
                other; measured, ``save()`` wrote a 2492-byte blank where the real figure was 7107 bytes
                and ``figure_spec.title`` read `None` off the empty one while the drawn figure was headed
                (R2-M8). A caller composing into a figure of their own passes an `ax` *from* it, which the
                derivation already honours. Because a scene always holds a real figure now, the note on
                `ax` above holds for a scene given **only** an axes too: the figure is derived and read by
                :meth:`save` and :attr:`figure_spec`, but it is a borrowed figure, so :meth:`close` **spares**
                it (``_owns_fig`` is ``False``). The derivation only fixed which figure those reads see; it
                did not make the scene own it.
            figsize: Size of the figure created when `ax` is None, in inches.
            strict: What to do with a layer that has nothing to draw — data entirely outside the view, or a
                band with no finite values. `False` (the default) skips it with a warning naming the layer,
                so one bad frame does not abort a batch; `True` raises `OffLimbError` instead, which is what
                a pipeline that must not publish a map with a layer missing should pass.

        Raises:
            ValueError: when `fig` is named without an `ax`, or names a figure that `ax` does not belong
                to. Both are a `fig=` the scene cannot honour, and storing one quietly split the scene
                across two figures (R2-M8).
        """
        made_figure = ax is None
        if ax is None:
            if fig is not None:
                raise ValueError(
                    "fig= is only read together with ax=: it names the figure that axes belongs to, and "
                    "a scene given no axes builds a figure of its own, so the figure named here would "
                    "never be drawn on. Pass ax= as well, or drop fig=."
                )
            fig, ax = plt.subplots(figsize=figsize)
        elif fig is not None and fig is not ax.get_figure(root=True):
            raise ValueError(
                "the given fig= is not the figure that owns ax=, so the scene would be split across two: "
                "layers draw on the axes, while save(), close() and figure_spec all act on fig=. Pass "
                "only ax= (its figure is derived), or an axes that belongs to fig=."
            )
        # Derived when the caller names only the axes, which is what `fig`'s own documentation has always
        # promised ("taken from `ax` when omitted") and what the `Figure` annotation below claims. It was
        # stored as the `None` it was passed instead, so every one of the nine `self.fig` reads was an
        # `AttributeError` waiting on a figure a caller laid out themselves: `save` and `on_pick` (ST-25)
        # from the start, `figure_spec` — and so every builder, which describes itself as it draws — since
        # the figure's heading began to be read off the figure (M4). `close()` reached `plt.close(None)`,
        # which closes whatever figure happens to be *current* (measured: figures [1, 2, 3] current 3 ->
        # [1, 2]) — the scene's own only by luck. An explicit `fig=` still wins, and the **root** figure is
        # taken for an axes inside a `SubFigure`, because `self.fig` is what `savefig` and `pyplot.close`
        # are handed and neither takes a subfigure.
        self.fig: Figure = fig if fig is not None else ax.get_figure(root=True)
        self.ax: Axes = ax
        # Whether this scene made the figure, or was handed one somebody else lays out. Recorded here
        # rather than counted later, because `len(self.fig.axes)` does not answer it: a lone map that
        # has drawn a colorbar holds two axes, and a `grid` panel whose siblings have been removed holds
        # one. It is what tells a figure-level restore it is writing shared state (R2-M1) — a `grid`
        # panel is given `ax=`, so it never owns its figure, while `Map(crs=...)` always does.
        self._owns_fig: bool = made_figure
        self.strict: bool = bool(strict)
        self.layers: list[tuple[Any, Any]] = []
        #: One entry per registered layer (same order as :attr:`layers`): the label :meth:`colorbar` falls
        #: back to when the caller passes none — the layer's resolved ``units``, or ``None``.
        self._layer_labels: list[str | None] = []
        # What the scene draws, as data. `self.layers` holds the matplotlib artists — the drawing — and this
        # holds the description each was built from, which is what a figure can be written to and read back
        # from (#303). They are not the same list: a basemap, a graticule or a Natural-Earth overlay draws
        # straight onto the axes with no mappable to register, and is described all the same.
        self._layer_tree: LayerTree = LayerTree()
        self._sources: dict[str, DataRef] = {}
        # Namespaced per scene: every figure restarts its layer numbering, so two maps in one session both
        # mint `raster-1`, and one process-global object table would have the second silently re-point the
        # first figure's captured source at its own data.
        self._objects_ns: str = object_namespace()
        #: The highest number issued for each generated-id prefix, so an unnamed layer is numbered
        #: within its kind rather than within the figure (review R2-M10).
        self._id_counters: dict[str, int] = {}
        self._issued_ids: set[str] = set()
        # What a drawer needs that the figure cannot carry — a clip boundary, a basemap credential — keyed
        # by layer id. Deliberately not part of `symbology`: a figure is written to JSON and read back, and
        # neither a shapely geometry nor an API key belongs in one (see `LayerRecord.key`).
        self._layer_keys: dict[str, Any] = {}
        # The caller's engine keywords, exactly as passed, keyed by layer id (see `LayerRecord.opts`). The
        # plain ones are described as well; these are the objects themselves, and for a dash tuple, a
        # `Normalize` or a colormap object this is the only place they live — a description is plain values,
        # and none of those is one.
        self._layer_opts: dict[str, dict[str, Any]] = {}
        # The caller's own objects, for the custom layers they handed in (see `LayerRecord.held`).
        self._held_objects: dict[str, Any] = {}
        # Where each layer's coordinates are placed — `IN_DISPLAY_CRS` or `AT_INDICES` — keyed by layer id,
        # so `_require_one_placement` can refuse the figure that would hold both. A `custom:matplotlib`
        # layer has no entry: the caller's own artist is in the caller's own coordinates.
        self._layer_placements: dict[str, str] = {}
        # Whether this scene has already drawn a glyph onto `ax` (#313). A cleopatra glyph clears every
        # glyph's artists off its axes unless it is told to compose, so from the *second* layer onwards a
        # render has to compose or it takes the layer below it off again. Only from the second: the first
        # one keeps replacing, so a scene handed an axes another figure was drawn on — including one an
        # earlier scene drew — still supersedes it rather than stacking on top of it silently.
        self._drew_on_axes: bool = False
        #: The class edges of the most recent **graduated** layer, read off the ``BoundaryNorm`` its mappable
        #: is coloured through — the same reading the web and interactive tiers publish under this name, so a
        #: caller building a key out of band gets one answer whichever tier drew the map
        #: (``tests/base/test_map_conformance.py``).
        #:
        #: ``None`` when nothing has classified yet, when the most recent colour-mapped layer was a
        #: continuous ramp, and for a **categorical** fill — whose norm bins the class *codes* cleopatra
        #: assigned (measured: ``[-0.5, 0.5, 1.5]`` for two categories) rather than the caller's own values,
        #: so reporting them as class edges would be reporting a wrong answer. A categorical key is the
        #: swatch legend the glyph draws on this tier.
        self.last_breaks: list[float] | None = None
        # The callbacks a click on this figure is delivered to, and the canvas connection that feeds them
        # (see `on_pick`). The connection is made on the first registration rather than in the constructor,
        # so a scene nobody picks on puts no handler on the canvas at all.
        self._pick_handlers: list[Callable[[Pick], Any]] = []
        self._pick_cid: int | None = None
        # The panel's title, as the description carries it (see `set_title`); the figure's own heading is
        # its `suptitle`, read off the figure by `figure_spec`. Held on the scene rather than read back off
        # `ax.title`, because matplotlib keeps three titles on an axes — centre, left and right — and a
        # panel has one title whichever of them it was drawn at.
        self._title: str | None = None
        #: The renderer that turns this scene's description into artists on :attr:`ax`.
        self._renderer: Renderer = Renderer(self)

    def _layer_id(self, prefix: str, name: Any = None) -> str:
        """Return a unique layer id: the caller's name when they gave one, else a generated one.

        Args:
            prefix: What a generated id counts — the kind, usually.
            name: The caller's own name for the layer, used as its id when it is free. Normalised by
                :func:`~digitalearth.base.spec.layer.layer_name`, so surrounding whitespace is dropped and a
                blank name means no name (review R2-H4).

        Returns:
            The id. A caller's name that is already issued is suffixed ``-2``, ``-3``, … by
            :func:`~digitalearth.base.spec.layer.free_layer_id` — the rule all four tiers share (#321) —
            because two layers sharing an id makes the second unaddressable. An unnamed layer is numbered
            **within its kind**, so two kinds interleaved give ``points-1``, ``text-1``, ``points-2``,
            ``text-2`` (review R2-M10).

        Raises:
            TypeError: if `name` is neither a string nor `None`.
        """
        asked = layer_name(name)
        if asked is not None:
            candidate = free_layer_id(asked, self._issued_ids.__contains__)
        else:
            candidate = self._generated_id(prefix)
        self._issued_ids.add(candidate)
        return candidate

    def _generated_id(self, prefix: str) -> str:
        """Return the next generated id for one kind, stepping over any a caller already holds.

        One counter per prefix, not one per scene (review R2-M10). A single scene-wide counter numbered the
        *figure*: ``scatter, text, scatter, text`` came back as ``points-1, text-2, points-3, text-4``, which
        reads as if two layers had gone missing — and disagreed with the 3-D tier, which has always counted
        within the kind, and with what this tier's own :attr:`layer_ids` docstring claimed (review R2-L2).

        Args:
            prefix: What the id counts — the kind, with any engine namespace already removed.

        Returns:
            ``f"{prefix}-{n}"`` with the lowest ``n`` this scene has not issued. The counter stays where the
            search ended, so the next layer of the same kind does not re-walk the ids it stepped over.
        """
        number = self._id_counters.get(prefix, 0)
        while True:
            number += 1
            candidate = f"{prefix}-{number}"
            if candidate not in self._issued_ids:
                self._id_counters[prefix] = number
                return candidate

    def _index_layer(
        self,
        layer_id: str,
        label: str | None,
        *,
        kind: str,
        visible: bool = True,
        band: str | None = None,
        source: Any = None,
        symbology: Any = None,
    ) -> None:
        """Record a layer so the figure describes it rather than only holding its artist.

        Args:
            layer_id: The layer's id, as :attr:`layer_ids` reports it.
            label: What a layer switcher should call it; `None` — or a name that is nothing but
                whitespace — falls back to the id. Normalised with
                :func:`~digitalearth.base.spec.layer.layer_name`, so it agrees with the id it came from.
            kind: The registered, engine-neutral kind — `"raster"`, `"points"`, `"choropleth"` — not the
                matplotlib artist class, which cannot tell a choropleth from a plain polygon fill.
            visible: Whether the layer was built visible.
            band: Where it is drawn, when its kind does not say — what a backdrop and a caller's own artist
                need, since `custom:matplotlib` names the engine rather than what it draws.
            source: What the layer draws, recorded under its id. `None` for a layer drawn from no data.
            symbology: How it looks, as values rather than as the flat kwargs the glyph was handed.
        """
        if source is not None:
            self._sources[layer_id] = DataRef.of(
                source, name=f"{self._objects_ns}:{layer_id}"
            )
        self._layer_tree = self._layer_tree.add(
            LayerSpec(
                layer_id,
                kind,
                source_id=layer_id if source is not None else None,
                symbology=Symbology() if symbology is None else symbology,
                # Normalised like the id it falls back to: the two come from one `name=`, and a label
                # that kept padding the id had dropped was the same invisible difference in the other
                # field — two layers a switcher captions identically (review R2-H4).
                label=layer_name(label) or layer_id,
                # By truthiness, because a builder decides visibility the same loose way it decides every
                # other flag, and `LayerSpec` takes only a real boolean.
                visible=bool(visible),
                band=band,
            )
        )

    def _describe_layer(self, record: LayerRecord) -> str:
        """Record one layer in the figure and return the id it was given.

        The single registration funnel: every builder in this tier ends here, whether or not it also had a
        mappable to register in :attr:`layers`. Routing them all through one place is what keeps the kind a
        layer is recorded under an engine-neutral noun rather than whichever cleopatra glyph happened to draw
        it.

        The caller's engine keywords go **both** ways, which is deliberate. The plain ones are written into
        the layer's description (see :func:`~digitalearth.base.spec._serial.travels_in_a_figure`), so a figure
        read back elsewhere draws the ``vmin``, ``alpha``, ``color`` or ``title`` the caller asked for
        instead of the engine's defaults.
        All of them — plain or not — stay held on the scene as the very objects passed, and
        :func:`drawing_style` lets those win, so a layer on the scene that built it is drawn with exactly
        what it always was rather than with a frozen copy.

        Args:
            record: What the builder drew, as :class:`LayerRecord` describes it.

        Returns:
            The layer's id, which a caller-supplied name becomes when it is free.

        Raises:
            Exception: whatever recording the layer raises — `LayerSpec` validation, `DataRef.of`,
                `LayerTree.add` — after the id and everything filed under it have been given back again.
                The mint sat outside every ``try`` in this tier, so a description that refused left the id
                reserved on a scene that draws no such layer, and the next call under the same name was
                suffixed past it; the interactive tier already rolled its own back (review R2-M11). Rolling
                back here rather than in :meth:`_draw` covers the builders that describe without drawing —
                ``graticule`` is one — which a ``try`` in :meth:`_draw` would not reach.
        """
        # Before the mint, because a refused layer must leave no id reserved behind it.
        self._require_one_placement(record)
        # A generated id counts the kind, so `custom:matplotlib` numbers `custom-1`: a colon cannot appear in
        # the middle of an id, and the engine name is not what a reader is counting anyway.
        layer_id = self._layer_id(record.kind.split(":")[0], record.name)
        try:
            self._record_layer(layer_id, record)
        except BaseException:
            self._forget_layer(layer_id)
            raise
        placement = placement_of(record)
        if placement is not None:
            self._layer_placements[layer_id] = placement
        return layer_id

    def _require_one_placement(self, record: LayerRecord) -> None:
        """Refuse a layer whose coordinates are not placed the way this figure's already are.

        One axes has one pair of data coordinates, and this tier has two ways of filling them: a layer is
        placed :data:`IN_DISPLAY_CRS`, or — for a bare numpy array, which carries no CRS and no geo-transform
        — :data:`AT_INDICES`. Mixed on one figure, matplotlib autoscales to hold both: a ``3 x 4`` array beside
        a coastline becomes a speck a millimetre wide off the coast of Africa, and the figure reads as if it
        had drawn the coastline and lost the array. Neither layer raised, so nothing said which had gone
        wrong (#343).

        A ``custom:matplotlib`` layer is neither refused nor counted: the caller drew it in their own
        coordinates, and only they know which those are (see :func:`placement_of`).

        Args:
            record: The layer about to be described.

        Raises:
            ValueError: naming the layers already on the figure and what to do instead. The alternative is
                real rather than rhetorical: an array wrapped in a pyramids ``Dataset`` carries a
                geo-transform, and then it is placed like everything else.
        """
        placement = placement_of(record)
        if placement is None:
            return
        clashing = sorted(
            layer_id
            for layer_id, held in self._layer_placements.items()
            if held != placement
        )
        if not clashing:
            return
        other = IN_DISPLAY_CRS if placement == AT_INDICES else AT_INDICES
        raise ValueError(
            f"a {record.kind!r} layer placed {placement} cannot join a figure whose layers are placed "
            f"{other} ({', '.join(clashing)}): one axes has one pair of data coordinates, and a bare numpy "
            "array has no CRS and no geo-transform to be placed by. Draw the array on a Map of its own, or "
            "wrap it in a pyramids Dataset to give it a place"
        )

    def _record_layer(self, layer_id: str, record: LayerRecord) -> None:
        """File one layer's description, data, key and keywords under an id already minted for it.

        Split out of :meth:`_describe_layer` so the mint sits outside the body that can raise and the
        rollback can be written once (review R2-M11).

        Args:
            layer_id: The id :meth:`_layer_id` handed out for this layer.
            record: What the builder drew, as :class:`LayerRecord` describes it.
        """
        if record.key is not None:
            self._layer_keys[layer_id] = record.key
        if record.held is not None:
            self._held_objects[layer_id] = record.held
        if record.opts:
            # A shallow copy: the dict is this layer's, so a caller reusing theirs cannot re-style it later,
            # while each value stays the very object they passed.
            self._layer_opts[layer_id] = dict(record.opts)
        self._index_layer(
            layer_id,
            record.name,
            kind=record.kind,
            visible=record.visible,
            band=record.band,
            source=record.source,
            symbology=_with_described_opts(record.symbology, record.opts),
        )

    def _draw(self, record: LayerRecord) -> Any:
        """Record a layer and draw it, returning whatever its drawer handed back.

        The funnel every builder of a drawn kind ends at. The order is the point: the layer is **described
        first** and its drawer builds the artists from that description, so the two can never disagree about
        what the figure holds. A builder that computed the artists itself and described them afterwards was
        writing the same layer twice, in two vocabularies, with nothing holding them to each other.

        Args:
            record: What the builder wants drawn, as :class:`LayerRecord` describes it.

        Returns:
            The drawer's ``artist`` — the mappable a field render produced, the ``Text`` of a label, the
            polylines a limb-split coastline became — or ``None`` when the drawer declined the layer, which
            is what an off-limb raster or a far-side label is.

        Raises:
            Exception: whatever the drawer raises, after the layer has been dropped from the description
                again — a figure must not name a layer that was not drawn, and that is as true of a refusal
                as it is of a skip.
        """
        layer_id = self._describe_layer(record)
        try:
            drawn = self._renderer.draw_layer(self.figure_spec, layer_id)
        except BaseException:
            self._forget_layer(layer_id)
            raise
        if drawn is None:
            self._forget_layer(layer_id)
            return None
        self._record_class_edges(drawn)
        self._publish_color(layer_id, drawn)
        return drawn.artist

    def _publish_color(self, layer_id: str, drawn: DrawnLayer) -> None:
        """Record what varies a drawn layer's colour, so a key can be asked for on it.

        The description's half of what :meth:`_record_class_edges` publishes on :attr:`last_breaks`, and read
        the same way — off the artist that was drawn (see
        :func:`~digitalearth.static.legends.legend.color_encoding`). Without it no layer on this tier published a
        colour :class:`~digitalearth.base.spec.encoding.Encoding` at all, and a
        :class:`~digitalearth.base.spec.encoding.Guide` has nothing to hang on: `Encoding.__post_init__`
        takes exactly one of a constant or a field, so an unbound colour is no binding at all (#261, order
        24).

        Done here rather than in the builder because the builder never opens the source: it records a band
        **number**, and the band's name — and the limits the render settled on — exist only once the glyph
        has drawn. Done here rather than in the renderer because
        :meth:`~digitalearth.static.render.renderer.Renderer.apply` deliberately does not touch the description, so
        a layer drawn again keeps the encoding it published the first time.

        Args:
            layer_id: The layer that has just been drawn.
            drawn: What its drawer produced.
        """
        layer = self._layer_tree.get(layer_id)
        # The drawer answers for a raster, whose band name it alone resolved; every other layer's colour
        # field is the `column` its own description already names. A layer with neither — points sized by a
        # column, an outline-only fill, a graticule — names nothing and publishes nothing.
        column = layer.symbology.props.get("column")
        field = drawn.color_field or (column if isinstance(column, str) else None)
        encoding = color_encoding(field, drawn)
        if encoding is None:
            return
        symbology = with_fields(
            layer.symbology,
            encodings={**dict(layer.symbology.encodings), "color": encoding},
        )
        self._layer_tree = self._layer_tree.replace(
            with_fields(layer, symbology=symbology)
        )

    def _record_class_edges(self, drawn: Any) -> None:
        """Publish the class edges of a layer that colours by value, on :attr:`last_breaks`.

        Read off the artist rather than recomputed beside it: cleopatra does the classifying, and the
        ``BoundaryNorm`` it leaves on the mappable is what matplotlib actually colours through — so a record
        taken from anywhere else could disagree with the picture, which is the failure mode this tier has had
        before. Done here, in the one funnel every drawn layer passes through, because ``scheme=`` is a
        declared parameter of :meth:`~digitalearth.static.builders.vector.VectorMixin.choropleth` and travels in
        ``**opts`` on every other classifying builder; a record written into one of them would have left the
        rest silent.

        Args:
            drawn: What the drawer handed back, as ``DrawnLayer`` describes it.
        """
        norm = getattr(drawn.artist, "norm", None)
        if norm is None:
            # Nothing on this layer maps a value to a colour — a graticule, a label, a coastline — so it has
            # no opinion about class edges and must not clear the layer that had one.
            return
        edges = getattr(norm, "boundaries", None)
        stated = getattr(drawn, "scale", None)
        categorical = getattr(drawn.glyph, "category_legend", None) is not None or (
            stated is not None and stated.is_categorical
        )
        if edges is None or categorical:
            # A continuous ramp cut nothing; a categorical fill's norm bins the codes cleopatra assigned, and a
            # categorical raster's brackets its codes, not the caller's categories — so neither has class edges
            # to publish (see :attr:`last_breaks`).
            self.last_breaks = None
            return
        self.last_breaks = [float(edge) for edge in edges]

    def _forget_layer(self, layer_id: str) -> None:
        """Drop a layer from the description, and with it whatever it registered.

        What :meth:`_draw` calls for a layer its drawer declined or refused. The id goes back to the pool
        of free names too, so a caller who names a layer, watches it skip, and names it again gets the name
        they asked for rather than a suffixed one.

        Args:
            layer_id: The layer to forget. One already gone is ignored — as this docstring already promised
                and the unguarded `LayerTree.remove` below did not, since that call raises `KeyError` for an
                id it does not hold (review R2-L11). Named by what it is rather than by a line number: the
                number this sentence carried was already pointing at a docstring's closing quotes by the
                time the same wave split :meth:`_record_layer` out (`R2-N2`). That matters now rather than
                later: :meth:`_describe_layer` rolls back a
                description that refused, and the refusal may have come from `LayerTree.add` itself — so the
                rollback would have raised over the very exception it was unwinding.
        """
        if layer_id in self._layer_tree:
            self._layer_tree = self._layer_tree.remove(layer_id)
        self._issued_ids.discard(layer_id)
        self._forget_layer_data(layer_id)

    def _forget_layer_data(self, layer_id: str) -> None:
        """Let go of the in-memory data, the drawer key and the engine keywords one layer held.

        The object table is process-global and holds strong references, so a layer that is removed and
        never forgotten keeps its dataset alive for the life of the process.

        Args:
            layer_id: The layer whose source, key and keywords are dropped. A layer that registered none of
                them — a graticule, a text label — is ignored.
        """
        ref = self._sources.pop(layer_id, None)
        if ref is not None:
            forget_object(ref.uri)
        self._layer_keys.pop(layer_id, None)
        self._layer_opts.pop(layer_id, None)
        self._held_objects.pop(layer_id, None)
        # With the layer goes its claim on the figure's coordinates: taking the one array layer off frees the
        # figure to hold georeferenced ones again, and a layer whose drawer declined it never held the claim.
        self._layer_placements.pop(layer_id, None)

    @property
    def layer_ids(self) -> list[str]:
        """The ids of the layers this scene draws, in draw order, bottom first.

        Returns:
            One id per described layer. A layer the caller named carries that name, with surrounding
            whitespace removed; an unnamed one gets a generated id counting the layers of its kind —
            ``scatter, text, scatter, text`` is ``points-1, points-2, text-1, text-2``, listed in draw
            order. It counted the *figure* until review R2-M10, while this sentence already said otherwise
            (review R2-L2).
        """
        return list(self._layer_tree.ids)

    @property
    def figure_spec(self) -> FigureSpec:
        """What the scene draws, as data: its layers, their sources and the view.

        Returns:
            A :class:`~digitalearth.base.spec.FigureSpec` with one panel, :data:`PANEL_ID`, whose layers are
            the tree in draw order and whose sources are what each builder was given.

            It carries the plain half of the caller's styling and no more: a keyword passed through
            ``**opts`` is described when :func:`~digitalearth.base.spec._serial.travels_in_a_figure` accepts
            it, and held beside the layer
            (:attr:`LayerRecord.opts`) when it does not — so a figure drawn on another scene draws the
            described ``vmin``, ``alpha``, ``color`` or ``title``, and the engine's defaults in place of a
            dash tuple, a per-pixel array or a ``Normalize``.

            A scene built from data already in memory can be handed straight to a renderer, but not written:
            ``to_dict()`` refuses an ``object:`` source, because a reference into this process's memory would
            be unreadable everywhere else. Give a builder a path or a URL to get a figure that can be stored.
        """
        return self._figure_with(self._layer_tree)

    def _figure_with(self, tree: LayerTree) -> FigureSpec:
        """Return the figure this scene would report if its layers were `tree`.

        The panel is **derived** rather than maintained beside the tree: this tier draws one axes, so its one
        panel shows every layer, and a figure whose panel named a layer the tree does not hold is refused by
        `FigureSpec` — correctly. Writing that derivation once is what lets :meth:`_change` take a tree and
        keep the panel — and the panel's title, which rides on it (:meth:`set_title`) — in step with it.

        The **figure's** heading is read off the figure itself rather than remembered, because this tier's
        figure is not always this scene's alone: :func:`~digitalearth.static.panels.figure.grid` titles a figure
        several panels share, and tells a caller who wants to style that heading to call ``fig.suptitle``
        on the returned figure. One derivation covers both, and covers a scene whose figure was handed in
        (``Map(fig=...)``). It is normalised by the same :meth:`_recorded_title` the panel's title goes
        through, so matplotlib's empty ``''`` is the ``None`` `FigureSpec` spells "no title" as.

        Args:
            tree: The layers the figure describes.

        Returns:
            The figure, with the sources of exactly those layers, the panel's title (:meth:`set_title`) and
            the figure's heading (``Figure.suptitle``) — the two places a heading can live, described
            separately because they are **restored** separately:
            :meth:`~digitalearth.static.map.Map.draw_figure` puts the panel's title back on the axes and the
            figure's heading back as the `suptitle`, each into the slot it was described from, so neither
            stands in for the other. Measured on a map titled `January` under the heading
            `rainfall, 2020`: described as `('rainfall, 2020', 'January')` for
            `(figure.title, figure.panels[0].title)`, drawn into a fresh map it restores the same pair as
            `(fig.get_suptitle(), ax.get_title())` and redescribes unchanged, with `to_dict()` equal across
            two further passes. Each is written **only when the incoming figure carries it**, so drawing an
            untitled figure does not blank a heading the map already has.
        """
        panel = PanelSpec(
            PANEL_ID, self.viewport, layers=tuple(tree.ids), title=self._title
        )
        return FigureSpec(
            panels=(panel,),
            layers=tree,
            sources={
                key: ref for key, ref in self._sources.items() if key in set(tree.ids)
            },
            title=self._recorded_title(self.fig.get_suptitle()),
        )

    def _change(self, figure: FigureSpec) -> None:
        """Move the scene to another figure, drawing the difference onto the axes first.

        The one path every layer-management method goes through, and the 3-D scene's `_change` in this
        tier's terms. The order is the point: the renderer draws the difference, and the description is
        installed **only if** it did. A figure that cannot be drawn — a kind this tier has no drawer for, a
        layer whose data will not load — was installed first on the 3-D tier and left in place when `apply`
        raised, so `layer_ids`, `figure_spec` and `to_dict` all advertised a layer that was never drawn and
        could not be (review H7).

        There is no rollback written here, and that is deliberate: :meth:`~digitalearth.static.render.renderer.Renderer.apply`
        is atomic on this tier. It snapshots what the axes, this record and the colorbar registry held, and
        puts all three back before it re-raises — so by the time a refusal reaches this method the axes is
        already as it was, and the only thing left to do is not install the description. The 3-D scene
        re-applies the figure in reverse instead, because its renderer's `apply` has no rollback of its own.

        Args:
            figure: The figure the scene should show. Its panel is ignored — :meth:`_figure_with` derives
                one from the tree — so a caller may hand in a tree wrapped by either.

        Raises:
            KeyError: when a layer names a kind this tier does not draw, or a recipe it does not know.
            ValueError: when a layer's description does not carry what its drawer needs.
            OffLimbError: when a layer's data cannot be placed and the scene is ``strict``.
        """
        candidate = self._figure_with(figure.layers)
        self._renderer.apply(self.figure_spec, candidate)
        self._layer_tree = candidate.layers
        # An axes holds one swatch legend, so a figure that arrives claiming two is installed claiming one.
        # Here rather than in `apply`, which draws the picture and does not write descriptions — this is the
        # rebuild reaching the same half of the rule `_record_key` reaches on the calling path (review M4).
        self._settle_swatch_keys()
        # The reference goes out of this scene's figure; the object stays registered, because a
        # `figure_spec` captured before the change still names it and `close()` is where a scene lets its
        # data go — the policy `Renderer.apply` states and the web tier settled on too.
        held = set(candidate.layers.ids)
        self._sources = {key: ref for key, ref in self._sources.items() if key in held}

    def get_layer(self, layer_id: str) -> LayerSpec:
        """Return the description of one layer, by id.

        Args:
            layer_id: The layer to look up.

        Returns:
            Its :class:`~digitalearth.base.spec.LayerSpec` — kind, source, symbology, band and visibility.

        Raises:
            KeyError: if no layer has that id, naming the ids that do.

        Examples:
            - What a builder recorded, read back by id:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
                >>> m.get_layer("ams").kind
                'text'
                >>> m.close()

                ```
        """
        self._require_layer(layer_id)
        return self._layer_tree.get(layer_id)

    def artist(self, layer_id: str | None = None) -> Any:
        """Return what one layer's drawer handed back — for most kinds, the matplotlib artist it drew.

        The companion to the builders returning `Self` (ST-20): they hand back the map so a figure reads
        as one expression, and this is how the engine's object is reached when a caller genuinely wants it
        — to read a drawn colormap, a norm, the cells' paths, the limits a render settled on. It was the
        builders' return value until then, which made every chained call impossible; the artist was
        reachable only as `scene._renderer.drawn[layer_id].artist`, a private attribute this tier's own
        docstrings had taken to pointing callers at.

        Args:
            layer_id: Which layer's artist. `None` (the default) takes the layer **drawn last**, which is
                the one the call before this drew — so `m.field(ds); m.artist()` is the old return value,
                with no name needed.

        Returns:
            Whatever that layer's drawer produced, which is exactly what its builder used to return: the
            mappable of a field render, the `PolyCollection` of a fill, the `LineCollection` of a line
            layer, the **list** of `Annotation` of a
            :meth:`~digitalearth.static.builders.vector.VectorMixin.labels` layer.

            So it is not always a matplotlib artist, because not every drawer produces one object on the
            axes. A **graticule** is the case to know: its drawer's value is the list of projected
            polylines (18 of them at the default spacing), while what it put on the axes is one
            `LineCollection` plus one `Text` per **labelled gridline** — 19 artists in all at that
            spacing, and just the `LineCollection` when the layer was drawn `labels=False`. The two
            counts track the gridlines rather than the degrees between them: at `spacing=60.0` the
            drawer hands back 9 polylines and the axes holds 11 artists.

            Those counts are the **flat** map's. On a **globe** the same drawer's value is the same list
            of 18 polylines, but the grid is painted by `apply_projection_frame` as 18 `Line2D` — no
            `LineCollection` and no `Text` — and it is painted at :meth:`render`, so before that call the
            layer is described, `artist()` already hands back its 18 arrays, and the axes holds none of
            its artists yet. So read the drawer's value as the drawer's value: what the axes holds is a
            per-projection, per-render answer, not a property of the layer.

            A layer like that — a graticule, a limb-split coastline — owns a whole set of artists, and
            that set is the renderer's own record (`DrawnLayer.artists`), which is what
            :meth:`set_visible` and :meth:`remove_layer` act on rather than part of this tier's public
            surface. **There is no public accessor for it**, and that is a gap rather than a nicety: the
            examples below count the axes' own lists (``ax.lines``, ``ax.collections``, ``ax.texts``)
            instead, which is only the layer's set on a figure carrying one layer. A caller who needs to
            act on the set should go through :meth:`set_visible` / :meth:`remove_layer`; one who needs to
            *read* it has nowhere public to go, and reaching into `_renderer.drawn` is not a supported
            route (R2-L8).

        Raises:
            KeyError: when `layer_id` names no layer on this figure, naming the ids that do. The test is
                whether the **description** holds the id, not whether anything of the layer is on the
                axes: a layer whose data the display CRS could not place is dropped from the description
                outright, so it is refused here too — the same answer its builder's `None` used to give,
                in the tier's own words. A layer that is described but has **no artists yet** is *not*
                refused; it hands its drawer's value back as usual, which is what a globe's graticule does
                before :meth:`render` has painted it.
            ValueError: when `layer_id` is `None` and nothing has been drawn yet: there is no "last" for
                an empty figure, and `None` would read as "that layer drew nothing".

        Examples:
            - The old return value, by one more call:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> m.field(np.arange(12.0).reshape(3, 4)).artist().get_extent()
                [-0.5, 3.5, -0.5, 2.5]
                >>> m.close()

                ```
            - By id, which is what a figure of several layers wants, and an unknown id is refused by name:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> _ = m.field(np.arange(12.0).reshape(3, 4), name="grid", cmap="magma")
                >>> m.artist("grid").get_cmap().name, m.artist("grid").get_clim()
                ('magma', (0.0, 11.0))
                >>> m.artist("nope")
                Traceback (most recent call last):
                    ...
                KeyError: "no layer 'nope' on this figure; its layers are ['grid']"
                >>> m.close()

                ```
            - A graticule's drawer hands back its projected lines rather than one artist. What the axes
              holds is counted off the **axes** — ``ax.collections`` and ``ax.texts``, which on a figure
              carrying this one layer are exactly its artists: one ``LineCollection`` for the lines plus
              one ``Text`` per labelled gridline, 19 against the drawer's 18 polylines:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map(crs=4326)
                >>> _ = m.graticule(spacing=30.0)
                >>> len(m.artist("graticule-1")), len(m.ax.collections) + len(m.ax.texts)
                (18, 19)
                >>> m.close()
                >>> coarse = Map(crs=4326)
                >>> _ = coarse.graticule(spacing=60.0)
                >>> len(coarse.artist("graticule-1")), len(coarse.ax.collections) + len(coarse.ax.texts)
                (9, 11)
                >>> coarse.close()

                ```
            - On a globe the drawer's value is unchanged while the axes holds nothing until
              :meth:`render` paints the grid as `Line2D` — so a described layer with no artists yet is
              answered, not refused. ``ax.lines`` is the count to watch here, because that is what the
              projection frame paints the grid as:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> globe = Map(crs=4326, globe=True)
                >>> _ = globe.graticule(spacing=30.0)
                >>> len(globe.artist("graticule-1")), len(globe.ax.lines)
                (18, 0)
                >>> globe.render()
                >>> len(globe.artist("graticule-1")), len(globe.ax.lines)
                (18, 18)
                >>> sorted({type(artist).__name__ for artist in globe.ax.lines})
                ['Line2D']
                >>> globe.close()

                ```
            - A figure with nothing drawn has no "last" to hand back:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> bare = Map(globe=False)
                >>> bare.artist()  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: Map.artist() has nothing to hand back: no layer has been drawn...
                >>> bare.close()

                ```
        """
        if layer_id is None:
            drawn = self._renderer.drawn
            if not drawn:
                raise ValueError(
                    f"{type(self).__name__}.artist() has nothing to hand back: no layer has been drawn on "
                    "this figure yet. Draw one first, or name the layer you mean"
                )
            return list(drawn.values())[-1].artist
        self._require_layer(layer_id)
        return self._renderer.drawn[layer_id].artist

    def add_layer(
        self,
        layer: Any,
        *,
        name: str | None = None,
        band: str | None = None,
        color_field: str | None = None,
    ) -> Self:
        """Register an artist **you built yourself** as a layer, and return this scene (chainable).

        The Core spelling of what :meth:`_add_layer` has always done, and the point of having it in public:
        an artist added this way is addressable like any other layer — :attr:`layer_ids` lists it,
        :meth:`get_layer` describes it, :meth:`set_visible` hides it and :meth:`remove_layer` takes it off.
        What the figure keeps is the *description* (id, kind `custom:matplotlib`, label, band, visibility);
        the artist itself is held by this scene, because a matplotlib artist has no description to write, so
        a figure read back elsewhere names the layer and cannot rebuild it
        (:mod:`digitalearth.base.custom`).

        Drawing straight onto :attr:`ax` is still the escape hatch, and is still invisible to the figure.

        Args:
            layer: The matplotlib artist you drew. Whether it is **visible** is read off the object, as the
                web tier reads it off a MapLibre layer: an artist built with ``visible=False`` is described
                hidden rather than described as something the figure does not draw (review L10).
            name: The id to address it by; ``None`` generates ``custom-1``, ``custom-2``, …. A name already
                on the figure is suffixed, as every builder's ``name=`` is.
            band: Where it is drawn — ``"underlay"``, ``"reference"``, ``"data"`` or ``"overlay"``. ``None``
                takes the kind's own band, which is ``data``. A caller's artist can draw anything, so only
                the caller can say whether it is ground cover or a label.
            color_field: The name of the value the artist's colour encodes. A hand-built artist publishes no
                colour encoding of its own, so without this the layer has no colour key and
                :meth:`colorbar`/:meth:`legend` refuse it — the one case the builders cover and the escape
                hatch did not (#349). Naming it publishes ``Encoding.by_field("color", color_field)`` for the
                layer, which is all a key needs; the bar reads its range off the artist. ``None`` (default)
                leaves the layer keyless, as before.

        Returns:
            This scene, so calls chain.

        Raises:
            ValueError: if `band` is not one of the four bands, or if `color_field` is given empty.
            TypeError: if `name` is neither a string nor ``None``.

        Examples:
            - An artist of your own, addressable afterwards:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from matplotlib.text import Text
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.add_layer(m.ax.add_artist(Text(0.0, 0.0, "mine")), name="mine")
                >>> m.get_layer("mine").kind
                'custom:matplotlib'
                >>> m.close()

                ```
        """
        if band is not None and band not in KIND_BANDS:
            raise ValueError(
                f"add_layer band must be one of {list(KIND_BANDS)}; got {band!r}"
            )
        self._add_layer(
            None,
            layer,
            name=name,
            band=band,
            visible=artist_is_visible(layer),
            color_field=color_field,
        )
        return self

    def remove_layer(self, layer_id: str) -> Self:
        """Take a layer off the figure, by id.

        Args:
            layer_id: The layer to remove.

        Returns:
            This scene (chainable).

        Raises:
            KeyError: if no layer has that id, naming the ids that do — a silent no-op here would look
                exactly like a layer that refused to go away.

        Note:
            The **id** goes back to the pool, so a name removed and asked for again is handed back
            unsuffixed: an id is reserved exactly while the layer is on the figure, which is the lifetime
            all four tiers share (:func:`~digitalearth.base.spec.layer.free_layer_id`).

            The in-memory **data** is not forgotten. A `figure_spec` captured before the removal still names
            it, and drawing that figure again needs it; :meth:`close` is where this scene lets its data go.

        Examples:
            - A layer added and then removed leaves nothing behind:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
                >>> m.remove_layer("ams").layer_ids
                []
                >>> m.close()

                ```
        """
        self._require_layer(layer_id)
        self._change(self._figure_with(self._layer_tree.remove(layer_id)))
        # After the change, not before: the drawer reads the key, the keywords and the caller's own artist
        # out of these, so dropping them first would leave the rollback inside `apply` unable to draw the
        # layer it has just taken off.
        self._layer_keys.pop(layer_id, None)
        self._layer_opts.pop(layer_id, None)
        self._held_objects.pop(layer_id, None)
        self._issued_ids.discard(layer_id)
        # The claim on the figure's coordinates goes with the layer that made it, so taking the one
        # index-placed layer off lets a georeferenced one take the axes (see `_require_one_placement`).
        self._layer_placements.pop(layer_id, None)
        return self

    def set_visible(self, layer_id: str, visible: bool = True) -> Self:
        """Show or hide a layer, by id.

        The layer stays on the figure and in its description — which is what lets it be switched back on,
        and what tells a saved figure that the layer is there but not drawn.

        Args:
            layer_id: The layer to toggle.
            visible: Whether it is drawn.

        Returns:
            This scene (chainable).

        Raises:
            KeyError: if no layer has that id, naming the ids that do.

        Examples:
            - A hidden layer is still described, and comes back on:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
                >>> m.set_visible("ams", False).figure_spec.layers.is_visible("ams")
                False
                >>> m._renderer.is_visible("ams")
                False
                >>> m.set_visible("ams")._renderer.is_visible("ams")
                True
                >>> m.close()

                ```
        """
        self._require_layer(layer_id)
        self._change(
            self._figure_with(self._layer_tree.set_visible(layer_id, bool(visible)))
        )
        return self

    def move_layer(self, layer_id: str, index: int) -> Self:
        """Move a layer in draw order, by id.

        Args:
            layer_id: The layer to move.
            index: Its position afterwards, counted as a list index is — ``0`` is the bottom, ``-1`` the
                top. A layer moves within its band: reordering the data layers is what a layer switcher
                does, and dragging the basemap over them is not.

        Returns:
            This scene (chainable).

        Raises:
            KeyError: if no layer has that id.
            IndexError: if the position is outside the figure, or outside the layer's band.

        Note:
            This reaches the picture and not only the description. matplotlib paints the artists of one
            z-order in the order they were added, so the renderer re-arranges the layers it holds
            (:meth:`~digitalearth.static.render.renderer.Renderer._repaint`) — and because that stops at a z-order
            boundary, it also deals the layers' own z-orders back out along the new order
            (:func:`~digitalearth.static.render.renderer._rank_zorders`), which is what moves a point layer under a
            raster rather than only saying so. The layers keep the z-orders they held between them, so the
            move stays inside their slice of the stack and nothing outside it shifts; a ``zorder=`` a caller
            gave one of the moved layers is superseded, the move being the later word on where it is painted.

        Examples:
            - Two labels, reordered by id:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
                >>> _ = m.text(2.35, 48.86, "Paris", name="par")
                >>> m.move_layer("par", 0).layer_ids
                ['par', 'ams']
                >>> m.close()

                ```
        """
        # Asked here rather than left to `LayerTree.move`, so an unknown id is refused in the same words as
        # every other layer-management call on this tier: the tree names itself, the facade names the figure.
        self._require_layer(layer_id)
        self._change(self._figure_with(self._layer_tree.move(layer_id, index)))
        return self

    def replace_layer(self, layer: LayerSpec) -> Self:
        """Swap a layer's description for another, keeping its id and its place in draw order.

        This is how a layer is restyled or re-pointed after it has been drawn: a cleopatra glyph bakes its
        colormap and its class breaks into the artist it built, so the renderer draws the layer again from
        the new description rather than setting a property on what is there.

        Args:
            layer: The new description. Its id names the layer it replaces.

        Returns:
            This scene (chainable).

        Raises:
            CapabilityError: if the replacement names a kind this tier does not draw, naming the kind and the
                backend that has no drawer for it. Raised off the declaration, before a description is built
                or the axes is touched. It subclasses ``ValueError``, so a caller catching that catches this.
            KeyError: if no layer has that id, naming the ids that do.
            ValueError: if `layer` is not a `LayerSpec`, or if it draws from data and names no `source_id`:
                the drawers read the source out of the figure, and a missing one reaches the drawer as
                ``None`` and fails somewhere it cannot explain.

        Examples:
            - A label re-described keeps its id and its place:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from dataclasses import replace
                >>> from digitalearth.static import Map
                >>> m = Map()
                >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
                >>> held = m.get_layer("ams")
                >>> _ = m.replace_layer(replace(held, label="Capital"))
                >>> m.get_layer("ams").label
                'Capital'
                >>> m.close()

                ```
        """
        # By type before by id: `getattr(layer, "id", None)` made the id lookup fail first, so a caller who
        # passed the id where the description belongs was answered "no layer None on this figure" — an id
        # they never wrote, about an argument that was not a description at all (review L1).
        if not isinstance(layer, LayerSpec):
            raise ValueError(
                f"{type(self).__name__}.replace_layer needs a LayerSpec — the new description, not an id; "
                f"got {type(layer).__name__}"
            )
        self._require_layer(layer.id)
        # The first production caller of `Capabilities.require` (D-10). A replacement is the one
        # layer-management call that can name a **new kind**, so it is the one that can ask this tier for
        # something it does not have — and refusing here, off the declaration, refuses before a description
        # is built or the engine is touched. Without it the refusal came from the drawer table, part-way
        # through a reconcile, and said nothing about what the tier declares.
        CAPABILITIES.require(layer.kind, caller="Map.replace_layer")
        if layer.source_id is None and kind_info(layer.kind).takes != "none":
            raise ValueError(
                f"layer {layer.id!r} is a {layer.kind!r} layer, which draws from data, so its replacement "
                f"needs a source_id; got None"
            )
        self._change(self._figure_with(self._layer_tree.replace(layer)))
        return self

    def _require_layer(self, layer_id: Any) -> None:
        """Refuse an id this scene does not draw, naming the ids it does.

        Written once because five public methods ask the same question, and a refusal that named neither the
        id nor the alternatives is the one a caller cannot act on.

        Args:
            layer_id: The id the caller passed.

        Raises:
            KeyError: when no layer has that id.
        """
        if layer_id not in self._layer_tree:
            raise KeyError(
                f"no layer {layer_id!r} on this figure; its layers are {self.layer_ids}"
            )

    @property
    def viewport(self) -> Viewport:
        """Where the scene is looking, as a value.

        A bare :class:`Scene` is a figure host rather than a map — it has no display CRS to place anything in
        — so the view is the default one. :class:`~digitalearth.static.builders.base.GeoLayerBase` overrides this
        with the CRS, domain and globe flag it was built with.

        Returns:
            A :class:`~digitalearth.base.spec.Viewport`.
        """
        return Viewport()

    def _register_artist(
        self, glyph: Any, mappable: Any, label: str | None = None
    ) -> Any:
        """Register a rendered glyph and its mappable so a colorbar or legend can be keyed to it.

        The drawing half of what :meth:`_add_layer` used to do in one step. A drawer calls this; the
        description was already written by :meth:`_draw` before the drawer ran, which is what keeps the two
        structures from disagreeing.

        Args:
            glyph: The cleopatra glyph instance that was drawn on :attr:`ax`, or ``None`` for an artist
                added to the axes directly (a globe's land fill, an artist the caller built).
            mappable: The matplotlib mappable/artist the glyph produced (e.g. ``glyph.im``).
            label: Optional default colorbar label for this layer (e.g. the units resolved by
                :func:`~digitalearth.base.autostyle.auto_style`); used only when :meth:`colorbar` is
                called without one.

        Returns:
            The ``mappable`` (so callers can chain or attach a colorbar).
        """
        self.layers.append((glyph, mappable))
        self._layer_labels.append(label)
        return mappable

    def _unregister_artist(self, drawn: DrawnLayer) -> None:
        """Drop a removed layer's ``(glyph, mappable)`` pair and its default label.

        Matched by identity rather than by position: :attr:`layers` holds only the layers that registered a
        mappable, so a layer's index there is not its index in the description and cannot be derived from
        one.

        Args:
            drawn: What the renderer recorded for the layer being removed. One that registered no mappable
                — a graticule, a basemap, a text label — is not in :attr:`layers` and is left alone.
        """
        index = self._registered_index(drawn)
        if index is not None:
            del self.layers[index]
            del self._layer_labels[index]

    def _registered_index(self, drawn: DrawnLayer | None) -> int | None:
        """Return where one drawn layer's ``(glyph, mappable)`` pair sits in :attr:`layers`.

        Matched by identity rather than by position: :attr:`layers` holds only the layers that registered a
        mappable, so a layer's index there is not its index in the description and cannot be derived from
        one. Written once because two readers ask it — :meth:`_unregister_artist`, which deletes the entry,
        and :meth:`_default_label`, which reads the units filed beside it.

        Args:
            drawn: What the renderer recorded for the layer, or ``None`` for one nothing was drawn for.

        Returns:
            The index, or ``None`` for a layer that registered no mappable — a graticule, a basemap, a text
            label. A pair of ``None``\\ s is never matched: it would find whichever layer happened to be
            first.
        """
        if drawn is None or drawn.artist is None:
            return None
        for index, (glyph, mappable) in enumerate(self.layers):
            if glyph is drawn.glyph and mappable is drawn.artist:
                return index
        return None

    def _add_layer(
        self,
        glyph: Any,
        mappable: Any,
        label: str | None = None,
        *,
        name: str | None = None,
        band: str | None = None,
        visible: bool = True,
        color_field: str | None = None,
    ) -> Any:
        """Register an artist the caller built themselves, and describe it as a custom layer.

        Not the builders' path: an artist somebody built by hand has no source to reference and no
        symbology to read back, so it is recorded as ``custom:matplotlib`` and described by id, kind and
        label alone. A figure can name it, hide it, reorder it and take it off — but never *rebuild* it,
        which is what :mod:`digitalearth.base.custom` says a reader of such a layer is looking at. So the
        artist itself is held on the scene under the layer's id, and the tier's own custom drawer puts it
        back from there; a figure read back somewhere else describes the layer and skips it.

        Drawing straight onto :attr:`ax` is still the escape hatch, and still invisible to the figure.

        Args:
            glyph: The cleopatra glyph instance that was drawn on :attr:`ax`, or ``None``.
            mappable: The matplotlib mappable/artist to register.
            label: Optional default colorbar label for this layer.
            name: The caller's own name for the layer, used as its id; ``None`` (default) generates
                ``custom-1``, ``custom-2``, … A name already on the figure is suffixed ``-2``, ``-3``, …
                (#321).
            band: Where the layer is drawn — one of :data:`~digitalearth.base.registry.KIND_BANDS`.
                ``None`` takes the kind's own band, which is ``data``. The kind names the *engine* and says
                nothing about what the artist draws, so a backdrop or a label can only say so here.
            visible: Whether the layer is drawn. ``False`` registers it hidden **and** describes it
                hidden (#327).
            color_field: The name of the value the layer's colour encodes, or ``None``. When given, the
                layer is described with ``Encoding.by_field("color", color_field)``, so the otherwise keyless
                custom layer carries a colour key for :meth:`colorbar`/:meth:`legend` (#349).

        Returns:
            The ``mappable`` (so callers can chain or attach a colorbar).
        """
        encodings = (
            {"color": Encoding.by_field("color", color_field)}
            if color_field is not None
            else {}
        )
        symbology = Symbology(props={"via": "custom"}, encodings=encodings)
        return self._draw(
            LayerRecord(
                custom_kind(ENGINE),
                name=name,
                band=band,
                visible=visible,
                symbology=symbology,
                held=(glyph, mappable, label),
            )
        )

    def _reset_layers(self) -> None:
        """Forget every registered layer — its default label and its description — e.g. between frames.

        The description is reset with the drawing, because an animation redraws every layer on a cleared
        axes: leaving the tree alone would have frame 50 describe 50 copies of one raster. The id counter
        goes back with it, so each frame mints the same ids and the in-memory source each one registered is
        replaced rather than accumulated. Whatever the dropped layers referenced is forgotten too, so a long
        run does not hold every frame's dataset alive through the process-wide object table.
        """
        # Every source goes and both tables are replaced below, so each object is forgotten directly rather
        # than popped one layer at a time — which is what made the loop need a copy of the table it emptied.
        for ref in self._sources.values():
            forget_object(ref.uri)
        self.layers = []
        self._layer_labels = []
        self._layer_tree = LayerTree()
        self._sources = {}
        self._layer_keys = {}
        self._layer_opts = {}
        self._held_objects = {}
        self._layer_placements = {}
        self._id_counters = {}
        self._issued_ids = set()
        # A colour key is the exception, and is taken off rather than dropped: a colorbar lives on an axes of
        # its own, which clearing the data axes does not touch, so a dropped one would stay on the figure with
        # no layer left to explain — fifty frames of an animation, fifty bars. Through `detach_guide` rather
        # than `detach_artist`, for the reason that helper states: a legend the axes has already replaced is
        # forgotten instead, because `remove()` on one of those clears the slot whichever legend is in it and
        # would take a surviving frame's key off with it (review H1).
        for drawn in self._renderer.drawn.values():
            for guide in drawn.guides:
                detach_guide(guide, self.ax)
        # The artists themselves are gone with the cleared axes, so what the renderer holds is stale rather
        # than removable: it is dropped, not removed.
        self._renderer = Renderer(self)
        # The next frame's first layer draws onto an emptied axes, so it is a first render again and clears
        # rather than composes — which is what keeps a frame from composing over the frame before it.
        self._drew_on_axes = False

    def _default_label(self, layer_id: str) -> str | None:
        """Return the default colour-key title recorded for one layer, or ``None`` when there is none.

        Args:
            layer_id: The layer to ask about, by id — not by position. It was an index into :attr:`layers`
                until order 24, which is what let a coastline added after a raster answer for the raster's
                key.

        Returns:
            The label :meth:`_register_artist` filed with the layer — a raster field's resolved ``units``
            (:func:`~digitalearth.base.autostyle.auto_style`) — or ``None`` for a layer that registered
            none and for one that registered no mappable at all.
        """
        index = self._registered_index(self._renderer.drawn.get(layer_id))
        return None if index is None else self._layer_labels[index]

    def _render_glyph(
        self,
        glyph: Any,
        *plot_args: Any,
        artist: str = "im",
        label: str | None = None,
        **plot_kwargs: Any,
    ) -> DrawnLayer:
        """Plot ``glyph`` on the shared axes, register the produced mappable, and report what it drew.

        Consolidates the recipe every drawer shares — call ``glyph.plot(...)``, find the mappable it
        produced, then :meth:`_register_artist` — so it lives in one place. cleopatra glyphs expose their
        mappable in one of two ways, selected by ``artist``:

        - ``"im"`` (default): the mappable is ``glyph.im`` (``ArrayGlyph`` / ``MeshGlyph``).
        - ``"plot"``: ``glyph.plot()`` returns ``(fig, ax, artist)`` and the mappable is that third element
          (``Scatter`` / ``Polygon`` / ``Vector`` / ``KDE`` / ``Flow`` glyphs).

        It is also where a layer is told to draw **over** the ones already on the axes rather than in place
        of them (#313). A cleopatra glyph clears every glyph's artists off its axes by default, so a scene
        that added two field layers kept only the second: the axes held one image while :attr:`figure_spec`
        described two layers. Every render after this scene's first therefore passes ``compose=True``, which
        narrows that clear to the glyph's own artists. Only after the first: the opening render still
        replaces, so a scene handed an axes something else was drawn on supersedes it rather than stacking
        on it. A rebuilt layer composes too and still leaves one copy of itself, because
        :meth:`~digitalearth.static.render.renderer.Renderer.remove` has already taken the previous artists off.

        Args:
            glyph: An already-constructed cleopatra glyph bound to this Scene's ``ax``/``fig``.
            *plot_args: Positional arguments forwarded to ``glyph.plot`` (e.g. the data array for a mesh).
            artist: Which return convention to read the mappable from (``"im"`` or ``"plot"``).
            label: Optional default colorbar label recorded with the layer (see :meth:`_register_artist`);
                it is *not* forwarded to ``glyph.plot``.
            **plot_kwargs: Keyword arguments forwarded to ``glyph.plot`` (e.g. ``kind``, ``outline_only``).

        Returns:
            A :class:`~digitalearth.static.render.renderer.DrawnLayer` holding the mappable, the glyph that made it
            and the artists the layer owns — what the renderer records so the layer can later be hidden or
            taken off the axes.
        """
        plot_kwargs, deferred_alpha = prepare_plot_kwargs(glyph, plot_kwargs)
        # Only the glyphs that clear on render take the keyword; the rest (scatter, polygon, KDE, flow) add
        # to the axes without clearing it and declare no such parameter, so forwarding one would slip
        # through their `**kwargs` and reach matplotlib as an unknown artist property.
        if self._drew_on_axes and plot_takes(glyph, "compose"):
            plot_kwargs.setdefault("compose", True)
        result = glyph.plot(*plot_args, **plot_kwargs)
        # After the call, so a glyph that raised part-way does not leave the next layer composing over a
        # render that never happened.
        self._drew_on_axes = True
        mappable = glyph.im if artist == "im" else result[2]
        if deferred_alpha is not None and mappable is not None:
            mappable.set_alpha(deferred_alpha)
        self._register_artist(glyph, mappable, label)
        return DrawnLayer(
            artist=mappable,
            glyph=glyph,
            artists=() if mappable is None else (mappable,),
        )

    @contextmanager
    def _preserve_view(self) -> Iterator[None]:
        """Hold the current axes limits across the block, but only when data is already drawn.

        A global backdrop or decoration (basemap, coastlines, ocean fill, a Natural-Earth layer) would
        otherwise autoscale a regional view back out to the whole world. When the axes already holds a data
        layer (a registered layer, an image, or a collection), the pre-block x/y limits are captured and
        restored on exit; on an otherwise-empty axes the block is free to set the initial extent.

        **Restored on the way out even when the block raises**, which is the case a bare ``yield`` skipped.
        A decoration that fails part-way — a Natural-Earth read, a raster backdrop reprojected into the
        display CRS — has usually already pinned the axes to as far as it got, and the map outlives the
        failure: a caller that reports the error and goes on drawing was then drawing into a blown-out
        view rather than into the regional one it had asked for. Measured on an axes held at ``(0, 3)``
        with a block that widens it to ``(-180, 180)`` and then raises: ``(-180.0, 180.0)`` before,
        ``(0.0, 3.0)`` after. The normal path is unchanged, and the empty-axes carve-out still keeps the
        extent the block set, raising or not.

        Yields:
            None — run the drawing code inside the ``with`` block.
        """
        has_data = (
            bool(self.layers) or bool(self.ax.images) or bool(self.ax.collections)
        )
        xlim, ylim = self.ax.get_xlim(), self.ax.get_ylim()
        try:
            yield
        finally:
            if has_data:
                self.ax.set_xlim(xlim)
                self.ax.set_ylim(ylim)

    def _color_keyed(self) -> list[str]:
        """Return the ids of the layers that publish a colour a key could explain, bottom first.

        Returns:
            One id per layer whose :class:`~digitalearth.base.spec.Symbology` carries a colour
            :class:`~digitalearth.base.spec.encoding.Encoding` (see :meth:`_publish_color`). A flat-coloured
            layer, an outline-only fill, a graticule, a basemap and a caller's own artist are all absent,
            which is what makes a key on them a refusal rather than an empty box.
        """
        return [
            layer_id
            for layer_id in self._layer_tree.ids
            if self._layer_tree.get(layer_id).symbology.encoding("color") is not None
        ]

    def _keyed_layer(self, layer_id: str | None, caller: str) -> LayerSpec:
        """Return the layer a key was asked for, resolving ``None`` and refusing one with no colour to key.

        ``None`` resolves to the **topmost coloured layer in draw order** — `_color_keyed()[-1]`, since that
        list is the tree's own order, bottom first. Draw order is what the tree keeps and the only order it
        can be asked for; it coincides with the order the layers were added only while none of them has been
        moved, and `move_layer` parts the two. Measured, on two rasters:

        ```text
        added in the order      : ['raster-1', 'raster-2']
        after move_layer('raster-2', 0) the draw order is ['raster-2', 'raster-1']
        colorbar() keys 'raster-1'  — the topmost — not the last-added 'raster-2'
        legend()   keys 'raster-1'  — the same resolution
        ```

        The **behaviour** is the defensible one and is unchanged: a key explains the layer the reader
        actually sees, which is the one on top. Only the sentence moved, here and on
        :meth:`colorbar`/:meth:`legend`, and it is the same correction review M14 made on the interactive
        tier so the two tiers describe one rule in one way.

        Args:
            layer_id: The caller's id, or ``None`` for the default.
            caller: The method asking, for the refusal.

        Returns:
            The layer's description.

        Raises:
            KeyError: when `layer_id` names no layer on this figure, naming the ids that do.
            ValueError: when the named layer publishes no colour encoding, or — for ``None`` — when no layer
                on the figure does, naming the layers that were drawn with one.
        """
        if layer_id is not None:
            self._require_layer(layer_id)
            if self._layer_tree.get(layer_id).symbology.encoding("color") is None:
                raise ValueError(
                    f"layer {layer_id!r} was not drawn with a colour that varies, so it has no colour key "
                    f"to show; the layers that were are {self._color_keyed()}"
                )
            return self._layer_tree.get(layer_id)
        keyed = self._color_keyed()
        if not keyed:
            raise ValueError(
                f"{caller}() has nothing to describe: no layer on this figure is coloured by a value. Draw "
                "a field, or a fill given column=..., first — a flat colour, an outline and a basemap have "
                "no key to show"
            )
        return self._layer_tree.get(keyed[-1])

    def _title_for(self, layer_id: str, asked: str | None) -> str | None:
        """Return the title a key is recorded with: the caller's, or the layer's own units.

        Resolved at the **record** rather than at the draw, so the title travels with the figure instead of
        having to be looked up again wherever it is read — and so ``""`` keeps meaning "no title at all",
        which a :class:`~digitalearth.base.spec.encoding.Guide` has no other spelling for (it refuses a
        blank one).

        Args:
            layer_id: The layer being keyed.
            asked: What the caller passed as ``label=``/``title=``.

        Returns:
            The caller's text, exactly as they wrote it; the layer's recorded units when they passed
            ``None``; and ``None`` when they passed a label with nothing in it, or the layer has no units.

            **"Nothing in it" means blank, not just empty.** `""` and `"   "` are the same request — no
            label — and only the first of them used to be read that way: a whitespace-only label is truthy,
            so it travelled on to :class:`~digitalearth.base.spec.encoding.Guide`, which refuses a blank
            title, and the caller who wrote ``label=`` was answered about a ``Guide`` (review L5). A label
            that is *not* blank is passed through untrimmed, because trimming it would be a second, silent
            change to what the figure records, and `Guide` does not trim either.

            **Only a string is read for blankness.** Anything else is handed on untouched, so the caller is
            answered by name: `Guide` refuses a title that is not a non-empty string or ``None``, which is
            the ``ValueError`` :meth:`colorbar`'s and :meth:`legend`'s ``Raises:`` sections promise and the
            answer the other three tiers already give. Reading ``asked.strip()`` unconditionally raised
            ``AttributeError: 'int' object has no attribute 'strip'`` instead — a type the caller never
            mentioned, from a method they did not call, and one :data:`~digitalearth.api.UNMAPPABLE`
            swallows as "this layer has no key to draw" (review M3). It is deliberately not answered here
            as "no label" either: accepting ``label=123`` as unlabelled would drop the caller's argument on
            the floor rather than telling them it cannot be a title.
        """
        if asked is None:
            return self._default_label(layer_id)
        if not isinstance(asked, str):
            return asked
        return asked if asked.strip() else None

    def _record_key(
        self,
        layer: LayerSpec,
        kind: str,
        *,
        title: str | None,
        visible: bool,
        labels: Sequence[str] | None,
        **kwargs: Any,
    ) -> None:
        """Record the guide on the layer's colour encoding, then draw the key from what was recorded.

        The order is the whole of order 24: the guide is part of the layer's description, so the key moves
        with the layer, hides with it, goes away with it, and survives ``to_dict()`` → ``from_dict()``. The
        drawing is then :meth:`~digitalearth.static.render.renderer.Renderer.draw_guide`'s, which is the one place
        a key is put on this figure.

        The tree is written **directly** rather than through :meth:`_change`: a guide is a change to the
        layer's symbology, and a reconcile would read that as a restyle and redraw the whole layer — a fresh
        source read and a fresh glyph to add a colorbar to the picture that is already there.

        Args:
            layer: The layer being keyed.
            kind: ``"colorbar"`` or ``"legend"`` — which furniture the guide asks for
                (:data:`~digitalearth.static.legends.legend.GUIDE_KINDS`).
            title: What the key is called, already resolved (see :meth:`_title_for`).
            visible: Whether the key is drawn. Recorded either way, so switching it back on needs no second
                description.
            labels: The caller's own row labels, or ``None`` to derive them from the layer's scale. ``None``
                also *clears* labels recorded by an earlier call, so one call's override does not outlive it.
            **kwargs: Styling forwarded to the matplotlib colorbar or legend.

        Raises:
            ValueError: from :func:`~digitalearth.static.legends.legend.draw_guide`, for a key this layer's scale
                cannot be drawn as — after the description has been put back, so a refused call leaves the
                figure describing the key it had rather than one it could not draw.
        """
        props = dict(layer.symbology.props)
        props[GUIDE_KIND_KEY] = kind
        if labels is None:
            props.pop(GUIDE_LABELS_KEY, None)
        else:
            props[GUIDE_LABELS_KEY] = tuple(str(label) for label in labels)
        symbology = with_fields(layer.symbology, props=props).with_guide(
            Guide(show=bool(visible), title=title)
        )
        held = self._layer_tree
        self._layer_tree = self._layer_tree.replace(
            with_fields(layer, symbology=symbology)
        )
        try:
            self._renderer.draw_guide(self._layer_tree.get(layer.id), **kwargs)
        except BaseException:
            self._layer_tree = held
            raise
        if kind == "legend" and visible:
            # After the draw, not before it: a refused draw must leave every other layer's description
            # exactly as it found it, and until the draw has happened no key has been displaced.
            self._displace_other_legends(layer.id)

    @staticmethod
    def _shown_swatch_guide(layer: LayerSpec) -> Guide | None:
        """Return the guide by which a layer claims a drawn swatch legend, or ``None``.

        Args:
            layer: The layer's description.

        Returns:
            The guide, when the layer carries a shown one whose kind is ``"legend"`` — the claim that
            competes for the axes' single legend slot. ``None`` otherwise, which includes a colorbar guide:
            matplotlib takes any number of bars, so those do not compete.
        """
        guide = layer.symbology.guide()
        if guide is None or not guide.show or guide_kind(layer) != "legend":
            return None
        return guide

    def _settle_swatch_keys(self) -> None:
        """Leave one layer describing a drawn swatch key, for a figure that arrived claiming several.

        :meth:`_record_key` keeps the rule on the calling path — one `legend()` displaces the last — so two
        shown swatch guides can only reach this scene on a figure built where the rule does not exist and
        read back onto it. :meth:`~digitalearth.static.render.renderer.Renderer.apply` then draws each layer in
        turn, one legend wins the axes' single slot, and until this ran the *descriptions* both went on
        saying ``show=True``. That is the worse half to leave wrong: a description is what travels to
        another tier and what a reader trusts when the figure is not in front of them, and order 24 exists
        precisely so the record and the picture cannot disagree.

        **The topmost of the layers claiming a swatch key keeps it** — the last of them in draw order, read
        off the end of a bottom-first list exactly as :meth:`_keyed_layer` reads ``None``.

        That is the topmost *claimant*, which is not always the layer :meth:`legend` with no id would key:
        only a layer that asked for a swatch key is in this contest, while :meth:`_keyed_layer` takes the
        topmost layer carrying a colour encoding whether it asked for a key or not. Measured, on three
        categorical fills ``['a', 'b', 'c']`` where a figure arrives handing a shown swatch guide to ``a``
        and ``b`` only, the keeper is ``b`` — and ``b`` is what the axes then draws — while
        ``_keyed_layer(None)`` answers ``c``. Settling on ``c`` instead would key a layer nothing asked to
        have keyed, so the narrower reading is the right one here; the two coincide whenever every coloured
        layer on the figure claims a key.

        It is not "whichever the renderer happened to draw last": `_reconcile` visits removed, rebuilt,
        restyled and added layers in that order, so the last legend drawn is not reliably the topmost. The
        keeper's key is therefore **drawn again** rather than assumed, which both puts the axes on the
        stated layer and — through
        :meth:`~digitalearth.static.render.renderer.Renderer._displaced` — takes every other layer's orphaned
        legend out of the drawn record.

        The losers are switched **off**, not cleared, so ``legend(layer_id)`` on any of them takes the key
        back exactly as it does on the calling path.

        Called from :meth:`_change`, which is the one path a description is installed by — rather than from
        the renderer, which draws the picture and must not write descriptions
        (:meth:`~digitalearth.static.render.renderer.Renderer.apply`).
        """
        claimed = [
            layer_id
            for layer_id in self._layer_tree.ids
            if self._shown_swatch_guide(self._layer_tree.get(layer_id)) is not None
            and layer_id in self._renderer.drawn
        ]
        if len(claimed) < 2:
            return
        keeper = claimed[-1]
        # Drawn before the descriptions are edited: every one of these guides already drew once during
        # `apply`, so this cannot newly refuse — and if it ever did, the descriptions would be untouched
        # rather than half-settled.
        self._renderer.draw_guide(self._layer_tree.get(keeper))
        self._displace_other_legends(keeper)

    def _displace_other_legends(self, keeper: str) -> None:
        """Switch off every other layer's swatch key, because the axes holds one legend.

        The description half of what :meth:`~digitalearth.static.render.renderer.Renderer._displaced` does to the
        drawing. matplotlib keeps a single legend per axes, so keying a second layer takes the first
        layer's swatches off the figure — :meth:`legend` has always documented that — and the first layer
        went on carrying ``Guide(show=True)`` on its encoding. A figure written out then claimed two swatch
        keys of which only one can ever be drawn, with the winner decided by draw order (review M4).

        Switched **off** rather than taken off: the *record* keeps the title and the row labels the caller
        gave, so a figure written out here still says what the displaced key was called and a layer that
        gave the slot up is still keyable rather than having to be described from scratch — the same trade
        ``visible=False`` makes.

        What it does **not** do is hand them back to the next call. ``legend(layer_id)`` with no ``title``
        and no ``labels`` resolves ``title`` through :meth:`_title_for`, which answers the layer's own units
        for a ``None``, and passes ``labels=None``, which clears a recorded override so one call's rename
        does not outlive it — so the key comes back with a re-derived title and derived rows. Bringing it
        back *as it was* means repeating them. (This said "brings that key back without a second
        description" until review L2, which is true of the record and not of the call.) Pinned by
        ``tests/static/test_static_guides.py::TestOneAxesHoldsOneSwatchLegend``'s
        ``test_taking_the_key_back_re_derives_what_it_is_called``.

        Args:
            keeper: The layer that has just been keyed, whose guide is left alone.
        """
        for layer_id in self._layer_tree.ids:
            if layer_id == keeper:
                continue
            other = self._layer_tree.get(layer_id)
            guide = self._shown_swatch_guide(other)
            if guide is None:
                continue
            self._layer_tree = self._layer_tree.replace(
                with_fields(
                    other,
                    symbology=other.symbology.with_guide(
                        with_fields(guide, show=False)
                    ),
                )
            )

    def colorbar(
        self,
        layer_id: str | None = None,
        *,
        label: str | None = None,
        visible: bool = True,
        **kwargs: Any,
    ) -> Self:
        """Show the continuous colour key of a layer.

        The Core contract's name for a colour key (#299, #261), and the Core's shape for it — the same call
        keys a map on any tier. It was ``colorbar(layer=-1)`` here until order 24: keyed **by position** into
        :attr:`layers`, so a coastline or a text label added after a raster took the key over, and drawn when
        called rather than recorded, so a removed layer left its bar behind and a figure written down carried
        no note that a key had been asked for. The guide is now recorded on the layer's own colour encoding
        and the bar is drawn from that record.

        Args:
            layer_id: Which layer's key to show. ``None`` (the default) takes **the topmost layer in draw
                order that carries a colour encoding** — not simply the topmost layer: a coastline, a
                basemap, a graticule or a text label drawn over a raster is coloured by nothing and cannot
                take the key over. A layer whose data lay outside the display CRS drew nothing and publishes
                nothing, so it is skipped too. See :meth:`_keyed_layer` for why it is the topmost rather
                than the last added, and for the measurement that separates the two.
            label: What the bar is called. ``None`` (the default) takes the layer's own recorded units — a
                raster field records the ``units``
                :func:`~digitalearth.base.autostyle.auto_style` resolved for its variable — and leaves the
                bar unlabelled when it has none. A caller's text always wins; pass ``""`` for no label at all.
            visible: ``False`` records the guide and draws no bar, so a caller passing a flag through does
                not have to branch — and takes an already-drawn bar off again. The layer is resolved and
                checked **before** the flag is read, so one spelling of a call is not valid only half the
                time.
            **kwargs: Forwarded to ``cleopatra.styling.styles.colorbar_legend`` and on to
                ``Figure.colorbar`` (``orientation``, ``shrink``, ``ticks``, ``extend``, …). Styling for
                *this* call: it is not part of the record, so a bar redrawn from the description — after a
                restyle, a rollback, or a figure read back — comes back with matplotlib's defaults in its
                place.

        Returns:
            This scene, so figure decoration reads as one expression. The Core declares `returns="self"`
            for this name and the web and interactive tiers already answer that way; returning the
            `Colorbar` meant `m.field(ds).colorbar().legend(...)` chained on two tiers and raised on this
            one. What the bar *is* comes back off the layer instead, and off the description rather than
            off the engine: `get_layer(layer_id).symbology.guide()` is the recorded
            `Guide` — its `title` and whether it is shown — which is the reading that survives being
            written out and read back. The matplotlib `Colorbar` object itself is not on this tier's
            public surface.

        Raises:
            KeyError: when `layer_id` names no layer on this figure, naming the ids that do.
            ValueError: when that layer is coloured by nothing, when no layer on the figure is, or when the
                layer is coloured **by category** — a categorical fill's norm bins the class codes cleopatra
                assigned, so a bar over them reads ``0, 1, 2 …`` where the labels belong, and :meth:`legend`
                is the key that fits it.

        Note:
            **This tier draws as many bars as there are guided layers.** matplotlib takes any number of
            colorbars — which is why :meth:`colorbars` exists — so three keyed layers are three bars, each
            stealing width from the axes. The web tier shows exactly one key and a second replaces the first,
            so a figure ported between the two changes its count; asking for one bar here means keying one
            layer. Asking twice for the *same* layer replaces its bar rather than stacking a second.

        Examples:
            - Key a field and read the recorded guide back off the layer; the bar is an axes of its own
              on the figure, and asking twice replaces it rather than stacking a second:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalearth import Map
                >>> depth = Dataset.from_array(
                ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
                ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
                ...     no_data_value=-9999.0,
                ... )
                >>> m = Map(crs=4326)
                >>> _ = m.field(depth, name="depth").colorbar(label="m")
                >>> m.get_layer("depth").symbology.guide()
                Guide(show=True, title='m', anchor=None)
                >>> len(m.fig.axes)
                2
                >>> _ = m.colorbar(label="m")
                >>> len(m.fig.axes)
                2
                >>> m.close()

                ```
            - A categorical fill is refused by name, because a bar over it would read the class codes
              cleopatra assigned rather than the categories:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import geopandas as gpd
                >>> from shapely.geometry import Polygon
                >>> from digitalearth import Map
                >>> cells = gpd.GeoDataFrame(
                ...     {"use": ["arable", "forest", "urban"]},
                ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
                ...     crs="EPSG:4326",
                ... )
                >>> m = Map(crs=4326)
                >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
                >>> m.colorbar("use")  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: layer 'use' is coloured by category, so a colorbar over it would read the ...
                >>> m.close()

                ```
        """
        layer = self._keyed_layer(layer_id, "colorbar")
        # Before the guide is recorded, not from inside the draw: a call this tier cannot answer must leave
        # the layer exactly as it found it, key and all.
        refusal = bar_refusal(layer)
        if refusal is not None:
            raise ValueError(refusal)
        self._record_key(
            layer,
            "colorbar",
            title=self._title_for(layer.id, label),
            visible=visible,
            labels=None,
            **kwargs,
        )
        return self

    def colorbars(self, **kwargs: Any) -> Self:
        """Draw one colorbar for every layer that is coloured by a value.

        This tier's own name rather than a Core one: matplotlib takes any number of bars, so "key everything
        on the figure" is a call it can answer and the other tiers cannot. Each bar is recorded on its own
        layer exactly as :meth:`colorbar` records one, so each follows the layer it explains.

        Args:
            **kwargs: Forwarded to :meth:`colorbar` for every layer keyed.

        Returns:
            This scene (chainable). It returned the list of colorbars it had created until order 24; a
            method that keys several layers has no one bar to hand back, and each layer's key is read
            back off its own description with `get_layer(layer_id).symbology.guide()`.

        Note:
            A layer coloured by nothing is **skipped**, not refused — which is the point of the plural: a
            figure of one raster, a coastline and a graticule keys the raster and says nothing about the
            other two. A layer coloured by **category** is skipped as well, because its key is a swatch
            legend rather than a bar (:meth:`legend`).

        Examples:
            - Three coloured fields take three bars, and the graticule drawn over them is skipped
              rather than refused — so the figure holds its own axes plus one per keyed layer:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalearth import Map
                >>> def band(offset):
                ...     return Dataset.from_array(
                ...         arr=np.array([[1.0, 2.0], [3.0, 4.0]]) + offset,
                ...         geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
                ...         no_data_value=-9999.0,
                ...     )
                >>> m = Map(crs=4326)
                >>> for name, offset in (("a", 0.0), ("b", 10.0), ("c", 20.0)):
                ...     _ = m.field(band(offset), name=name)
                >>> _ = m.graticule(spacing=60.0)
                >>> _ = m.colorbars()
                >>> len(m.fig.axes)
                4
                >>> [i for i in m.layer_ids if m.get_layer(i).symbology.guide() is not None]
                ['a', 'b', 'c']
                >>> m.close()

                ```
        """
        for layer_id in self._color_keyed():
            if bar_refusal(self._layer_tree.get(layer_id)) is not None:
                continue
            self.colorbar(layer_id, **kwargs)
        return self

    def legend(
        self,
        layer_id: str | None = None,
        *,
        title: str | None = None,
        labels: Sequence[str] | None = None,
        visible: bool = True,
        **kwargs: Any,
    ) -> Self:
        """Show the keyed colour list of a layer, as one labelled swatch per class.

        The Core contract's name for a keyed colour list, in the Core's shape. It took the **content**
        itself here until order 24 — ``legend(colors, labels)`` — so a caller had to read the drawn swatches
        off ``layer.category_legend`` and hand them back, and the key agreed with the picture only while they
        did it right. The rows are now derived from the very
        :class:`~digitalearth.base.spec.scale.Scale` the layer publishes, through
        :meth:`~digitalearth.base.spec.legend.LegendSpec.from_scale`, so a swatch equals the colour that was
        drawn by construction (#185).

        Args:
            layer_id: Which layer's classes to describe. ``None`` (the default) takes the topmost layer in
                draw order that carries a colour encoding, read exactly as :meth:`colorbar` reads it.
            title: The heading above the swatches. ``None`` (the default) takes the layer's recorded units,
                and ``""`` draws no heading.
            labels: Explicit row labels, replacing the derived ones — for units, or for renaming categories.
                One per row. ``None`` (the default) derives them, and clears labels an earlier call recorded.
            visible: ``False`` records the guide and draws nothing, and takes an already-drawn key off again.
                The layer **and the key it would draw** are resolved and checked before the flag is read, so
                one spelling of a call is not valid only half the time: `labels` that do not number the rows,
                and a layer publishing no scale to derive rows from, are refused either way (review M1).
            **kwargs: Forwarded to ``cleopatra.styling.styles.disjoint_legend`` and on to ``Axes.legend``
                (``loc``, ``ncol``, ``fontsize``, …). Styling for this call, not part of the record.

        Returns:
            This scene (chainable) — the Core declares `returns="self"` for this name. What the key is
            called and whether it is shown read back off the layer's own description, as
            `get_layer(layer_id).symbology.guide()`; the matplotlib `Legend` object itself is not on
            this tier's public surface.

        Raises:
            KeyError: when `layer_id` names no layer on this figure.
            ValueError: when that layer is coloured by nothing, when no layer on the figure is, when the
                layer publishes no scale for rows to be derived from, or when `labels` does not number the
                rows — a short list leaves swatches unlabelled and a long one labels swatches nobody drew.

        Note:
            **One legend per axes.** matplotlib holds a single legend on an axes, so keying a second layer
            this way replaces the first layer's swatches rather than adding a box beside them — unlike
            :meth:`colorbar`, where each layer gets its own strip. **The displaced layer's guide is switched
            off with it**, so the figure never describes two swatch keys of which only one can be drawn;
            ``legend()`` on that layer again brings its key back and takes this one off in its turn (review
            M4) — with a re-derived title and derived rows, because a call that passes no ``title`` and no
            ``labels`` derives both, so bringing a displaced key back *as it was* means repeating them
            (review L2). What the record keeps while the key is off is what the figure says it was called;
            it is not fed back into the next call. A categorical fill already draws its own
            swatch legend through cleopatra; asking here records it on the layer, which is what lets it be
            titled, relabelled, hidden and removed with the layer.

        Examples:
            - Key a categorical fill, then key a second one: the axes holds one legend, the displaced
              layer's guide is switched off while keeping the title and rows it was given, and taking
              the key back re-derives both:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import geopandas as gpd
                >>> from shapely.geometry import Polygon
                >>> from digitalearth import Map
                >>> cells = gpd.GeoDataFrame(
                ...     {"use": ["arable", "forest", "urban"]},
                ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
                ...     crs="EPSG:4326",
                ... )
                >>> m = Map(crs=4326)
                >>> for name in ("use", "soil"):
                ...     _ = m.choropleth(cells, column="use", scheme="categorical", name=name)
                >>> _ = m.legend("use", title="Land use", labels=["Arable", "Forest", "Urban"])
                >>> m.get_layer("use").symbology.guide()
                Guide(show=True, title='Land use', anchor=None)
                >>> _ = m.legend("soil", title="Soil")
                >>> m.get_layer("use").symbology.guide()
                Guide(show=False, title='Land use', anchor=None)
                >>> _ = m.legend("use")
                >>> m.get_layer("use").symbology.guide()
                Guide(show=True, title=None, anchor=None)
                >>> m.close()

                ```
            - Row labels that do not number the rows are refused by name, whatever `visible` says:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import geopandas as gpd
                >>> from shapely.geometry import Polygon
                >>> from digitalearth import Map
                >>> cells = gpd.GeoDataFrame(
                ...     {"use": ["arable", "forest", "urban"]},
                ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
                ...     crs="EPSG:4326",
                ... )
                >>> m = Map(crs=4326)
                >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
                >>> m.legend("use", labels=["only one"])
                Traceback (most recent call last):
                    ...
                ValueError: the key of layer 'use' has 3 rows, so labels= needs 3 labels; got 1
                >>> m.close()

                ```
        """
        layer = self._keyed_layer(layer_id, "legend")
        self._record_key(
            layer,
            "legend",
            title=self._title_for(layer.id, title),
            visible=visible,
            labels=labels,
            **kwargs,
        )
        return self

    @staticmethod
    def _recorded_title(title: Any) -> str | None:
        """Return the heading a figure records for what was handed to ``Axes.set_title``.

        The record has to agree with the drawing, and the two vocabularies are not the same:
        :class:`~digitalearth.base.spec.PanelSpec` holds a non-empty string or ``None``, while
        ``Axes.set_title`` takes anything it can render and spells "no title" three ways. Measured on a bare
        axes: ``set_title(123)`` draws ``'123'``, ``set_title(4.5)`` draws ``'4.5'``, ``set_title(None)``
        draws ``''`` and ``set_title("   ")`` draws the spaces. So the record follows matplotlib rather than
        refusing a call that has always worked, and a title with nothing readable in it is recorded as no
        title.

        It also normalises the **drawing**, because the two have to agree: :meth:`set_title` hands the axes
        what this returns rather than what the caller passed, and
        :meth:`~digitalearth.static.map.Map.draw_figure` passes a restored heading through it too. Without
        that, `set_title("   ")` painted the spaces matplotlib measured above while recording `None`, and a
        figure written down and read back drew a different picture (R2-L5).

        Args:
            title: What the caller passed to :meth:`set_title`.

        Returns:
            The text the axes draws, or ``None`` when the caller asked for no title — which is ``None``
            itself, ``""``, or whitespace. Blank rather than merely empty, for the reason
            :meth:`_title_for` gives about a guide's title: ``"   "`` is the same request as ``""`` and
            reads as one.

        Examples:
            - The three ways of asking for no title all record one answer, and everything else is recorded
              as the text matplotlib draws for it:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Scene
                >>> [Scene._recorded_title(asked) for asked in (None, "", "   ")]
                [None, None, None]
                >>> Scene._recorded_title("Discharge, 2020"), Scene._recorded_title(123)
                ('Discharge, 2020', '123')

                ```
        """
        if title is None:
            return None
        text = title if isinstance(title, str) else str(title)
        return text if text.strip() else None

    @property
    def title(self) -> str | None:
        """The panel's title, as the figure's description carries it.

        Returns:
            What :meth:`set_title` last recorded — the text it drew, normalised by :meth:`_recorded_title` —
            or ``None`` for a scene nobody has titled and one whose title was cleared. It is
            ``FigureSpec.panels[0].title``; the **figure's** own heading is its ``suptitle``, described as
            ``FigureSpec.title``, and :attr:`figure_spec` is where that one is read.

            It is **one** value, where the axes has three: matplotlib keeps a centre, a left and a right
            title, so ``ax.get_title(loc=...)`` answers per position while the panel has one title
            whichever position it was drawn at. A caller who wants the drawn text back should ask the axes.

        Examples:
            - A titled scene reads its panel title back, and clearing it reads back as none:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Scene
                >>> scene = Scene()
                >>> scene.set_title("Discharge, 2020").title
                'Discharge, 2020'
                >>> print(scene.set_title("").title)
                None
                >>> scene.close()

                ```
        """
        return self._title

    def set_title(self, heading: str, **kwargs: Any) -> Self:
        """Set the panel's title: draw it above the axes, and record it on the figure's description.

        Figure-level decoration rather than a layer — it draws straight onto :attr:`ax`, so removing every
        layer does not remove it — but **described** all the same, on this tier's one
        :class:`~digitalearth.base.spec.PanelSpec`, the way the 3-D tier has always described its own
        (ST-18). Until then it reached matplotlib and nothing else: a titled map answered
        ``figure_spec.panels[0].title is None``, so a figure written down lost its heading and
        :meth:`~digitalearth.static.map.Map.draw_figure` had nothing to restore on a round trip through
        this tier's own description. It is the **panel's** title, and `draw_figure` paints it back on the
        axes; the figure's own heading is its ``suptitle``, described as ``FigureSpec.title`` and restored
        there (M4).

        Args:
            heading: The text to place above the axes. Normalised by :meth:`_recorded_title`, so ``None``,
                ``""`` and any whitespace-only string (``"   "``, ``"	"``) are the one request "no
                title": none is recorded **and none is drawn**. Anything else is drawn as the text
                matplotlib renders for it, and recorded as that same text. The drawing was not normalised
                before, so `set_title("   ")` painted the spaces and described no title (R2-L5).
            **kwargs: Forwarded to ``Axes.set_title`` (``fontsize``, ``loc``, ``pad``, …). Styling for the
                drawing only: ``loc="left"`` moves where the text is painted and the figure still records
                the heading, because where a tier paints it is not what travels.

        Returns:
            This scene, so figure decoration reads as one expression. The Core declares
            ``returns="self"`` for this name and the web tier already answers that way; returning ``None``
            here meant the same line chained on one tier and raised on the other (order 27a, #265).

        Examples:
            - Set a title and read it back off the axes — and off the figure, which now carries it:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Scene
                >>> scene = Scene()
                >>> scene.set_title("Discharge, 2020").ax.get_title()
                'Discharge, 2020'
                >>> scene.figure_spec.panels[0].title
                'Discharge, 2020'
                >>> scene.close()

                ```
            - ``loc`` reaches ``Axes.set_title`` through ``**kwargs``, so the text lands on the left title
              and the centre one stays empty — while the figure records the heading either way:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Scene
                >>> scene = Scene().set_title("Left-aligned", loc="left")
                >>> scene.ax.get_title(loc="left"), scene.ax.get_title()
                ('Left-aligned', '')
                >>> scene.title
                'Left-aligned'
                >>> scene.close()

                ```
            - The title is not a layer, so removing every layer leaves it on the figure:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalearth import Map
                >>> depth = Dataset.from_array(
                ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
                ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
                ...     no_data_value=-9999.0,
                ... )
                >>> m = Map(crs=4326)
                >>> _ = m.field(depth, name="depth")
                >>> m.set_title("Depth, m").remove_layer("depth").layer_ids
                []
                >>> m.ax.get_title()
                'Depth, m'
                >>> m.close()

                ```
            - Because the heading is described, a map rebuilt from its own figure comes back titled:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth import Map
                >>> first = Map(crs=4326).set_title("Depth, m")
                >>> second = Map.from_figure(first.figure_spec)
                >>> second.ax.get_title()
                'Depth, m'
                >>> first.close()
                >>> second.close()

                ```
        """
        # Normalised before the draw as well as after it, so the drawing and the record agree: the four
        # spellings of "no title" are one request, and `set_title("   ")` painted the spaces while
        # recording `None` (R2-L5). `grid(suptitle=)` already normalised its own draw (R1-L4); this is
        # the same rule on the axes. The record is still written *after* the draw, so a `set_title` the
        # axes refuses leaves no record behind.
        recorded = self._recorded_title(heading)
        self.ax.set_title("" if recorded is None else recorded, **kwargs)
        self._title = recorded
        return self

    def on_pick(self, callback: Callable[[Pick], Any]) -> Self:
        """Call `callback` with a :class:`Pick` whenever a layer on this figure is clicked (ST-25).

        A matplotlib figure is a picture, and this tier says so — it draws no tooltip, no hover and no
        layer switcher, because there is no pointer over a saved PNG. A figure on a **live canvas** is a
        different thing: a notebook's ``%matplotlib widget``, a Qt or Tk window, or a test driving the
        canvas directly. There the canvas does report clicks, and the only piece missing was the one this
        repo owns — turning the artist matplotlib hands over back into the **layer id** the caller named
        the layer by (:meth:`~digitalearth.static.render.renderer.Renderer.layer_of`).

        It is a click rather than matplotlib's own ``pick_event``: that one fires only for artists whose
        ``set_picker`` was set, and the artists here are built by cleopatra's glyphs and by this tier's
        drawers, so opting each one in would be a per-kind decision where a tier-wide gesture is wanted.
        Nothing is asked of the drawers, and a layer drawn before the callback was registered is pickable
        too.

        **Which layer a pick reports.** Layers overlap, so a click can land on several; the pick reports
        the **topmost** — the one painted last, which is the one the reader sees — and lists the rest in
        :attr:`Pick.hits`, topmost first. A layer that is **hidden** is not reported, and neither is one
        that has been **removed**: the hit test is run against what the renderer holds at the moment of
        the click, and a hidden layer is excluded explicitly, because ``Artist.contains`` ignores the
        visibility flag (measured: a hidden ``AxesImage`` still answers ``True`` inside its extent).

        A click that lands on **no** layer — the margin of the axes, or outside it altogether — calls
        nothing: a pick is a pick *of a layer*, and there is no layer to name. A layer owning several
        artists (a limb-split coastline, a graticule's lines) is reported once, by its one id.

        **A callback that raises does not take the others with it.** Each is called inside its own
        ``try``: the failure is reported as a ``UserWarning`` naming the callback and the exception, and
        the remaining callbacks still hear the pick, as does the next click. It propagated before
        (R2-L1), which starved every handler registered after the raising one — measured, a two-handler
        figure whose first handler raised `RuntimeError` ran the second 0 times.

        Args:
            callback: Called as ``callback(pick)`` with one :class:`Pick`. Several may be registered and
                each is called, in the order they were registered. Registering the same callback twice
                calls it twice, which is what a list of handlers means; :meth:`off_pick` takes one off.

        Returns:
            This scene (chainable), as every other figure-level call on this tier answers.

        Raises:
            TypeError: when `callback` is not callable — the refusal belongs at the registration, where
                the caller is, rather than at the first click, where they are not.

        Warns:
            UserWarning: at **delivery**, when a registered callback raises — naming the callback and the
                exception. The pick still reaches the other callbacks.

        Note:
            This is the **matplotlib canvas only**. The interactive and web tiers have pointer events of
            their own, delivered by Bokeh and MapLibre; nothing here is shared with them, and a saved
            image carries no callback at all.

        Examples:
            - Register a callback and drive one click through the canvas, as a GUI backend would:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from matplotlib.backend_bases import MouseEvent
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> _ = m.field(np.arange(16.0).reshape(4, 4), name="grid")
                >>> picked = []
                >>> _ = m.on_pick(lambda pick: picked.append((pick.layer_id, round(pick.x, 1))))
                >>> m.fig.canvas.draw()
                >>> px, py = m.ax.transData.transform((1.5, 2.0))
                >>> click = MouseEvent("button_press_event", m.fig.canvas, px, py, button=1)
                >>> m.fig.canvas.callbacks.process("button_press_event", click)
                >>> picked
                [('grid', 1.5)]
                >>> m.close()

                ```
            - A click on no layer calls nothing, and something that cannot be called is refused at the
              registration rather than at the first click:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from matplotlib.backend_bases import MouseEvent
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> _ = m.field(np.arange(16.0).reshape(4, 4), name="grid")
                >>> picked = []
                >>> _ = m.on_pick(picked.append)
                >>> m.fig.canvas.draw()
                >>> away = MouseEvent("button_press_event", m.fig.canvas, -50, -50, button=1)
                >>> m.fig.canvas.callbacks.process("button_press_event", away)
                >>> picked
                []
                >>> m.on_pick("not callable")
                Traceback (most recent call last):
                    ...
                TypeError: Map.on_pick needs something to call with each pick; got str
                >>> m.close()

                ```
        """
        if not callable(callback):
            raise TypeError(
                f"{type(self).__name__}.on_pick needs something to call with each pick; got "
                f"{type(callback).__name__}"
            )
        self._pick_handlers.append(callback)
        if self._pick_cid is None:
            self._pick_cid = self.fig.canvas.mpl_connect(
                "button_press_event", self._deliver_pick
            )
        return self

    def off_pick(self, callback: Callable[[Pick], Any] | None = None) -> Self:
        """Stop delivering picks to one callback, or to all of them.

        Args:
            callback: The callback to take off, matched by **equality** — ``==``, the way ``list.remove``
                and ``atexit.unregister`` match what they were given, not by identity. That is what makes
                the ordinary idiom work: ``list.append`` builds a *new* bound method on every attribute
                access, so ``m.on_pick(picked.append).off_pick(picked.append)`` hands over two distinct
                objects that compare equal, and identity matching would refuse the second (measured:
                ``ValueError: <built-in method append of list object …> is not registered``). The
                consequence is the other way round too — a callable whose own ``__eq__`` reports equal to
                its siblings is matched by that ``__eq__``, so a handler that wants to be taken off by
                identity alone leaves ``__eq__`` as ``object`` defines it. ``None`` (the default) takes
                every one off, which is what a caller tearing a session down wants.

        Returns:
            This scene (chainable).

        Raises:
            ValueError: when `callback` was never registered, naming how many are. A silent no-op here
                would look exactly like a callback that refused to go away — the reason
                :meth:`remove_layer` refuses an unknown id rather than ignoring it.

        Note:
            The canvas connection is dropped with the **last** callback, so a scene nobody is listening to
            no longer has a handler on its canvas; the next :meth:`on_pick` makes it again.

        Examples:
            - A callback taken off hears nothing more:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from matplotlib.backend_bases import MouseEvent
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> _ = m.field(np.arange(16.0).reshape(4, 4), name="grid")
                >>> picked = []
                >>> _ = m.on_pick(picked.append).off_pick(picked.append)
                >>> m.fig.canvas.draw()
                >>> px, py = m.ax.transData.transform((1.5, 2.0))
                >>> click = MouseEvent("button_press_event", m.fig.canvas, px, py, button=1)
                >>> m.fig.canvas.callbacks.process("button_press_event", click)
                >>> picked
                []
                >>> m.close()

                ```
            - No argument takes every callback off and drops the canvas connection with the last of them;
              a callback that was never registered is refused rather than ignored:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Map
                >>> m = Map(globe=False)
                >>> seen = []
                >>> _ = m.on_pick(seen.append)
                >>> m._pick_cid is None
                False
                >>> _ = m.off_pick()
                >>> m._pick_cid is None
                True
                >>> m.off_pick(print)  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: ...is not registered on this figure...0 callback(s) are
                >>> m.close()

                ```
        """
        if callback is None:
            self._pick_handlers = []
        # `in` and `remove` are both `==`, which is the documented rule rather than an accident of the
        # spelling: see the `callback` argument above for why identity would refuse `picked.append`.
        elif callback in self._pick_handlers:
            self._pick_handlers.remove(callback)
        else:
            raise ValueError(
                f"{callback!r} is not registered on this figure, so there is nothing to take off; "
                f"{len(self._pick_handlers)} callback(s) are"
            )
        if not self._pick_handlers:
            self._disconnect_picks()
        return self

    def _disconnect_picks(self) -> None:
        """Take this scene's click handler off its canvas, if it has one.

        Written once because three callers need it: :meth:`off_pick` when the last callback goes,
        :meth:`close` so a closed figure delivers nothing, and itself a second time harmlessly — the
        connection id is cleared, so disconnecting twice is a no-op rather than an error.
        """
        if self._pick_cid is not None:
            self.fig.canvas.mpl_disconnect(self._pick_cid)
            self._pick_cid = None

    def _deliver_pick(self, event: Any) -> None:
        """Turn one canvas click into a :class:`Pick` and hand it to every registered callback.

        The scene's half of the gesture: it is what knows which axes is its own, and what builds the
        public value out of the renderer's answer. The hit test itself is
        :meth:`~digitalearth.static.render.renderer.Renderer.hits`, which holds the artist-to-layer mapping.

        Args:
            event: The matplotlib ``MouseEvent`` the canvas delivered.

        Note:
            Three clicks deliver nothing: one outside this scene's axes (``inaxes`` is another axes, or
            none at all — the colorbar's axes is on this figure too and is not the map), one on no layer,
            and one on a figure whose callbacks have all been taken off. The callbacks are iterated over a
            **copy**, so a callback that calls :meth:`off_pick` — a "pick once" handler — does not change
            the list being walked underneath it. The copy is load-bearing rather than defensive, and
            measured: walking the live list, a handler that takes itself off makes the loop skip the
            handler that shifts into the index just consumed, silently (its neighbour is simply never
            called). It is spelled ``list.copy`` because ``list(...)`` over something already iterable
            reads as a redundant cast — to a reader and to a linter (SonarCloud python:S7504) — where
            this is a snapshot taken on purpose.

            A callback that **raises** is contained here rather than propagated (R2-L1): the exception
            left the canvas dispatch and took every handler registered after it with it, which is the
            same starvation the copy exists to prevent, by another route. Each callback is called inside
            its own ``try``, and a failure is reported as a ``UserWarning`` naming the callback and the
            exception. The gesture survives too — the connection is untouched, so the next click is
            delivered as usual.

        Warns:
            UserWarning: when a registered callback raises, naming the callback's repr and the
                exception's type and message. The remaining callbacks are still called.
        """
        if getattr(event, "inaxes", None) is not self.ax:
            return
        hits = self._renderer.hits(event)
        if not hits:
            return
        pick = Pick(hits[0], float(event.xdata), float(event.ydata), hits, event)
        for callback in self._pick_handlers.copy():
            try:
                callback(pick)
            except Exception as error:
                # One handler's failure is not the gesture's. Matplotlib's own `CallbackRegistry`
                # takes the same line, and without this the exception left the canvas dispatch and
                # every handler registered after the raising one was skipped: measured, a two-handler
                # figure whose first handler raised `RuntimeError` ran the second 0 times. `Exception`
                # rather than a named class, because the handler is the caller's own code and can fail
                # any way it likes; `BaseException` is left alone so a `KeyboardInterrupt` still stops.
                warnings.warn(
                    f"a pick callback raised and was skipped: {callback!r} raised "
                    f"{type(error).__name__}: {error}. The other callbacks still heard this pick.",
                    UserWarning,
                    stacklevel=2,
                )

    def stamp(self, mark: Any, **kwargs: Any) -> Any:
        """Stamp a logo / watermark onto the figure (delegates to cleopatra's ``WatermarkMixin.stamp_mark``).

        The mark is placed in one corner of :attr:`fig` on a frameless inset axes in figure-fraction
        coordinates, so it keeps its proportion and corner offset at whatever dpi the figure is later saved
        at. Because it is figure-level rather than axes-level it sits above every layer, and works on any
        scene — a :class:`~digitalearth.static.map.Map`, a chart, or a bare :class:`Scene`.

        **Figure furniture, not a layer, and a deliberate ``-> Any`` carve-out.** Like
        :meth:`~digitalearth.static.builders.vector.VectorMixin.quiverkey` and :meth:`save`, the return *is* the
        point of the call — the inset ``Axes`` comes back so the mark can be repositioned or restyled — so it
        is annotated ``-> Any`` rather than the ``-> Self`` the chaining contract makes the default for a
        builder it only resembles. It registers **no layer**: it adds no entry to :attr:`layer_ids`, writes
        nothing to the figure's description, and so is **not** reachable through :meth:`artist`
        (``scene.artist("stamp")`` raises `KeyError`). It is figure furniture rather than a data builder,
        which is why :meth:`quiverkey`'s furniture note names it — with :meth:`save` — as handing back its own
        object yet sitting *beside* :meth:`~digitalearth.static.builders.raster.RasterMixin.field`'s Returns census
        of the builder carve-outs (which enumerates ``quiverkey`` and ``stock_img``) rather than inside it.
        ``tests/static/test_stamp_is_furniture.py`` pins both halves.

        Args:
            mark: The mark image — a file path (any format Pillow can open) or an in-memory ``(H, W, 3)`` /
                ``(H, W, 4)`` array, either ``uint8`` ``0-255`` or float ``0-1``.
            **kwargs: Forwarded to ``stamp_mark`` — ``frac`` (the mark's longer side as a fraction of the
                figure, default ``0.11``), ``corner`` (``"lower right"`` / ``"lower left"`` /
                ``"upper right"`` / ``"upper left"``), ``margin``, ``shadow`` and ``blur``.

        Returns:
            The frameless inset ``Axes`` the mark was drawn on.

        Raises:
            ValueError: if ``corner``, ``frac``, ``margin`` or ``blur`` is out of contract, if the mark plus
                its margin would not fit the figure, or if an array mark has a bad shape/dtype/range.
            FileNotFoundError: if ``mark`` is a path that does not exist.

        Warning:
            Stamp **last** — the mark is baked from the figure's current size, so call this after any
            ``tight_layout()`` and after the final ``set_size_inches``. Note also that :meth:`save` defaults
            to ``bbox_inches="tight"``, which crops surrounding whitespace and so shifts the mark's relative
            margin; pass ``bbox_inches=None`` to :meth:`save` to preserve the placement exactly.

        Examples:
            - Stamp a small opaque mark into the lower-right corner:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import Scene
                >>> scene = Scene(figsize=(8, 6))
                >>> logo = np.zeros((40, 80, 4), dtype=np.uint8)
                >>> logo[..., :3] = 255
                >>> logo[..., 3] = 255
                >>> mark_ax = scene.stamp(logo, frac=0.2, shadow=False)
                >>> [round(float(v), 3) for v in mark_ax.get_position().bounds]
                [0.775, 0.025, 0.2, 0.133]
                >>> scene.close()

                ```
        """
        return self.stamp_mark(mark, **kwargs)

    def save(self, path: str | os.PathLike[str], **kwargs: Any) -> Path:
        """Save the figure to ``path`` (``bbox_inches="tight"`` by default).

        Args:
            path: Destination file path; the extension picks the format matplotlib writes.
            **kwargs: Forwarded to ``Figure.savefig`` (e.g. ``dpi``, ``bbox_inches``, ``transparent``).

        Returns:
            The path that was written, as a :class:`pathlib.Path` — every backend's ``save`` returns one, so
            a caller can chain onto the result without re-deriving it.

        Examples:
            - Save a scene and read the written file back off the return value:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import tempfile
                >>> from pathlib import Path
                >>> from digitalearth.static import Scene
                >>> scene = Scene()
                >>> out = scene.save(Path(tempfile.mkdtemp()) / "scene.png")
                >>> out.suffix
                '.png'
                >>> out.exists()
                True
                >>> scene.close()

                ```
        """
        self.fig.savefig(path, **{"bbox_inches": "tight", **kwargs})
        return Path(path)

    def show(self) -> None:
        """Show the figure via `matplotlib.pyplot.show`.

        Returns:
            `None`. This is the one Core name where this tier does not hand its engine object back. The
            Core declares `returns="engine"` for `show`, and the other three tiers each answer with the
            object their engine displays: the web tier returns its widget, the interactive tier the
            composed HoloViews object, and the 3-D tier whatever `pyvista.Plotter.show` hands back.
            On those tiers displaying a map *produces* something. `pyplot.show` does not — it hands the
            figure to whatever GUI backend is active and returns nothing — so there is no engine object
            here to hand over, and inventing one would be inventing it.

        Note:
            Nothing is displayed under a non-interactive backend. On `Agg` — which the test suite and
            every headless run use — matplotlib warns `FigureCanvasAgg is non-interactive, and thus
            cannot be shown` and the call is otherwise a no-op; use :meth:`save` there.

        Examples:
            - Showing a scene on the headless backend returns nothing and leaves the figure intact, so
              it can still be saved or closed afterwards:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import warnings
                >>> from digitalearth.static import Scene
                >>> scene = Scene()
                >>> with warnings.catch_warnings():
                ...     warnings.simplefilter("ignore")
                ...     print(scene.show())
                None
                >>> len(scene.fig.axes)
                1
                >>> scene.close()

                ```
        """
        plt.show()

    def close(self) -> None:
        """Close the figure and let go of the in-memory data this scene registered.

        Two things are released, because a scene holds two kinds of memory. The **figure** is matplotlib's,
        and a long run of scenes that never closes one keeps every axes alive. The **object table** is this
        package's: it is process-global and holds strong references, so a session that builds maps keeps
        every dataset they drew until something says otherwise. This is the caller saying so, and it is what
        ``with`` calls on the way out.

        Closing twice is harmless, and a scene that drew nothing has nothing to forget.

        An ``object:`` source in a :attr:`figure_spec` captured from this scene cannot be opened afterwards
        — which is what "closed" means for a figure whose data lived only in this process. Save the data and
        reference it by path to keep such a figure readable.

        **The figure is closed only when this scene created it.** A figure the scene **made** itself (a
        bare ``Map()``/``Scene()``, and so every :meth:`from_figure` round trip) is closed here; a figure
        handed in through ``ax=``/``fig=`` is **spared**, because it belongs to whoever laid it out. This is
        #371, resolved: a borrowed figure is spared (R2-L12), which brings this into line with
        :meth:`~digitalearth.static.globe.textured_globe.TexturedGlobe.close`, always gated the same way. The
        object table and the pick handler are released on **every** close regardless — see below.

        .. warning::
            When the scene owns the figure, this closes the **entire** ``self.fig``. The panels returned by
            :func:`~digitalearth.static.panels.figure.grid` share **one** figure none of them owns (each is built
            with ``ax=``/``fig=``), so closing a single panel no longer closes its siblings — and an
            :meth:`~digitalearth.static.builders.inset.InsetMixin.inset` locator, drawn on the host's own
            figure, likewise spares the host when closed. Close the scene that **made** the figure (or call
            :meth:`save` and close it yourself) to take the whole figure down. The pick handler this scene
            connected comes off on close whether the figure is owned or borrowed, so a closed borrowed-axes
            scene stops answering clicks even though its figure lives on.

        Examples:
            - A scene that drew nothing closes quietly:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> from digitalearth.static import Scene
                >>> Scene().close()

                ```

        See Also:
            __exit__: calls this on the way out of a ``with`` block.
        """
        forget_namespace(self._objects_ns)
        self._layer_keys = {}
        self._layer_opts = {}
        self._held_objects = {}
        # A closed figure has no pointer over it, so its click handler goes with it: the canvas outlives
        # `plt.close` as a Python object, and a handler left connected would go on answering for a scene
        # whose data has just been let go (see `on_pick`). This runs on **every** close, owned or borrowed:
        # a borrowed-axes scene still connected its own handler, and that is the scene's to take back.
        self._disconnect_picks()
        self._pick_handlers = []
        # Close the figure only when this scene created it (`_owns_fig`, set in `__init__`). A figure handed
        # in through `ax=`/`fig=` — and so every `grid` panel and every `inset` locator — belongs to whoever
        # laid it out; closing it here tore down the caller's whole figure, which was the #371 footgun. This
        # matches `TexturedGlobe.close`, which has always gated on `_owns_fig`.
        if self._owns_fig:
            plt.close(self.fig)

    def __enter__(self) -> "Scene":
        """Enter the runtime context, returning the scene so ``with Scene(...) as s:`` binds it.

        Returns:
            This scene.
        """
        return self

    def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> bool:
        """Close the scene on exit so a long run of them stays memory-bounded.

        The scene is closed whether or not the body raised; any exception propagates (``__exit__`` returns
        ``False``), so ``with`` never silences errors. This is :meth:`close`, so the owned-vs-borrowed rule
        is the same: a ``with Map(crs=...)`` block closes the figure it made, while a ``with Map(ax=ax)``
        block over a caller's axes leaves that figure open and only releases this scene's own state.

        Args:
            exc_type: The exception type, ignored — closing is unconditional, as it is for a file.
            exc: The exception, ignored.
            tb: The traceback, ignored.

        Returns:
            ``False`` — exceptions are not suppressed.
        """
        self.close()
        return False

layer_ids property #

The ids of the layers this scene draws, in draw order, bottom first.

Returns:

Type Description
list[str]

One id per described layer. A layer the caller named carries that name, with surrounding

list[str]

whitespace removed; an unnamed one gets a generated id counting the layers of its kind —

list[str]

scatter, text, scatter, text is points-1, points-2, text-1, text-2, listed in draw

list[str]

order. It counted the figure until review R2-M10, while this sentence already said otherwise

list[str]

(review R2-L2).

figure_spec property #

What the scene draws, as data: its layers, their sources and the view.

Returns:

Name Type Description
A FigureSpec

class:~digitalearth.base.spec.FigureSpec with one panel, :data:PANEL_ID, whose layers are

FigureSpec

the tree in draw order and whose sources are what each builder was given.

FigureSpec

It carries the plain half of the caller's styling and no more: a keyword passed through

FigureSpec

**opts is described when :func:~digitalearth.base.spec._serial.travels_in_a_figure accepts

FigureSpec

it, and held beside the layer

FigureSpec

(:attr:LayerRecord.opts) when it does not — so a figure drawn on another scene draws the

FigureSpec

described vmin, alpha, color or title, and the engine's defaults in place of a

FigureSpec

dash tuple, a per-pixel array or a Normalize.

FigureSpec

A scene built from data already in memory can be handed straight to a renderer, but not written:

FigureSpec

to_dict() refuses an object: source, because a reference into this process's memory would

FigureSpec

be unreadable everywhere else. Give a builder a path or a URL to get a figure that can be stored.

viewport property #

Where the scene is looking, as a value.

A bare :class:Scene is a figure host rather than a map — it has no display CRS to place anything in — so the view is the default one. :class:~digitalearth.static.builders.base.GeoLayerBase overrides this with the CRS, domain and globe flag it was built with.

Returns:

Name Type Description
A Viewport

class:~digitalearth.base.spec.Viewport.

get_layer(layer_id) #

Return the description of one layer, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to look up.

required

Returns:

Name Type Description
Its LayerSpec

class:~digitalearth.base.spec.LayerSpec — kind, source, symbology, band and visibility.

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do.

Examples:

  • What a builder recorded, read back by id:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> m.get_layer("ams").kind
    'text'
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def get_layer(self, layer_id: str) -> LayerSpec:
    """Return the description of one layer, by id.

    Args:
        layer_id: The layer to look up.

    Returns:
        Its :class:`~digitalearth.base.spec.LayerSpec` — kind, source, symbology, band and visibility.

    Raises:
        KeyError: if no layer has that id, naming the ids that do.

    Examples:
        - What a builder recorded, read back by id:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> m.get_layer("ams").kind
            'text'
            >>> m.close()

            ```
    """
    self._require_layer(layer_id)
    return self._layer_tree.get(layer_id)

add_layer(layer, *, name=None, band=None, color_field=None) #

Register an artist you built yourself as a layer, and return this scene (chainable).

The Core spelling of what :meth:_add_layer has always done, and the point of having it in public: an artist added this way is addressable like any other layer — :attr:layer_ids lists it, :meth:get_layer describes it, :meth:set_visible hides it and :meth:remove_layer takes it off. What the figure keeps is the description (id, kind custom:matplotlib, label, band, visibility); the artist itself is held by this scene, because a matplotlib artist has no description to write, so a figure read back elsewhere names the layer and cannot rebuild it (:mod:digitalearth.base.custom).

Drawing straight onto :attr:ax is still the escape hatch, and is still invisible to the figure.

Parameters:

Name Type Description Default
layer Any

The matplotlib artist you drew. Whether it is visible is read off the object, as the web tier reads it off a MapLibre layer: an artist built with visible=False is described hidden rather than described as something the figure does not draw (review L10).

required
name str | None

The id to address it by; None generates custom-1, custom-2, …. A name already on the figure is suffixed, as every builder's name= is.

None
band str | None

Where it is drawn — "underlay", "reference", "data" or "overlay". None takes the kind's own band, which is data. A caller's artist can draw anything, so only the caller can say whether it is ground cover or a label.

None
color_field str | None

The name of the value the artist's colour encodes. A hand-built artist publishes no colour encoding of its own, so without this the layer has no colour key and :meth:colorbar/:meth:legend refuse it — the one case the builders cover and the escape hatch did not (#349). Naming it publishes Encoding.by_field("color", color_field) for the layer, which is all a key needs; the bar reads its range off the artist. None (default) leaves the layer keyless, as before.

None

Returns:

Type Description
Self

This scene, so calls chain.

Raises:

Type Description
ValueError

if band is not one of the four bands, or if color_field is given empty.

TypeError

if name is neither a string nor None.

Examples:

  • An artist of your own, addressable afterwards:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from matplotlib.text import Text
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.add_layer(m.ax.add_artist(Text(0.0, 0.0, "mine")), name="mine")
    >>> m.get_layer("mine").kind
    'custom:matplotlib'
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def add_layer(
    self,
    layer: Any,
    *,
    name: str | None = None,
    band: str | None = None,
    color_field: str | None = None,
) -> Self:
    """Register an artist **you built yourself** as a layer, and return this scene (chainable).

    The Core spelling of what :meth:`_add_layer` has always done, and the point of having it in public:
    an artist added this way is addressable like any other layer — :attr:`layer_ids` lists it,
    :meth:`get_layer` describes it, :meth:`set_visible` hides it and :meth:`remove_layer` takes it off.
    What the figure keeps is the *description* (id, kind `custom:matplotlib`, label, band, visibility);
    the artist itself is held by this scene, because a matplotlib artist has no description to write, so
    a figure read back elsewhere names the layer and cannot rebuild it
    (:mod:`digitalearth.base.custom`).

    Drawing straight onto :attr:`ax` is still the escape hatch, and is still invisible to the figure.

    Args:
        layer: The matplotlib artist you drew. Whether it is **visible** is read off the object, as the
            web tier reads it off a MapLibre layer: an artist built with ``visible=False`` is described
            hidden rather than described as something the figure does not draw (review L10).
        name: The id to address it by; ``None`` generates ``custom-1``, ``custom-2``, …. A name already
            on the figure is suffixed, as every builder's ``name=`` is.
        band: Where it is drawn — ``"underlay"``, ``"reference"``, ``"data"`` or ``"overlay"``. ``None``
            takes the kind's own band, which is ``data``. A caller's artist can draw anything, so only
            the caller can say whether it is ground cover or a label.
        color_field: The name of the value the artist's colour encodes. A hand-built artist publishes no
            colour encoding of its own, so without this the layer has no colour key and
            :meth:`colorbar`/:meth:`legend` refuse it — the one case the builders cover and the escape
            hatch did not (#349). Naming it publishes ``Encoding.by_field("color", color_field)`` for the
            layer, which is all a key needs; the bar reads its range off the artist. ``None`` (default)
            leaves the layer keyless, as before.

    Returns:
        This scene, so calls chain.

    Raises:
        ValueError: if `band` is not one of the four bands, or if `color_field` is given empty.
        TypeError: if `name` is neither a string nor ``None``.

    Examples:
        - An artist of your own, addressable afterwards:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from matplotlib.text import Text
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.add_layer(m.ax.add_artist(Text(0.0, 0.0, "mine")), name="mine")
            >>> m.get_layer("mine").kind
            'custom:matplotlib'
            >>> m.close()

            ```
    """
    if band is not None and band not in KIND_BANDS:
        raise ValueError(
            f"add_layer band must be one of {list(KIND_BANDS)}; got {band!r}"
        )
    self._add_layer(
        None,
        layer,
        name=name,
        band=band,
        visible=artist_is_visible(layer),
        color_field=color_field,
    )
    return self

remove_layer(layer_id) #

Take a layer off the figure, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to remove.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do — a silent no-op here would look exactly like a layer that refused to go away.

Note

The id goes back to the pool, so a name removed and asked for again is handed back unsuffixed: an id is reserved exactly while the layer is on the figure, which is the lifetime all four tiers share (:func:~digitalearth.base.spec.layer.free_layer_id).

The in-memory data is not forgotten. A figure_spec captured before the removal still names it, and drawing that figure again needs it; :meth:close is where this scene lets its data go.

Examples:

  • A layer added and then removed leaves nothing behind:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> m.remove_layer("ams").layer_ids
    []
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def remove_layer(self, layer_id: str) -> Self:
    """Take a layer off the figure, by id.

    Args:
        layer_id: The layer to remove.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do — a silent no-op here would look
            exactly like a layer that refused to go away.

    Note:
        The **id** goes back to the pool, so a name removed and asked for again is handed back
        unsuffixed: an id is reserved exactly while the layer is on the figure, which is the lifetime
        all four tiers share (:func:`~digitalearth.base.spec.layer.free_layer_id`).

        The in-memory **data** is not forgotten. A `figure_spec` captured before the removal still names
        it, and drawing that figure again needs it; :meth:`close` is where this scene lets its data go.

    Examples:
        - A layer added and then removed leaves nothing behind:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> m.remove_layer("ams").layer_ids
            []
            >>> m.close()

            ```
    """
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.remove(layer_id)))
    # After the change, not before: the drawer reads the key, the keywords and the caller's own artist
    # out of these, so dropping them first would leave the rollback inside `apply` unable to draw the
    # layer it has just taken off.
    self._layer_keys.pop(layer_id, None)
    self._layer_opts.pop(layer_id, None)
    self._held_objects.pop(layer_id, None)
    self._issued_ids.discard(layer_id)
    # The claim on the figure's coordinates goes with the layer that made it, so taking the one
    # index-placed layer off lets a georeferenced one take the axes (see `_require_one_placement`).
    self._layer_placements.pop(layer_id, None)
    return self

set_visible(layer_id, visible=True) #

Show or hide a layer, by id.

The layer stays on the figure and in its description — which is what lets it be switched back on, and what tells a saved figure that the layer is there but not drawn.

Parameters:

Name Type Description Default
layer_id str

The layer to toggle.

required
visible bool

Whether it is drawn.

True

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do.

Examples:

  • A hidden layer is still described, and comes back on:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> m.set_visible("ams", False).figure_spec.layers.is_visible("ams")
    False
    >>> m._renderer.is_visible("ams")
    False
    >>> m.set_visible("ams")._renderer.is_visible("ams")
    True
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def set_visible(self, layer_id: str, visible: bool = True) -> Self:
    """Show or hide a layer, by id.

    The layer stays on the figure and in its description — which is what lets it be switched back on,
    and what tells a saved figure that the layer is there but not drawn.

    Args:
        layer_id: The layer to toggle.
        visible: Whether it is drawn.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do.

    Examples:
        - A hidden layer is still described, and comes back on:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> m.set_visible("ams", False).figure_spec.layers.is_visible("ams")
            False
            >>> m._renderer.is_visible("ams")
            False
            >>> m.set_visible("ams")._renderer.is_visible("ams")
            True
            >>> m.close()

            ```
    """
    self._require_layer(layer_id)
    self._change(
        self._figure_with(self._layer_tree.set_visible(layer_id, bool(visible)))
    )
    return self

move_layer(layer_id, index) #

Move a layer in draw order, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to move.

required
index int

Its position afterwards, counted as a list index is — 0 is the bottom, -1 the top. A layer moves within its band: reordering the data layers is what a layer switcher does, and dragging the basemap over them is not.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
KeyError

if no layer has that id.

IndexError

if the position is outside the figure, or outside the layer's band.

Note

This reaches the picture and not only the description. matplotlib paints the artists of one z-order in the order they were added, so the renderer re-arranges the layers it holds (:meth:~digitalearth.static.render.renderer.Renderer._repaint) — and because that stops at a z-order boundary, it also deals the layers' own z-orders back out along the new order (:func:~digitalearth.static.render.renderer._rank_zorders), which is what moves a point layer under a raster rather than only saying so. The layers keep the z-orders they held between them, so the move stays inside their slice of the stack and nothing outside it shifts; a zorder= a caller gave one of the moved layers is superseded, the move being the later word on where it is painted.

Examples:

  • Two labels, reordered by id:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> _ = m.text(2.35, 48.86, "Paris", name="par")
    >>> m.move_layer("par", 0).layer_ids
    ['par', 'ams']
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def move_layer(self, layer_id: str, index: int) -> Self:
    """Move a layer in draw order, by id.

    Args:
        layer_id: The layer to move.
        index: Its position afterwards, counted as a list index is — ``0`` is the bottom, ``-1`` the
            top. A layer moves within its band: reordering the data layers is what a layer switcher
            does, and dragging the basemap over them is not.

    Returns:
        This scene (chainable).

    Raises:
        KeyError: if no layer has that id.
        IndexError: if the position is outside the figure, or outside the layer's band.

    Note:
        This reaches the picture and not only the description. matplotlib paints the artists of one
        z-order in the order they were added, so the renderer re-arranges the layers it holds
        (:meth:`~digitalearth.static.render.renderer.Renderer._repaint`) — and because that stops at a z-order
        boundary, it also deals the layers' own z-orders back out along the new order
        (:func:`~digitalearth.static.render.renderer._rank_zorders`), which is what moves a point layer under a
        raster rather than only saying so. The layers keep the z-orders they held between them, so the
        move stays inside their slice of the stack and nothing outside it shifts; a ``zorder=`` a caller
        gave one of the moved layers is superseded, the move being the later word on where it is painted.

    Examples:
        - Two labels, reordered by id:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> _ = m.text(2.35, 48.86, "Paris", name="par")
            >>> m.move_layer("par", 0).layer_ids
            ['par', 'ams']
            >>> m.close()

            ```
    """
    # Asked here rather than left to `LayerTree.move`, so an unknown id is refused in the same words as
    # every other layer-management call on this tier: the tree names itself, the facade names the figure.
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.move(layer_id, index)))
    return self

replace_layer(layer) #

Swap a layer's description for another, keeping its id and its place in draw order.

This is how a layer is restyled or re-pointed after it has been drawn: a cleopatra glyph bakes its colormap and its class breaks into the artist it built, so the renderer draws the layer again from the new description rather than setting a property on what is there.

Parameters:

Name Type Description Default
layer LayerSpec

The new description. Its id names the layer it replaces.

required

Returns:

Type Description
Self

This scene (chainable).

Raises:

Type Description
CapabilityError

if the replacement names a kind this tier does not draw, naming the kind and the backend that has no drawer for it. Raised off the declaration, before a description is built or the axes is touched. It subclasses ValueError, so a caller catching that catches this.

KeyError

if no layer has that id, naming the ids that do.

ValueError

if layer is not a LayerSpec, or if it draws from data and names no source_id: the drawers read the source out of the figure, and a missing one reaches the drawer as None and fails somewhere it cannot explain.

Examples:

  • A label re-described keeps its id and its place:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from dataclasses import replace
    >>> from digitalearth.static import Map
    >>> m = Map()
    >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
    >>> held = m.get_layer("ams")
    >>> _ = m.replace_layer(replace(held, label="Capital"))
    >>> m.get_layer("ams").label
    'Capital'
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def replace_layer(self, layer: LayerSpec) -> Self:
    """Swap a layer's description for another, keeping its id and its place in draw order.

    This is how a layer is restyled or re-pointed after it has been drawn: a cleopatra glyph bakes its
    colormap and its class breaks into the artist it built, so the renderer draws the layer again from
    the new description rather than setting a property on what is there.

    Args:
        layer: The new description. Its id names the layer it replaces.

    Returns:
        This scene (chainable).

    Raises:
        CapabilityError: if the replacement names a kind this tier does not draw, naming the kind and the
            backend that has no drawer for it. Raised off the declaration, before a description is built
            or the axes is touched. It subclasses ``ValueError``, so a caller catching that catches this.
        KeyError: if no layer has that id, naming the ids that do.
        ValueError: if `layer` is not a `LayerSpec`, or if it draws from data and names no `source_id`:
            the drawers read the source out of the figure, and a missing one reaches the drawer as
            ``None`` and fails somewhere it cannot explain.

    Examples:
        - A label re-described keeps its id and its place:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from dataclasses import replace
            >>> from digitalearth.static import Map
            >>> m = Map()
            >>> _ = m.text(4.9, 52.4, "Amsterdam", name="ams")
            >>> held = m.get_layer("ams")
            >>> _ = m.replace_layer(replace(held, label="Capital"))
            >>> m.get_layer("ams").label
            'Capital'
            >>> m.close()

            ```
    """
    # By type before by id: `getattr(layer, "id", None)` made the id lookup fail first, so a caller who
    # passed the id where the description belongs was answered "no layer None on this figure" — an id
    # they never wrote, about an argument that was not a description at all (review L1).
    if not isinstance(layer, LayerSpec):
        raise ValueError(
            f"{type(self).__name__}.replace_layer needs a LayerSpec — the new description, not an id; "
            f"got {type(layer).__name__}"
        )
    self._require_layer(layer.id)
    # The first production caller of `Capabilities.require` (D-10). A replacement is the one
    # layer-management call that can name a **new kind**, so it is the one that can ask this tier for
    # something it does not have — and refusing here, off the declaration, refuses before a description
    # is built or the engine is touched. Without it the refusal came from the drawer table, part-way
    # through a reconcile, and said nothing about what the tier declares.
    CAPABILITIES.require(layer.kind, caller="Map.replace_layer")
    if layer.source_id is None and kind_info(layer.kind).takes != "none":
        raise ValueError(
            f"layer {layer.id!r} is a {layer.kind!r} layer, which draws from data, so its replacement "
            f"needs a source_id; got None"
        )
    self._change(self._figure_with(self._layer_tree.replace(layer)))
    return self

colorbar(layer_id=None, *, label=None, visible=True, **kwargs) #

Show the continuous colour key of a layer.

The Core contract's name for a colour key (#299, #261), and the Core's shape for it — the same call keys a map on any tier. It was colorbar(layer=-1) here until order 24: keyed by position into :attr:layers, so a coastline or a text label added after a raster took the key over, and drawn when called rather than recorded, so a removed layer left its bar behind and a figure written down carried no note that a key had been asked for. The guide is now recorded on the layer's own colour encoding and the bar is drawn from that record.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's key to show. None (the default) takes the topmost layer in draw order that carries a colour encoding — not simply the topmost layer: a coastline, a basemap, a graticule or a text label drawn over a raster is coloured by nothing and cannot take the key over. A layer whose data lay outside the display CRS drew nothing and publishes nothing, so it is skipped too. See :meth:_keyed_layer for why it is the topmost rather than the last added, and for the measurement that separates the two.

None
label str | None

What the bar is called. None (the default) takes the layer's own recorded units — a raster field records the units :func:~digitalearth.base.autostyle.auto_style resolved for its variable — and leaves the bar unlabelled when it has none. A caller's text always wins; pass "" for no label at all.

None
visible bool

False records the guide and draws no bar, so a caller passing a flag through does not have to branch — and takes an already-drawn bar off again. The layer is resolved and checked before the flag is read, so one spelling of a call is not valid only half the time.

True
**kwargs Any

Forwarded to cleopatra.styling.styles.colorbar_legend and on to Figure.colorbar (orientation, shrink, ticks, extend, …). Styling for this call: it is not part of the record, so a bar redrawn from the description — after a restyle, a rollback, or a figure read back — comes back with matplotlib's defaults in its place.

{}

Returns:

Type Description
Self

This scene, so figure decoration reads as one expression. The Core declares returns="self"

Self

for this name and the web and interactive tiers already answer that way; returning the

Self

Colorbar meant m.field(ds).colorbar().legend(...) chained on two tiers and raised on this

Self

one. What the bar is comes back off the layer instead, and off the description rather than

Self

off the engine: get_layer(layer_id).symbology.guide() is the recorded

Self

Guide — its title and whether it is shown — which is the reading that survives being

Self

written out and read back. The matplotlib Colorbar object itself is not on this tier's

Self

public surface.

Raises:

Type Description
KeyError

when layer_id names no layer on this figure, naming the ids that do.

ValueError

when that layer is coloured by nothing, when no layer on the figure is, or when the layer is coloured by category — a categorical fill's norm bins the class codes cleopatra assigned, so a bar over them reads 0, 1, 2 … where the labels belong, and :meth:legend is the key that fits it.

Note

This tier draws as many bars as there are guided layers. matplotlib takes any number of colorbars — which is why :meth:colorbars exists — so three keyed layers are three bars, each stealing width from the axes. The web tier shows exactly one key and a second replaces the first, so a figure ported between the two changes its count; asking for one bar here means keying one layer. Asking twice for the same layer replaces its bar rather than stacking a second.

Examples:

  • Key a field and read the recorded guide back off the layer; the bar is an axes of its own on the figure, and asking twice replaces it rather than stacking a second:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> depth = Dataset.from_array(
    ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
    ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...     no_data_value=-9999.0,
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.field(depth, name="depth").colorbar(label="m")
    >>> m.get_layer("depth").symbology.guide()
    Guide(show=True, title='m', anchor=None)
    >>> len(m.fig.axes)
    2
    >>> _ = m.colorbar(label="m")
    >>> len(m.fig.axes)
    2
    >>> m.close()
    
  • A categorical fill is refused by name, because a bar over it would read the class codes cleopatra assigned rather than the categories:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
    >>> m.colorbar("use")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: layer 'use' is coloured by category, so a colorbar over it would read the ...
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def colorbar(
    self,
    layer_id: str | None = None,
    *,
    label: str | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Show the continuous colour key of a layer.

    The Core contract's name for a colour key (#299, #261), and the Core's shape for it — the same call
    keys a map on any tier. It was ``colorbar(layer=-1)`` here until order 24: keyed **by position** into
    :attr:`layers`, so a coastline or a text label added after a raster took the key over, and drawn when
    called rather than recorded, so a removed layer left its bar behind and a figure written down carried
    no note that a key had been asked for. The guide is now recorded on the layer's own colour encoding
    and the bar is drawn from that record.

    Args:
        layer_id: Which layer's key to show. ``None`` (the default) takes **the topmost layer in draw
            order that carries a colour encoding** — not simply the topmost layer: a coastline, a
            basemap, a graticule or a text label drawn over a raster is coloured by nothing and cannot
            take the key over. A layer whose data lay outside the display CRS drew nothing and publishes
            nothing, so it is skipped too. See :meth:`_keyed_layer` for why it is the topmost rather
            than the last added, and for the measurement that separates the two.
        label: What the bar is called. ``None`` (the default) takes the layer's own recorded units — a
            raster field records the ``units``
            :func:`~digitalearth.base.autostyle.auto_style` resolved for its variable — and leaves the
            bar unlabelled when it has none. A caller's text always wins; pass ``""`` for no label at all.
        visible: ``False`` records the guide and draws no bar, so a caller passing a flag through does
            not have to branch — and takes an already-drawn bar off again. The layer is resolved and
            checked **before** the flag is read, so one spelling of a call is not valid only half the
            time.
        **kwargs: Forwarded to ``cleopatra.styling.styles.colorbar_legend`` and on to
            ``Figure.colorbar`` (``orientation``, ``shrink``, ``ticks``, ``extend``, …). Styling for
            *this* call: it is not part of the record, so a bar redrawn from the description — after a
            restyle, a rollback, or a figure read back — comes back with matplotlib's defaults in its
            place.

    Returns:
        This scene, so figure decoration reads as one expression. The Core declares `returns="self"`
        for this name and the web and interactive tiers already answer that way; returning the
        `Colorbar` meant `m.field(ds).colorbar().legend(...)` chained on two tiers and raised on this
        one. What the bar *is* comes back off the layer instead, and off the description rather than
        off the engine: `get_layer(layer_id).symbology.guide()` is the recorded
        `Guide` — its `title` and whether it is shown — which is the reading that survives being
        written out and read back. The matplotlib `Colorbar` object itself is not on this tier's
        public surface.

    Raises:
        KeyError: when `layer_id` names no layer on this figure, naming the ids that do.
        ValueError: when that layer is coloured by nothing, when no layer on the figure is, or when the
            layer is coloured **by category** — a categorical fill's norm bins the class codes cleopatra
            assigned, so a bar over them reads ``0, 1, 2 …`` where the labels belong, and :meth:`legend`
            is the key that fits it.

    Note:
        **This tier draws as many bars as there are guided layers.** matplotlib takes any number of
        colorbars — which is why :meth:`colorbars` exists — so three keyed layers are three bars, each
        stealing width from the axes. The web tier shows exactly one key and a second replaces the first,
        so a figure ported between the two changes its count; asking for one bar here means keying one
        layer. Asking twice for the *same* layer replaces its bar rather than stacking a second.

    Examples:
        - Key a field and read the recorded guide back off the layer; the bar is an axes of its own
          on the figure, and asking twice replaces it rather than stacking a second:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> depth = Dataset.from_array(
            ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
            ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...     no_data_value=-9999.0,
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.field(depth, name="depth").colorbar(label="m")
            >>> m.get_layer("depth").symbology.guide()
            Guide(show=True, title='m', anchor=None)
            >>> len(m.fig.axes)
            2
            >>> _ = m.colorbar(label="m")
            >>> len(m.fig.axes)
            2
            >>> m.close()

            ```
        - A categorical fill is refused by name, because a bar over it would read the class codes
          cleopatra assigned rather than the categories:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
            >>> m.colorbar("use")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: layer 'use' is coloured by category, so a colorbar over it would read the ...
            >>> m.close()

            ```
    """
    layer = self._keyed_layer(layer_id, "colorbar")
    # Before the guide is recorded, not from inside the draw: a call this tier cannot answer must leave
    # the layer exactly as it found it, key and all.
    refusal = bar_refusal(layer)
    if refusal is not None:
        raise ValueError(refusal)
    self._record_key(
        layer,
        "colorbar",
        title=self._title_for(layer.id, label),
        visible=visible,
        labels=None,
        **kwargs,
    )
    return self

colorbars(**kwargs) #

Draw one colorbar for every layer that is coloured by a value.

This tier's own name rather than a Core one: matplotlib takes any number of bars, so "key everything on the figure" is a call it can answer and the other tiers cannot. Each bar is recorded on its own layer exactly as :meth:colorbar records one, so each follows the layer it explains.

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to :meth:colorbar for every layer keyed.

{}

Returns:

Type Description
Self

This scene (chainable). It returned the list of colorbars it had created until order 24; a

Self

method that keys several layers has no one bar to hand back, and each layer's key is read

Self

back off its own description with get_layer(layer_id).symbology.guide().

Note

A layer coloured by nothing is skipped, not refused — which is the point of the plural: a figure of one raster, a coastline and a graticule keys the raster and says nothing about the other two. A layer coloured by category is skipped as well, because its key is a swatch legend rather than a bar (:meth:legend).

Examples:

  • Three coloured fields take three bars, and the graticule drawn over them is skipped rather than refused — so the figure holds its own axes plus one per keyed layer:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> def band(offset):
    ...     return Dataset.from_array(
    ...         arr=np.array([[1.0, 2.0], [3.0, 4.0]]) + offset,
    ...         geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...         no_data_value=-9999.0,
    ...     )
    >>> m = Map(crs=4326)
    >>> for name, offset in (("a", 0.0), ("b", 10.0), ("c", 20.0)):
    ...     _ = m.field(band(offset), name=name)
    >>> _ = m.graticule(spacing=60.0)
    >>> _ = m.colorbars()
    >>> len(m.fig.axes)
    4
    >>> [i for i in m.layer_ids if m.get_layer(i).symbology.guide() is not None]
    ['a', 'b', 'c']
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def colorbars(self, **kwargs: Any) -> Self:
    """Draw one colorbar for every layer that is coloured by a value.

    This tier's own name rather than a Core one: matplotlib takes any number of bars, so "key everything
    on the figure" is a call it can answer and the other tiers cannot. Each bar is recorded on its own
    layer exactly as :meth:`colorbar` records one, so each follows the layer it explains.

    Args:
        **kwargs: Forwarded to :meth:`colorbar` for every layer keyed.

    Returns:
        This scene (chainable). It returned the list of colorbars it had created until order 24; a
        method that keys several layers has no one bar to hand back, and each layer's key is read
        back off its own description with `get_layer(layer_id).symbology.guide()`.

    Note:
        A layer coloured by nothing is **skipped**, not refused — which is the point of the plural: a
        figure of one raster, a coastline and a graticule keys the raster and says nothing about the
        other two. A layer coloured by **category** is skipped as well, because its key is a swatch
        legend rather than a bar (:meth:`legend`).

    Examples:
        - Three coloured fields take three bars, and the graticule drawn over them is skipped
          rather than refused — so the figure holds its own axes plus one per keyed layer:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> def band(offset):
            ...     return Dataset.from_array(
            ...         arr=np.array([[1.0, 2.0], [3.0, 4.0]]) + offset,
            ...         geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...         no_data_value=-9999.0,
            ...     )
            >>> m = Map(crs=4326)
            >>> for name, offset in (("a", 0.0), ("b", 10.0), ("c", 20.0)):
            ...     _ = m.field(band(offset), name=name)
            >>> _ = m.graticule(spacing=60.0)
            >>> _ = m.colorbars()
            >>> len(m.fig.axes)
            4
            >>> [i for i in m.layer_ids if m.get_layer(i).symbology.guide() is not None]
            ['a', 'b', 'c']
            >>> m.close()

            ```
    """
    for layer_id in self._color_keyed():
        if bar_refusal(self._layer_tree.get(layer_id)) is not None:
            continue
        self.colorbar(layer_id, **kwargs)
    return self

legend(layer_id=None, *, title=None, labels=None, visible=True, **kwargs) #

Show the keyed colour list of a layer, as one labelled swatch per class.

The Core contract's name for a keyed colour list, in the Core's shape. It took the content itself here until order 24 — legend(colors, labels) — so a caller had to read the drawn swatches off layer.category_legend and hand them back, and the key agreed with the picture only while they did it right. The rows are now derived from the very :class:~digitalearth.base.spec.scale.Scale the layer publishes, through :meth:~digitalearth.base.spec.legend.LegendSpec.from_scale, so a swatch equals the colour that was drawn by construction (#185).

Parameters:

Name Type Description Default
layer_id str | None

Which layer's classes to describe. None (the default) takes the topmost layer in draw order that carries a colour encoding, read exactly as :meth:colorbar reads it.

None
title str | None

The heading above the swatches. None (the default) takes the layer's recorded units, and "" draws no heading.

None
labels Sequence[str] | None

Explicit row labels, replacing the derived ones — for units, or for renaming categories. One per row. None (the default) derives them, and clears labels an earlier call recorded.

None
visible bool

False records the guide and draws nothing, and takes an already-drawn key off again. The layer and the key it would draw are resolved and checked before the flag is read, so one spelling of a call is not valid only half the time: labels that do not number the rows, and a layer publishing no scale to derive rows from, are refused either way (review M1).

True
**kwargs Any

Forwarded to cleopatra.styling.styles.disjoint_legend and on to Axes.legend (loc, ncol, fontsize, …). Styling for this call, not part of the record.

{}

Returns:

Type Description
Self

This scene (chainable) — the Core declares returns="self" for this name. What the key is

Self

called and whether it is shown read back off the layer's own description, as

Self

get_layer(layer_id).symbology.guide(); the matplotlib Legend object itself is not on

Self

this tier's public surface.

Raises:

Type Description
KeyError

when layer_id names no layer on this figure.

ValueError

when that layer is coloured by nothing, when no layer on the figure is, when the layer publishes no scale for rows to be derived from, or when labels does not number the rows — a short list leaves swatches unlabelled and a long one labels swatches nobody drew.

Note

One legend per axes. matplotlib holds a single legend on an axes, so keying a second layer this way replaces the first layer's swatches rather than adding a box beside them — unlike :meth:colorbar, where each layer gets its own strip. The displaced layer's guide is switched off with it, so the figure never describes two swatch keys of which only one can be drawn; legend() on that layer again brings its key back and takes this one off in its turn (review M4) — with a re-derived title and derived rows, because a call that passes no title and no labels derives both, so bringing a displaced key back as it was means repeating them (review L2). What the record keeps while the key is off is what the figure says it was called; it is not fed back into the next call. A categorical fill already draws its own swatch legend through cleopatra; asking here records it on the layer, which is what lets it be titled, relabelled, hidden and removed with the layer.

Examples:

  • Key a categorical fill, then key a second one: the axes holds one legend, the displaced layer's guide is switched off while keeping the title and rows it was given, and taking the key back re-derives both:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> for name in ("use", "soil"):
    ...     _ = m.choropleth(cells, column="use", scheme="categorical", name=name)
    >>> _ = m.legend("use", title="Land use", labels=["Arable", "Forest", "Urban"])
    >>> m.get_layer("use").symbology.guide()
    Guide(show=True, title='Land use', anchor=None)
    >>> _ = m.legend("soil", title="Soil")
    >>> m.get_layer("use").symbology.guide()
    Guide(show=False, title='Land use', anchor=None)
    >>> _ = m.legend("use")
    >>> m.get_layer("use").symbology.guide()
    Guide(show=True, title=None, anchor=None)
    >>> m.close()
    
  • Row labels that do not number the rows are refused by name, whatever visible says:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth import Map
    >>> cells = gpd.GeoDataFrame(
    ...     {"use": ["arable", "forest", "urban"]},
    ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
    ...     crs="EPSG:4326",
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
    >>> m.legend("use", labels=["only one"])
    Traceback (most recent call last):
        ...
    ValueError: the key of layer 'use' has 3 rows, so labels= needs 3 labels; got 1
    >>> m.close()
    
Source code in src/digitalearth/static/core/scene.py
def legend(
    self,
    layer_id: str | None = None,
    *,
    title: str | None = None,
    labels: Sequence[str] | None = None,
    visible: bool = True,
    **kwargs: Any,
) -> Self:
    """Show the keyed colour list of a layer, as one labelled swatch per class.

    The Core contract's name for a keyed colour list, in the Core's shape. It took the **content**
    itself here until order 24 — ``legend(colors, labels)`` — so a caller had to read the drawn swatches
    off ``layer.category_legend`` and hand them back, and the key agreed with the picture only while they
    did it right. The rows are now derived from the very
    :class:`~digitalearth.base.spec.scale.Scale` the layer publishes, through
    :meth:`~digitalearth.base.spec.legend.LegendSpec.from_scale`, so a swatch equals the colour that was
    drawn by construction (#185).

    Args:
        layer_id: Which layer's classes to describe. ``None`` (the default) takes the topmost layer in
            draw order that carries a colour encoding, read exactly as :meth:`colorbar` reads it.
        title: The heading above the swatches. ``None`` (the default) takes the layer's recorded units,
            and ``""`` draws no heading.
        labels: Explicit row labels, replacing the derived ones — for units, or for renaming categories.
            One per row. ``None`` (the default) derives them, and clears labels an earlier call recorded.
        visible: ``False`` records the guide and draws nothing, and takes an already-drawn key off again.
            The layer **and the key it would draw** are resolved and checked before the flag is read, so
            one spelling of a call is not valid only half the time: `labels` that do not number the rows,
            and a layer publishing no scale to derive rows from, are refused either way (review M1).
        **kwargs: Forwarded to ``cleopatra.styling.styles.disjoint_legend`` and on to ``Axes.legend``
            (``loc``, ``ncol``, ``fontsize``, …). Styling for this call, not part of the record.

    Returns:
        This scene (chainable) — the Core declares `returns="self"` for this name. What the key is
        called and whether it is shown read back off the layer's own description, as
        `get_layer(layer_id).symbology.guide()`; the matplotlib `Legend` object itself is not on
        this tier's public surface.

    Raises:
        KeyError: when `layer_id` names no layer on this figure.
        ValueError: when that layer is coloured by nothing, when no layer on the figure is, when the
            layer publishes no scale for rows to be derived from, or when `labels` does not number the
            rows — a short list leaves swatches unlabelled and a long one labels swatches nobody drew.

    Note:
        **One legend per axes.** matplotlib holds a single legend on an axes, so keying a second layer
        this way replaces the first layer's swatches rather than adding a box beside them — unlike
        :meth:`colorbar`, where each layer gets its own strip. **The displaced layer's guide is switched
        off with it**, so the figure never describes two swatch keys of which only one can be drawn;
        ``legend()`` on that layer again brings its key back and takes this one off in its turn (review
        M4) — with a re-derived title and derived rows, because a call that passes no ``title`` and no
        ``labels`` derives both, so bringing a displaced key back *as it was* means repeating them
        (review L2). What the record keeps while the key is off is what the figure says it was called;
        it is not fed back into the next call. A categorical fill already draws its own
        swatch legend through cleopatra; asking here records it on the layer, which is what lets it be
        titled, relabelled, hidden and removed with the layer.

    Examples:
        - Key a categorical fill, then key a second one: the axes holds one legend, the displaced
          layer's guide is switched off while keeping the title and rows it was given, and taking
          the key back re-derives both:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> for name in ("use", "soil"):
            ...     _ = m.choropleth(cells, column="use", scheme="categorical", name=name)
            >>> _ = m.legend("use", title="Land use", labels=["Arable", "Forest", "Urban"])
            >>> m.get_layer("use").symbology.guide()
            Guide(show=True, title='Land use', anchor=None)
            >>> _ = m.legend("soil", title="Soil")
            >>> m.get_layer("use").symbology.guide()
            Guide(show=False, title='Land use', anchor=None)
            >>> _ = m.legend("use")
            >>> m.get_layer("use").symbology.guide()
            Guide(show=True, title=None, anchor=None)
            >>> m.close()

            ```
        - Row labels that do not number the rows are refused by name, whatever `visible` says:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth import Map
            >>> cells = gpd.GeoDataFrame(
            ...     {"use": ["arable", "forest", "urban"]},
            ...     geometry=[Polygon([(i, 0), (i + 1, 0), (i + 1, 1), (i, 1)]) for i in range(3)],
            ...     crs="EPSG:4326",
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.choropleth(cells, column="use", scheme="categorical", name="use")
            >>> m.legend("use", labels=["only one"])
            Traceback (most recent call last):
                ...
            ValueError: the key of layer 'use' has 3 rows, so labels= needs 3 labels; got 1
            >>> m.close()

            ```
    """
    layer = self._keyed_layer(layer_id, "legend")
    self._record_key(
        layer,
        "legend",
        title=self._title_for(layer.id, title),
        visible=visible,
        labels=labels,
        **kwargs,
    )
    return self

stamp(mark, **kwargs) #

Stamp a logo / watermark onto the figure (delegates to cleopatra's WatermarkMixin.stamp_mark).

The mark is placed in one corner of :attr:fig on a frameless inset axes in figure-fraction coordinates, so it keeps its proportion and corner offset at whatever dpi the figure is later saved at. Because it is figure-level rather than axes-level it sits above every layer, and works on any scene — a :class:~digitalearth.static.map.Map, a chart, or a bare :class:Scene.

Figure furniture, not a layer, and a deliberate -> Any carve-out. Like :meth:~digitalearth.static.builders.vector.VectorMixin.quiverkey and :meth:save, the return is the point of the call — the inset Axes comes back so the mark can be repositioned or restyled — so it is annotated -> Any rather than the -> Self the chaining contract makes the default for a builder it only resembles. It registers no layer: it adds no entry to :attr:layer_ids, writes nothing to the figure's description, and so is not reachable through :meth:artist (scene.artist("stamp") raises KeyError). It is figure furniture rather than a data builder, which is why :meth:quiverkey's furniture note names it — with :meth:save — as handing back its own object yet sitting beside :meth:~digitalearth.static.builders.raster.RasterMixin.field's Returns census of the builder carve-outs (which enumerates quiverkey and stock_img) rather than inside it. tests/static/test_stamp_is_furniture.py pins both halves.

Parameters:

Name Type Description Default
mark Any

The mark image — a file path (any format Pillow can open) or an in-memory (H, W, 3) / (H, W, 4) array, either uint8 0-255 or float 0-1.

required
**kwargs Any

Forwarded to stamp_mark — frac (the mark's longer side as a fraction of the figure, default 0.11), corner ("lower right" / "lower left" / "upper right" / "upper left"), margin, shadow and blur.

{}

Returns:

Type Description
Any

The frameless inset Axes the mark was drawn on.

Raises:

Type Description
ValueError

if corner, frac, margin or blur is out of contract, if the mark plus its margin would not fit the figure, or if an array mark has a bad shape/dtype/range.

FileNotFoundError

if mark is a path that does not exist.

Warning

Stamp last — the mark is baked from the figure's current size, so call this after any tight_layout() and after the final set_size_inches. Note also that :meth:save defaults to bbox_inches="tight", which crops surrounding whitespace and so shifts the mark's relative margin; pass bbox_inches=None to :meth:save to preserve the placement exactly.

Examples:

  • Stamp a small opaque mark into the lower-right corner:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import Scene
    >>> scene = Scene(figsize=(8, 6))
    >>> logo = np.zeros((40, 80, 4), dtype=np.uint8)
    >>> logo[..., :3] = 255
    >>> logo[..., 3] = 255
    >>> mark_ax = scene.stamp(logo, frac=0.2, shadow=False)
    >>> [round(float(v), 3) for v in mark_ax.get_position().bounds]
    [0.775, 0.025, 0.2, 0.133]
    >>> scene.close()
    
Source code in src/digitalearth/static/core/scene.py
def stamp(self, mark: Any, **kwargs: Any) -> Any:
    """Stamp a logo / watermark onto the figure (delegates to cleopatra's ``WatermarkMixin.stamp_mark``).

    The mark is placed in one corner of :attr:`fig` on a frameless inset axes in figure-fraction
    coordinates, so it keeps its proportion and corner offset at whatever dpi the figure is later saved
    at. Because it is figure-level rather than axes-level it sits above every layer, and works on any
    scene — a :class:`~digitalearth.static.map.Map`, a chart, or a bare :class:`Scene`.

    **Figure furniture, not a layer, and a deliberate ``-> Any`` carve-out.** Like
    :meth:`~digitalearth.static.builders.vector.VectorMixin.quiverkey` and :meth:`save`, the return *is* the
    point of the call — the inset ``Axes`` comes back so the mark can be repositioned or restyled — so it
    is annotated ``-> Any`` rather than the ``-> Self`` the chaining contract makes the default for a
    builder it only resembles. It registers **no layer**: it adds no entry to :attr:`layer_ids`, writes
    nothing to the figure's description, and so is **not** reachable through :meth:`artist`
    (``scene.artist("stamp")`` raises `KeyError`). It is figure furniture rather than a data builder,
    which is why :meth:`quiverkey`'s furniture note names it — with :meth:`save` — as handing back its own
    object yet sitting *beside* :meth:`~digitalearth.static.builders.raster.RasterMixin.field`'s Returns census
    of the builder carve-outs (which enumerates ``quiverkey`` and ``stock_img``) rather than inside it.
    ``tests/static/test_stamp_is_furniture.py`` pins both halves.

    Args:
        mark: The mark image — a file path (any format Pillow can open) or an in-memory ``(H, W, 3)`` /
            ``(H, W, 4)`` array, either ``uint8`` ``0-255`` or float ``0-1``.
        **kwargs: Forwarded to ``stamp_mark`` — ``frac`` (the mark's longer side as a fraction of the
            figure, default ``0.11``), ``corner`` (``"lower right"`` / ``"lower left"`` /
            ``"upper right"`` / ``"upper left"``), ``margin``, ``shadow`` and ``blur``.

    Returns:
        The frameless inset ``Axes`` the mark was drawn on.

    Raises:
        ValueError: if ``corner``, ``frac``, ``margin`` or ``blur`` is out of contract, if the mark plus
            its margin would not fit the figure, or if an array mark has a bad shape/dtype/range.
        FileNotFoundError: if ``mark`` is a path that does not exist.

    Warning:
        Stamp **last** — the mark is baked from the figure's current size, so call this after any
        ``tight_layout()`` and after the final ``set_size_inches``. Note also that :meth:`save` defaults
        to ``bbox_inches="tight"``, which crops surrounding whitespace and so shifts the mark's relative
        margin; pass ``bbox_inches=None`` to :meth:`save` to preserve the placement exactly.

    Examples:
        - Stamp a small opaque mark into the lower-right corner:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import Scene
            >>> scene = Scene(figsize=(8, 6))
            >>> logo = np.zeros((40, 80, 4), dtype=np.uint8)
            >>> logo[..., :3] = 255
            >>> logo[..., 3] = 255
            >>> mark_ax = scene.stamp(logo, frac=0.2, shadow=False)
            >>> [round(float(v), 3) for v in mark_ax.get_position().bounds]
            [0.775, 0.025, 0.2, 0.133]
            >>> scene.close()

            ```
    """
    return self.stamp_mark(mark, **kwargs)

set_title(heading, **kwargs) #

Set the panel's title: draw it above the axes, and record it on the figure's description.

Figure-level decoration rather than a layer — it draws straight onto :attr:ax, so removing every layer does not remove it — but described all the same, on this tier's one :class:~digitalearth.base.spec.PanelSpec, the way the 3-D tier has always described its own (ST-18). Until then it reached matplotlib and nothing else: a titled map answered figure_spec.panels[0].title is None, so a figure written down lost its heading and :meth:~digitalearth.static.map.Map.draw_figure had nothing to restore on a round trip through this tier's own description. It is the panel's title, and draw_figure paints it back on the axes; the figure's own heading is its suptitle, described as FigureSpec.title and restored there (M4).

Parameters:

Name Type Description Default
heading str

The text to place above the axes. Normalised by :meth:_recorded_title, so None, "" and any whitespace-only string (" ", " ") are the one request "no title": none is recorded and none is drawn. Anything else is drawn as the text matplotlib renders for it, and recorded as that same text. The drawing was not normalised before, so set_title(" ") painted the spaces and described no title (R2-L5).

required
**kwargs Any

Forwarded to Axes.set_title (fontsize, loc, pad, …). Styling for the drawing only: loc="left" moves where the text is painted and the figure still records the heading, because where a tier paints it is not what travels.

{}

Returns:

Type Description
Self

This scene, so figure decoration reads as one expression. The Core declares

Self

returns="self" for this name and the web tier already answers that way; returning None

Self

here meant the same line chained on one tier and raised on the other (order 27a, #265).

Examples:

  • Set a title and read it back off the axes — and off the figure, which now carries it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Scene
    >>> scene = Scene()
    >>> scene.set_title("Discharge, 2020").ax.get_title()
    'Discharge, 2020'
    >>> scene.figure_spec.panels[0].title
    'Discharge, 2020'
    >>> scene.close()
    
  • loc reaches Axes.set_title through **kwargs, so the text lands on the left title and the centre one stays empty — while the figure records the heading either way:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Scene
    >>> scene = Scene().set_title("Left-aligned", loc="left")
    >>> scene.ax.get_title(loc="left"), scene.ax.get_title()
    ('Left-aligned', '')
    >>> scene.title
    'Left-aligned'
    >>> scene.close()
    
  • The title is not a layer, so removing every layer leaves it on the figure:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth import Map
    >>> depth = Dataset.from_array(
    ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
    ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
    ...     no_data_value=-9999.0,
    ... )
    >>> m = Map(crs=4326)
    >>> _ = m.field(depth, name="depth")
    >>> m.set_title("Depth, m").remove_layer("depth").layer_ids
    []
    >>> m.ax.get_title()
    'Depth, m'
    >>> m.close()
    
  • Because the heading is described, a map rebuilt from its own figure comes back titled:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth import Map
    >>> first = Map(crs=4326).set_title("Depth, m")
    >>> second = Map.from_figure(first.figure_spec)
    >>> second.ax.get_title()
    'Depth, m'
    >>> first.close()
    >>> second.close()
    
Source code in src/digitalearth/static/core/scene.py
def set_title(self, heading: str, **kwargs: Any) -> Self:
    """Set the panel's title: draw it above the axes, and record it on the figure's description.

    Figure-level decoration rather than a layer — it draws straight onto :attr:`ax`, so removing every
    layer does not remove it — but **described** all the same, on this tier's one
    :class:`~digitalearth.base.spec.PanelSpec`, the way the 3-D tier has always described its own
    (ST-18). Until then it reached matplotlib and nothing else: a titled map answered
    ``figure_spec.panels[0].title is None``, so a figure written down lost its heading and
    :meth:`~digitalearth.static.map.Map.draw_figure` had nothing to restore on a round trip through
    this tier's own description. It is the **panel's** title, and `draw_figure` paints it back on the
    axes; the figure's own heading is its ``suptitle``, described as ``FigureSpec.title`` and restored
    there (M4).

    Args:
        heading: The text to place above the axes. Normalised by :meth:`_recorded_title`, so ``None``,
            ``""`` and any whitespace-only string (``"   "``, ``"	"``) are the one request "no
            title": none is recorded **and none is drawn**. Anything else is drawn as the text
            matplotlib renders for it, and recorded as that same text. The drawing was not normalised
            before, so `set_title("   ")` painted the spaces and described no title (R2-L5).
        **kwargs: Forwarded to ``Axes.set_title`` (``fontsize``, ``loc``, ``pad``, …). Styling for the
            drawing only: ``loc="left"`` moves where the text is painted and the figure still records
            the heading, because where a tier paints it is not what travels.

    Returns:
        This scene, so figure decoration reads as one expression. The Core declares
        ``returns="self"`` for this name and the web tier already answers that way; returning ``None``
        here meant the same line chained on one tier and raised on the other (order 27a, #265).

    Examples:
        - Set a title and read it back off the axes — and off the figure, which now carries it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Scene
            >>> scene = Scene()
            >>> scene.set_title("Discharge, 2020").ax.get_title()
            'Discharge, 2020'
            >>> scene.figure_spec.panels[0].title
            'Discharge, 2020'
            >>> scene.close()

            ```
        - ``loc`` reaches ``Axes.set_title`` through ``**kwargs``, so the text lands on the left title
          and the centre one stays empty — while the figure records the heading either way:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Scene
            >>> scene = Scene().set_title("Left-aligned", loc="left")
            >>> scene.ax.get_title(loc="left"), scene.ax.get_title()
            ('Left-aligned', '')
            >>> scene.title
            'Left-aligned'
            >>> scene.close()

            ```
        - The title is not a layer, so removing every layer leaves it on the figure:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth import Map
            >>> depth = Dataset.from_array(
            ...     arr=np.array([[1.0, 2.0], [3.0, 4.0]]),
            ...     geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 2.0, 0.0, -1.0), epsg=4326),
            ...     no_data_value=-9999.0,
            ... )
            >>> m = Map(crs=4326)
            >>> _ = m.field(depth, name="depth")
            >>> m.set_title("Depth, m").remove_layer("depth").layer_ids
            []
            >>> m.ax.get_title()
            'Depth, m'
            >>> m.close()

            ```
        - Because the heading is described, a map rebuilt from its own figure comes back titled:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth import Map
            >>> first = Map(crs=4326).set_title("Depth, m")
            >>> second = Map.from_figure(first.figure_spec)
            >>> second.ax.get_title()
            'Depth, m'
            >>> first.close()
            >>> second.close()

            ```
    """
    # Normalised before the draw as well as after it, so the drawing and the record agree: the four
    # spellings of "no title" are one request, and `set_title("   ")` painted the spaces while
    # recording `None` (R2-L5). `grid(suptitle=)` already normalised its own draw (R1-L4); this is
    # the same rule on the axes. The record is still written *after* the draw, so a `set_title` the
    # axes refuses leaves no record behind.
    recorded = self._recorded_title(heading)
    self.ax.set_title("" if recorded is None else recorded, **kwargs)
    self._title = recorded
    return self

save(path, **kwargs) #

Save the figure to path (bbox_inches="tight" by default).

Parameters:

Name Type Description Default
path str | PathLike[str]

Destination file path; the extension picks the format matplotlib writes.

required
**kwargs Any

Forwarded to Figure.savefig (e.g. dpi, bbox_inches, transparent).

{}

Returns:

Type Description
Path

The path that was written, as a :class:pathlib.Path — every backend's save returns one, so

Path

a caller can chain onto the result without re-deriving it.

Examples:

  • Save a scene and read the written file back off the return value:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import tempfile
    >>> from pathlib import Path
    >>> from digitalearth.static import Scene
    >>> scene = Scene()
    >>> out = scene.save(Path(tempfile.mkdtemp()) / "scene.png")
    >>> out.suffix
    '.png'
    >>> out.exists()
    True
    >>> scene.close()
    
Source code in src/digitalearth/static/core/scene.py
def save(self, path: str | os.PathLike[str], **kwargs: Any) -> Path:
    """Save the figure to ``path`` (``bbox_inches="tight"`` by default).

    Args:
        path: Destination file path; the extension picks the format matplotlib writes.
        **kwargs: Forwarded to ``Figure.savefig`` (e.g. ``dpi``, ``bbox_inches``, ``transparent``).

    Returns:
        The path that was written, as a :class:`pathlib.Path` — every backend's ``save`` returns one, so
        a caller can chain onto the result without re-deriving it.

    Examples:
        - Save a scene and read the written file back off the return value:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import tempfile
            >>> from pathlib import Path
            >>> from digitalearth.static import Scene
            >>> scene = Scene()
            >>> out = scene.save(Path(tempfile.mkdtemp()) / "scene.png")
            >>> out.suffix
            '.png'
            >>> out.exists()
            True
            >>> scene.close()

            ```
    """
    self.fig.savefig(path, **{"bbox_inches": "tight", **kwargs})
    return Path(path)

show() #

Show the figure via matplotlib.pyplot.show.

Returns:

Type Description
None

None. This is the one Core name where this tier does not hand its engine object back. The

None

Core declares returns="engine" for show, and the other three tiers each answer with the

None

object their engine displays: the web tier returns its widget, the interactive tier the

None

composed HoloViews object, and the 3-D tier whatever pyvista.Plotter.show hands back.

None

On those tiers displaying a map produces something. pyplot.show does not — it hands the

None

figure to whatever GUI backend is active and returns nothing — so there is no engine object

None

here to hand over, and inventing one would be inventing it.

Note

Nothing is displayed under a non-interactive backend. On Agg — which the test suite and every headless run use — matplotlib warns FigureCanvasAgg is non-interactive, and thus cannot be shown and the call is otherwise a no-op; use :meth:save there.

Examples:

  • Showing a scene on the headless backend returns nothing and leaves the figure intact, so it can still be saved or closed afterwards:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import warnings
    >>> from digitalearth.static import Scene
    >>> scene = Scene()
    >>> with warnings.catch_warnings():
    ...     warnings.simplefilter("ignore")
    ...     print(scene.show())
    None
    >>> len(scene.fig.axes)
    1
    >>> scene.close()
    
Source code in src/digitalearth/static/core/scene.py
def show(self) -> None:
    """Show the figure via `matplotlib.pyplot.show`.

    Returns:
        `None`. This is the one Core name where this tier does not hand its engine object back. The
        Core declares `returns="engine"` for `show`, and the other three tiers each answer with the
        object their engine displays: the web tier returns its widget, the interactive tier the
        composed HoloViews object, and the 3-D tier whatever `pyvista.Plotter.show` hands back.
        On those tiers displaying a map *produces* something. `pyplot.show` does not — it hands the
        figure to whatever GUI backend is active and returns nothing — so there is no engine object
        here to hand over, and inventing one would be inventing it.

    Note:
        Nothing is displayed under a non-interactive backend. On `Agg` — which the test suite and
        every headless run use — matplotlib warns `FigureCanvasAgg is non-interactive, and thus
        cannot be shown` and the call is otherwise a no-op; use :meth:`save` there.

    Examples:
        - Showing a scene on the headless backend returns nothing and leaves the figure intact, so
          it can still be saved or closed afterwards:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import warnings
            >>> from digitalearth.static import Scene
            >>> scene = Scene()
            >>> with warnings.catch_warnings():
            ...     warnings.simplefilter("ignore")
            ...     print(scene.show())
            None
            >>> len(scene.fig.axes)
            1
            >>> scene.close()

            ```
    """
    plt.show()

close() #

Close the figure and let go of the in-memory data this scene registered.

Two things are released, because a scene holds two kinds of memory. The figure is matplotlib's, and a long run of scenes that never closes one keeps every axes alive. The object table is this package's: it is process-global and holds strong references, so a session that builds maps keeps every dataset they drew until something says otherwise. This is the caller saying so, and it is what with calls on the way out.

Closing twice is harmless, and a scene that drew nothing has nothing to forget.

An object: source in a :attr:figure_spec captured from this scene cannot be opened afterwards — which is what "closed" means for a figure whose data lived only in this process. Save the data and reference it by path to keep such a figure readable.

The figure is closed only when this scene created it. A figure the scene made itself (a bare Map()/Scene(), and so every :meth:from_figure round trip) is closed here; a figure handed in through ax=/fig= is spared, because it belongs to whoever laid it out. This is

371, resolved: a borrowed figure is spared (R2-L12), which brings this into line with#

:meth:~digitalearth.static.globe.textured_globe.TexturedGlobe.close, always gated the same way. The object table and the pick handler are released on every close regardless — see below.

.. warning:: When the scene owns the figure, this closes the entire self.fig. The panels returned by :func:~digitalearth.static.panels.figure.grid share one figure none of them owns (each is built with ax=/fig=), so closing a single panel no longer closes its siblings — and an :meth:~digitalearth.static.builders.inset.InsetMixin.inset locator, drawn on the host's own figure, likewise spares the host when closed. Close the scene that made the figure (or call :meth:save and close it yourself) to take the whole figure down. The pick handler this scene connected comes off on close whether the figure is owned or borrowed, so a closed borrowed-axes scene stops answering clicks even though its figure lives on.

Examples:

  • A scene that drew nothing closes quietly:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static import Scene
    >>> Scene().close()
    
See Also

exit: calls this on the way out of a with block.

Source code in src/digitalearth/static/core/scene.py
def close(self) -> None:
    """Close the figure and let go of the in-memory data this scene registered.

    Two things are released, because a scene holds two kinds of memory. The **figure** is matplotlib's,
    and a long run of scenes that never closes one keeps every axes alive. The **object table** is this
    package's: it is process-global and holds strong references, so a session that builds maps keeps
    every dataset they drew until something says otherwise. This is the caller saying so, and it is what
    ``with`` calls on the way out.

    Closing twice is harmless, and a scene that drew nothing has nothing to forget.

    An ``object:`` source in a :attr:`figure_spec` captured from this scene cannot be opened afterwards
    — which is what "closed" means for a figure whose data lived only in this process. Save the data and
    reference it by path to keep such a figure readable.

    **The figure is closed only when this scene created it.** A figure the scene **made** itself (a
    bare ``Map()``/``Scene()``, and so every :meth:`from_figure` round trip) is closed here; a figure
    handed in through ``ax=``/``fig=`` is **spared**, because it belongs to whoever laid it out. This is
    #371, resolved: a borrowed figure is spared (R2-L12), which brings this into line with
    :meth:`~digitalearth.static.globe.textured_globe.TexturedGlobe.close`, always gated the same way. The
    object table and the pick handler are released on **every** close regardless — see below.

    .. warning::
        When the scene owns the figure, this closes the **entire** ``self.fig``. The panels returned by
        :func:`~digitalearth.static.panels.figure.grid` share **one** figure none of them owns (each is built
        with ``ax=``/``fig=``), so closing a single panel no longer closes its siblings — and an
        :meth:`~digitalearth.static.builders.inset.InsetMixin.inset` locator, drawn on the host's own
        figure, likewise spares the host when closed. Close the scene that **made** the figure (or call
        :meth:`save` and close it yourself) to take the whole figure down. The pick handler this scene
        connected comes off on close whether the figure is owned or borrowed, so a closed borrowed-axes
        scene stops answering clicks even though its figure lives on.

    Examples:
        - A scene that drew nothing closes quietly:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static import Scene
            >>> Scene().close()

            ```

    See Also:
        __exit__: calls this on the way out of a ``with`` block.
    """
    forget_namespace(self._objects_ns)
    self._layer_keys = {}
    self._layer_opts = {}
    self._held_objects = {}
    # A closed figure has no pointer over it, so its click handler goes with it: the canvas outlives
    # `plt.close` as a Python object, and a handler left connected would go on answering for a scene
    # whose data has just been let go (see `on_pick`). This runs on **every** close, owned or borrowed:
    # a borrowed-axes scene still connected its own handler, and that is the scene's to take back.
    self._disconnect_picks()
    self._pick_handlers = []
    # Close the figure only when this scene created it (`_owns_fig`, set in `__init__`). A figure handed
    # in through `ax=`/`fig=` — and so every `grid` panel and every `inset` locator — belongs to whoever
    # laid it out; closing it here tore down the caller's whole figure, which was the #371 footgun. This
    # matches `TexturedGlobe.close`, which has always gated on `_owns_fig`.
    if self._owns_fig:
        plt.close(self.fig)

digitalearth.static.panels.figure.grid(nrows, ncols, *, crs=3857, globe=False, figsize=None, sharex=False, sharey=False, suptitle=None, **kwargs) #

Create an nrows × ncols grid of :class:Map panels sharing one figure.

Each cell of a matplotlib subplot grid is wrapped in a Map (all the same crs/globe), so panels can be drawn on independently while sharing one figure for a single savefig / colorbar / title. sharex/sharey additionally put the panels on one pair of axis scales, and suptitle titles the figure rather than any panel.

The sharing vocabulary is matplotlib's own, not a second one. sharex/sharey are forwarded verbatim to plt.subplots, so they take False (the default — nothing shared), True or "all" (every panel in one group), "row", "col" and "none", and a word outside that list is refused by matplotlib with its own message naming the keyword. There is therefore a global and a per-row/per-column form, and which one you get is the word you pass.

Sharing moves the ticks as well as linking the scales. matplotlib drops the tick labels its sharing makes redundant: sharex="all"/"col" leaves x labels on the bottom row only, and sharey="all"/"row" leaves y labels on the leftmost column only (both measured below). The labels are dropped where sharing makes them redundant along that axis, so sharex="row" and sharey="col" link their groups and leave every panel's labels in place.

Parameters:

Name Type Description Default
nrows int

Number of panel rows.

required
ncols int

Number of panel columns.

required
crs Any

Display CRS for every panel (passed to each Map).

3857
globe bool

When True, every panel is a globe (Map(globe=True)).

False
figsize tuple[float, float] | None

Figure size in inches; None uses the matplotlib default.

None
sharex bool | Literal['all', 'row', 'col', 'none']

How the panels share their x axis — False (default), True/"all", "row", "col" or "none", exactly as plt.subplots reads them, and exactly what the signature's own Literal admits. Sharing links the limits: framing or autoscaling one panel of a group frames every panel in it, which is the point of asking for it, and means a grid whose panels show different regions should leave it off.

False
sharey bool | Literal['all', 'row', 'col', 'none']

The same for the y axis.

False
suptitle str | None

One title over the whole figure (Figure.suptitle). None (default) adds none, and so do "" and " ": a blank heading is the one request "no heading" the panels' own set_title reads it as, rather than an empty Text on the figure. This is not a panel title: every panel's own set_title is untouched, so a shared heading and one caption per panel coexist. Style it by calling fig.suptitle yourself on the returned figure — which each panel describes as its figure's heading either way, since every panel reads the heading off the figure it shares (:attr:~digitalearth.static.core.scene.Scene.figure_spec).

None
**kwargs

Forwarded to each Map (e.g. domain).

{}

Returns:

Type Description
Figure

(fig, maps) — the shared :class:~matplotlib.figure.Figure and the list of Map panels in

list[Map]

row-major (left-to-right, top-to-bottom) order, length nrows * ncols.

Raises:

Type Description
ValueError

from plt.subplots, for a sharex/sharey outside the vocabulary above. The figure is created before matplotlib reads the keyword, so such a refusal leaves that empty figure open and the caller gets no handle to it — close it with plt.close("all") (measured: plt.get_fignums() is [1] after a refused call on a clean state). This is unlike :func:facet, whose own refusals are all raised before any axes exists.

Examples:

  • A 2×2 grid yields four Maps sharing one figure:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(2, 2, crs=4326)
    >>> len(maps)
    4
    >>> all(m.fig is fig for m in maps)
    True
    >>> plt.close(fig)
    
  • Draw on each panel independently (they share the figure):
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(1, 2, crs=4326)
    >>> _ = maps[0].set_title("left")
    >>> _ = maps[1].set_title("right")
    >>> [m.ax.get_title() for m in maps]
    ['left', 'right']
    >>> plt.close(fig)
    
  • Shared axes: framing one panel frames its group, and the redundant tick labels go. In a 2×2 under sharex="all" only the bottom row keeps x tick labels:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(2, 2, crs=4326, sharex="all", sharey="all")
    >>> _ = maps[0].set_bounds([2.0, 3.0, 8.0, 9.0])
    >>> [float(v) for v in maps[3].ax.get_xlim()]
    [2.0, 8.0]
    >>> [m.ax.xaxis.get_tick_params(which="major")["labelbottom"] for m in maps]
    [False, False, True, True]
    >>> [m.ax.yaxis.get_tick_params(which="major")["labelleft"] for m in maps]
    [True, False, True, False]
    >>> plt.close(fig)
    
  • Sharing per row and per column drops no labels at all, because neither makes a label redundant along its own axis:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(2, 2, crs=4326, sharex="row", sharey="col")
    >>> [m.ax.xaxis.get_tick_params(which="major")["labelbottom"] for m in maps]
    [True, True, True, True]
    >>> [m.ax.yaxis.get_tick_params(which="major")["labelleft"] for m in maps]
    [True, True, True, True]
    >>> plt.close(fig)
    
  • Per-column sharing groups the panels of a column — in a 2×2 that is the row-major pair (0, 2) — and a word outside matplotlib's vocabulary is refused by name:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(2, 2, crs=4326, sharex="col")
    >>> group = maps[0].ax.get_shared_x_axes().get_siblings(maps[0].ax)
    >>> sorted(id(ax) for ax in group) == sorted(id(m.ax) for m in (maps[0], maps[2]))
    True
    >>> plt.close(fig)
    >>> import matplotlib.pyplot as plt
    >>> try:
    ...     grid(2, 2, crs=4326, sharex="both")
    ... except ValueError as error:
    ...     print(error)
    'both' is not a valid value for sharex. Supported values are 'all', 'row', 'col', 'none', False, True
    >>> plt.close("all")  # the refused call had already made its figure
    
  • A figure title sits beside the panels' own titles rather than replacing one:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(1, 2, crs=4326, suptitle="rainfall, 2020")
    >>> _ = maps[0].set_title("January")
    >>> [t.get_text() for t in fig.texts], maps[0].ax.get_title()
    (['rainfall, 2020'], 'January')
    >>> plt.close(fig)
    
  • Both headings are described, each in its own place, so a stored figure keeps them (M4):
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static.panels.figure import grid
    >>> fig, maps = grid(1, 2, crs=4326, suptitle="rainfall, 2020")
    >>> _ = maps[0].set_title("January")
    >>> spec = maps[0].figure_spec
    >>> spec.title, spec.panels[0].title
    ('rainfall, 2020', 'January')
    >>> plt.close(fig)
    
Source code in src/digitalearth/static/panels/figure.py
def grid(
    nrows: int,
    ncols: int,
    *,
    crs: Any = 3857,
    globe: bool = False,
    figsize: tuple[float, float] | None = None,
    sharex: bool | Literal["all", "row", "col", "none"] = False,
    sharey: bool | Literal["all", "row", "col", "none"] = False,
    suptitle: str | None = None,
    **kwargs,
) -> tuple[Figure, list[Map]]:
    """Create an ``nrows`` × ``ncols`` grid of :class:`Map` panels sharing one figure.

    Each cell of a ``matplotlib`` subplot grid is wrapped in a ``Map`` (all the same ``crs``/``globe``), so
    panels can be drawn on independently while sharing one figure for a single ``savefig`` / colorbar /
    title. ``sharex``/``sharey`` additionally put the panels on **one pair of axis scales**, and ``suptitle``
    titles the figure rather than any panel.

    **The sharing vocabulary is matplotlib's own, not a second one.** ``sharex``/``sharey`` are forwarded
    verbatim to ``plt.subplots``, so they take ``False`` (the default — nothing shared), ``True`` or
    ``"all"`` (every panel in one group), ``"row"``, ``"col"`` and ``"none"``, and a word outside that list
    is refused by matplotlib with its own message naming the keyword. There is therefore a *global* and a
    *per-row/per-column* form, and which one you get is the word you pass.

    **Sharing moves the ticks as well as linking the scales.** matplotlib drops the tick labels its sharing
    makes redundant: ``sharex="all"``/``"col"`` leaves x labels on the bottom row only, and
    ``sharey="all"``/``"row"`` leaves y labels on the leftmost column only (both measured below). The
    labels are dropped where sharing makes them redundant *along that axis*, so ``sharex="row"`` and
    ``sharey="col"`` link their groups and leave every panel's labels in place.

    Args:
        nrows: Number of panel rows.
        ncols: Number of panel columns.
        crs: Display CRS for every panel (passed to each ``Map``).
        globe: When True, every panel is a globe (``Map(globe=True)``).
        figsize: Figure size in inches; ``None`` uses the matplotlib default.
        sharex: How the panels share their x axis — ``False`` (default), ``True``/``"all"``, ``"row"``,
            ``"col"`` or ``"none"``, exactly as ``plt.subplots`` reads them, and exactly what the
            signature's own ``Literal`` admits. Sharing links the *limits*:
            framing or autoscaling one panel of a group frames every panel in it, which is the point of
            asking for it, and means a grid whose panels show different regions should leave it off.
        sharey: The same for the y axis.
        suptitle: One title over the whole figure (``Figure.suptitle``). ``None`` (default) adds none,
            and so do ``""`` and ``"   "``: a blank heading is the one request "no heading" the panels'
            own ``set_title`` reads it as, rather than an empty ``Text`` on the figure.
            This is **not** a panel title: every panel's own ``set_title`` is untouched, so a shared
            heading and one caption per panel coexist. Style it by calling ``fig.suptitle`` yourself on
            the returned figure — which each panel describes as its figure's heading either way, since
            every panel reads the heading off the figure it shares
            (:attr:`~digitalearth.static.core.scene.Scene.figure_spec`).
        **kwargs: Forwarded to each ``Map`` (e.g. ``domain``).

    Returns:
        ``(fig, maps)`` — the shared :class:`~matplotlib.figure.Figure` and the list of ``Map`` panels in
        row-major (left-to-right, top-to-bottom) order, length ``nrows * ncols``.

    Raises:
        ValueError: from ``plt.subplots``, for a ``sharex``/``sharey`` outside the vocabulary above. The
            figure is created before matplotlib reads the keyword, so such a refusal leaves that empty
            figure open and the caller gets no handle to it — close it with `plt.close("all")` (measured:
            `plt.get_fignums()` is `[1]` after a refused call on a clean state). This is unlike
            :func:`facet`, whose own refusals are all raised before any axes exists.

    Examples:
        - A 2×2 grid yields four Maps sharing one figure:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(2, 2, crs=4326)
            >>> len(maps)
            4
            >>> all(m.fig is fig for m in maps)
            True
            >>> plt.close(fig)

            ```
        - Draw on each panel independently (they share the figure):
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(1, 2, crs=4326)
            >>> _ = maps[0].set_title("left")
            >>> _ = maps[1].set_title("right")
            >>> [m.ax.get_title() for m in maps]
            ['left', 'right']
            >>> plt.close(fig)

            ```
        - Shared axes: framing one panel frames its group, and the redundant tick labels go. In a 2×2
          under ``sharex="all"`` only the bottom row keeps x tick labels:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(2, 2, crs=4326, sharex="all", sharey="all")
            >>> _ = maps[0].set_bounds([2.0, 3.0, 8.0, 9.0])
            >>> [float(v) for v in maps[3].ax.get_xlim()]
            [2.0, 8.0]
            >>> [m.ax.xaxis.get_tick_params(which="major")["labelbottom"] for m in maps]
            [False, False, True, True]
            >>> [m.ax.yaxis.get_tick_params(which="major")["labelleft"] for m in maps]
            [True, False, True, False]
            >>> plt.close(fig)

            ```
        - Sharing per row and per column drops no labels at all, because neither makes a label redundant
          along its own axis:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(2, 2, crs=4326, sharex="row", sharey="col")
            >>> [m.ax.xaxis.get_tick_params(which="major")["labelbottom"] for m in maps]
            [True, True, True, True]
            >>> [m.ax.yaxis.get_tick_params(which="major")["labelleft"] for m in maps]
            [True, True, True, True]
            >>> plt.close(fig)

            ```
        - Per-column sharing groups the panels of a column — in a 2×2 that is the row-major pair
          ``(0, 2)`` — and a word outside matplotlib's vocabulary is refused by name:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(2, 2, crs=4326, sharex="col")
            >>> group = maps[0].ax.get_shared_x_axes().get_siblings(maps[0].ax)
            >>> sorted(id(ax) for ax in group) == sorted(id(m.ax) for m in (maps[0], maps[2]))
            True
            >>> plt.close(fig)
            >>> import matplotlib.pyplot as plt
            >>> try:
            ...     grid(2, 2, crs=4326, sharex="both")
            ... except ValueError as error:
            ...     print(error)
            'both' is not a valid value for sharex. Supported values are 'all', 'row', 'col', 'none', False, True
            >>> plt.close("all")  # the refused call had already made its figure

            ```
        - A figure title sits beside the panels' own titles rather than replacing one:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(1, 2, crs=4326, suptitle="rainfall, 2020")
            >>> _ = maps[0].set_title("January")
            >>> [t.get_text() for t in fig.texts], maps[0].ax.get_title()
            (['rainfall, 2020'], 'January')
            >>> plt.close(fig)

            ```
        - Both headings are described, each in its own place, so a stored figure keeps them (M4):
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static.panels.figure import grid
            >>> fig, maps = grid(1, 2, crs=4326, suptitle="rainfall, 2020")
            >>> _ = maps[0].set_title("January")
            >>> spec = maps[0].figure_spec
            >>> spec.title, spec.panels[0].title
            ('rainfall, 2020', 'January')
            >>> plt.close(fig)

            ```
    """
    fig, axs = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey)
    axes = np.atleast_1d(axs).ravel()
    maps = [Map(crs=crs, globe=globe, ax=ax, fig=fig, **kwargs) for ax in axes]
    # Through the panels' own normaliser, not a guard of its own: `None`, `""` and `"   "` are the one
    # request "no heading" on this tier (ST-18), and a bare `is not None` put an empty `Text` on the figure
    # where `set_title("")` draws and records none (L4).
    heading = Scene._recorded_title(suptitle)
    if heading is not None:
        fig.suptitle(heading)
    return fig, maps

digitalearth.static.panels.figure.shared_colorbar(fig, mappable, maps=None, *, label=None, **kwargs) #

Add one colorbar to fig spanning the given panels (or every axes when maps is None).

Parameters:

Name Type Description Default
fig Figure

The figure created by :func:grid.

required
mappable Any

A drawn mappable (e.g. an AxesImage / QuadMesh returned by a panel's field) whose colour scale the bar represents. None is accepted and adds no bar, since a layer whose data lies outside the display CRS draws nothing and so has no scale to represent.

required
maps list[Map] | None

Panels the colorbar should steal space from; None spans all of the figure's axes.

None
label str | None

Optional colorbar label.

None
**kwargs

Forwarded to Figure.colorbar (e.g. orientation, shrink, fraction).

{}

Returns:

Name Type Description
The Any

class:~matplotlib.colorbar.Colorbar added to the figure, or None when mappable is

Any

None — there is no colour scale to draw a bar for.

Examples:

  • One bar across both panels of a grid. It is an axes of its own, so the figure gains one, and the scale it shows is the mappable's — reached by name through Map.artist, never the renderer's private record:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from digitalearth.static import grid, shared_colorbar
    >>> fig, maps = grid(1, 2, crs=4326)
    >>> values = np.arange(16.0).reshape(4, 4)
    >>> for panel in maps:
    ...     _ = panel.field(values, vmin=0.0, vmax=15.0)
    >>> len(fig.axes)
    2
    >>> bar = shared_colorbar(fig, maps[0].artist(maps[0].layer_ids[-1]), maps, label="mm/day")
    >>> len(fig.axes), bar.ax.get_ylabel(), bar.mappable.get_clim()
    (3, 'mm/day', (0.0, 15.0))
    >>> plt.close(fig)
    
  • A panel whose layer drew nothing has no mappable to key, so passing None adds no bar and no axes rather than raising — which is what lets :func:facet call this unconditionally:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> from digitalearth.static import grid, shared_colorbar
    >>> fig, maps = grid(1, 2, crs=4326)
    >>> print(shared_colorbar(fig, None, maps))
    None
    >>> len(fig.axes)
    2
    >>> plt.close(fig)
    
See Also

grid: builds the figure and panels this spans. facet: resolves one scale over a whole stack and calls this for the bar.

Source code in src/digitalearth/static/panels/figure.py
def shared_colorbar(
    fig: Figure,
    mappable: Any,
    maps: list[Map] | None = None,
    *,
    label: str | None = None,
    **kwargs,
) -> Any:
    """Add one colorbar to ``fig`` spanning the given panels (or every axes when ``maps`` is ``None``).

    Args:
        fig: The figure created by :func:`grid`.
        mappable: A drawn mappable (e.g. an ``AxesImage`` / ``QuadMesh`` returned by a panel's ``field``)
            whose colour scale the bar represents. ``None`` is accepted and adds no bar, since a layer
            whose data lies outside the display CRS draws nothing and so has no scale to represent.
        maps: Panels the colorbar should steal space from; ``None`` spans all of the figure's axes.
        label: Optional colorbar label.
        **kwargs: Forwarded to ``Figure.colorbar`` (e.g. ``orientation``, ``shrink``, ``fraction``).

    Returns:
        The :class:`~matplotlib.colorbar.Colorbar` added to the figure, or ``None`` when ``mappable`` is
        ``None`` — there is no colour scale to draw a bar for.

    Examples:
        - One bar across both panels of a grid. It is an axes of its own, so the figure gains one, and the
            scale it shows is the mappable's — reached by name through `Map.artist`, never the renderer's
            private record:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from digitalearth.static import grid, shared_colorbar
            >>> fig, maps = grid(1, 2, crs=4326)
            >>> values = np.arange(16.0).reshape(4, 4)
            >>> for panel in maps:
            ...     _ = panel.field(values, vmin=0.0, vmax=15.0)
            >>> len(fig.axes)
            2
            >>> bar = shared_colorbar(fig, maps[0].artist(maps[0].layer_ids[-1]), maps, label="mm/day")
            >>> len(fig.axes), bar.ax.get_ylabel(), bar.mappable.get_clim()
            (3, 'mm/day', (0.0, 15.0))
            >>> plt.close(fig)

            ```
        - A panel whose layer drew nothing has no mappable to key, so passing `None` adds no bar and no
            axes rather than raising — which is what lets :func:`facet` call this unconditionally:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> from digitalearth.static import grid, shared_colorbar
            >>> fig, maps = grid(1, 2, crs=4326)
            >>> print(shared_colorbar(fig, None, maps))
            None
            >>> len(fig.axes)
            2
            >>> plt.close(fig)

            ```

    See Also:
        grid: builds the figure and panels this spans.
        facet: resolves one scale over a whole stack and calls this for the bar.
    """
    if mappable is None:  # the layer it would describe was never drawn (e.g. off-limb)
        return None
    axes = [m.ax for m in maps] if maps is not None else None
    cbar = fig.colorbar(mappable, ax=axes, **kwargs)
    if label is not None:
        cbar.set_label(label)
    return cbar