Skip to content

PlotlyPlotWidget

PlotlyPlotWidget is a reusable scientific plot: continuous scattergl traces, sparse marker overlays, editable measurement lines/pairs, x-range callbacks, and a right-click display menu.

PlotlyPlotWidget demo

Embed

from nicewidgets.plotly_plot.widget import PlotlyPlotWidget
from nicewidgets.plotly_plot.display_options import PlotlyPlotDisplayOptions

plot = PlotlyPlotWidget(
    x_label='Time (s)',
    y_label='Normalized intensity',
    display_options=PlotlyPlotDisplayOptions(show_legend=True, theme='light'),
    on_x_range_changed=lambda x0, x1: print(x0, x1),
)
# Required: give the root a real height (do not leave only h-full).
plot.container.classes(remove='h-full')
plot.container.classes(add='w-full h-96')

plot.add_trace(name='signal', x=[0.0, 1.0, 2.0], y=[1.0, 1.2, 0.9])
plot.plot_scatter(name='peaks', x=[1.0], y=[1.2])
plot.add_measurement_line(name='threshold', orientation='horizontal', value=1.1)

X-span event overlays live on plot.events (see unit tests in tests/nicewidgets/test_plotly_plot_widget.py and the public PlotlyEventOverlayApi).

Hosting height and first-navigation blank plots: Layout and sizing.

Demo: examples/plotly_plot/ (also /plotly in the combined demo).

Configuration

PlotlyPlotDisplayOptions controls theme, legend, axis-label visibility, toolbar, and hover. The widget stores a private copy; context-menu toggles mutate that copy.

API

nicewidgets.plotly_plot.widget.PlotlyPlotWidget

Interactive Plotly plotting widget for NiceGUI.

This widget provides a reusable plotting interface for scientific traces, sparse marker overlays, editable measurement lines, and x-axis range synchronization. It intentionally hides Plotly layout-shape details from parent NiceGUI applications.

Hosting notes
  • Size the root via plot.container after construction (for example plot.container.classes("w-full h-96")). The widget does not set a default height; without sizing the plot can render at zero height.
  • X-span event overlays live on the events sub-API (:class:~nicewidgets.plotly_plot.event_overlay.PlotlyEventOverlayApi), not on the series methods below. See unit tests in tests/nicewidgets/test_plotly_plot_widget.py and :class:~nicewidgets.plotly_plot.event_overlay.PlotlyEventOverlayApi.
  • Import from submodules, for example from nicewidgets.plotly_plot.widget import PlotlyPlotWidget.

See examples/plotly_plot for a runnable demo of the core host API.

Source code in src/nicewidgets/plotly_plot/widget.py
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
class PlotlyPlotWidget:
    """Interactive Plotly plotting widget for NiceGUI.

    This widget provides a reusable plotting interface for scientific traces,
    sparse marker overlays, editable measurement lines, and x-axis range
    synchronization. It intentionally hides Plotly layout-shape details from
    parent NiceGUI applications.

    Hosting notes:
        - Size the root via ``plot.container`` after construction (for example
          ``plot.container.classes("w-full h-96")``). The widget does not set a
          default height; without sizing the plot can render at zero height.
        - X-span event overlays live on the ``events`` sub-API
          (:class:`~nicewidgets.plotly_plot.event_overlay.PlotlyEventOverlayApi`),
          not on the series methods below. See unit tests in
          ``tests/nicewidgets/test_plotly_plot_widget.py`` and
          :class:`~nicewidgets.plotly_plot.event_overlay.PlotlyEventOverlayApi`.
        - Import from submodules, for example
          ``from nicewidgets.plotly_plot.widget import PlotlyPlotWidget``.

    See ``examples/plotly_plot`` for a runnable demo of the core host API.
    """

    def __init__(
        self,
        *,
        x_label: str = "x",
        y_label: str = "y",
        y2_label: str = "",
        display_options: PlotlyPlotDisplayOptions | None = None,
        on_x_range_changed: OnPlotlyXRangeChanged | None = None,
        on_x_range_selected: OnPlotlyXRangeSelected | None = None,
        on_measurement_changed: OnMeasurementChanged | None = None,
        on_series_visibility_changed: OnSeriesVisibilityChanged | None = None,
        on_build_context_menu: Callable[[PlotlyPlotWidget], None] | None = None,
        layout_margins_profile: PlotlyLayoutMarginsProfile | None = None,
    ) -> None:
        """Create an empty Plotly widget.

        The constructor builds the NiceGUI DOM immediately. After construction,
        size ``self.container`` before relying on a visible plot area.

        Args:
            x_label: X-axis label.
            y_label: Primary left y-axis label.
            y2_label: Secondary right y-axis label used when a visible right-axis
                trace or scatter is present.
            display_options: Initial display options (theme, legend, axis-label,
                toolbar, and hover visibility). Defaults to
                :class:`PlotlyPlotDisplayOptions` defaults. The widget owns a
                private copy; later context-menu toggles mutate the copy.
            on_x_range_changed: Optional callback invoked after the user changes
                the x-axis range by zooming, panning, or autoranging. ``(None,
                None)`` means Plotly returned to autorange.
            on_x_range_selected: Optional callback invoked once after the user
                completes a box-select while ``begin_select_x_range()`` is armed.
            on_measurement_changed: Optional callback invoked after the user
                drags a measurement line.
            on_series_visibility_changed: Optional callback invoked after a
                context-menu series visibility toggle.
            on_build_context_menu: Optional callback invoked while rebuilding the
                right-click context menu, after built-in display toggles and
                before Copy To Clipboard. Callers may add arbitrary
                ``ui.menu_item`` / separator entries (same pattern as
                ``TableWidget`` / ``TreeWidget``).
            layout_margins_profile: Optional fixed margin profile for aligned
                multi-plot stacks.
        """
        self._x_label = str(x_label)
        self._y_label = str(y_label)
        self._y2_label = str(y2_label)
        self._layout_margins_profile = layout_margins_profile
        self._display_options = replace(display_options or PlotlyPlotDisplayOptions())
        self._theme = normalize_plotly_theme(self._display_options.theme)
        self._display_options.theme = self._theme
        self._placeholder_text: str | None = None
        self._on_x_range_changed = on_x_range_changed
        self._on_x_range_selected = on_x_range_selected
        self._on_measurement_changed = on_measurement_changed
        self._on_series_visibility_changed = on_series_visibility_changed
        self._on_build_context_menu = on_build_context_menu
        self._x_range = PlotlyAxisRange()
        self._series_menu_items: list[PlotlySeriesMenuItem] = []
        self._series_visibility: dict[str, bool] = {}
        self._figure = build_plotly_figure_dict(
            x_label=self._x_label,
            y_label=self._y_label,
            x_range=self._x_range,
            theme=self._theme,
            show_x_axis_labels=self._display_options.show_x_axis_labels,
            show_y_axis_labels=self._display_options.show_y_axis_labels,
            show_legend=self._display_options.show_legend,
            show_plotly_toolbar=self._display_options.show_plotly_toolbar,
        )
        self._series_order: list[_SeriesRef] = []
        self._traces: dict[str, PlotlyTraceData] = {}
        self._scatters: dict[str, PlotlyScatterData] = {}
        self._measurements: dict[str, MeasurementLine | MeasurementPair] = {}
        self._shape_refs: list[_ShapeRef] = []
        self._measurement_callbacks: dict[str, OnMeasurementChanged] = {}
        self._last_applied_x_range: tuple[float | None, float | None] | None = None
        self._ignore_relayout = False
        self._x_range_selection_armed = False
        self._pending_self_relayouts: list[dict[str, object]] = []
        self._ctx_menu: ui.context_menu | None = None
        self._context_menu_builder: PlotlyPlotContextMenu | None = None
        self.events = PlotlyEventOverlayApi(self)
        if self._layout_margins_profile is not None:
            self._sync_margins_to_plotly_dict()
            self._sync_axis_stabilization_to_plotly_dict()

        with ui.element("div").classes(
            "relative w-full h-full min-h-0 nw-plotly-plot"
        ) as self.container:
            self._plot_element = ui.plotly(self._figure).classes("w-full h-full min-h-0")
            with ui.element("div").classes(
                "absolute inset-0 flex items-center justify-center pointer-events-none px-4"
            ) as self._placeholder_container:
                self._placeholder_label = ui.label("").classes("text-sm opacity-70 text-center")
        self._placeholder_container.set_visibility(False)
        self._ensure_measurement_drag_css()
        self._plot_element.on("plotly_relayout", self._on_plotly_relayout)
        self._plot_element.on("plotly_doubleclick", self._on_plotly_doubleclick)
        self._ctx_menu = ui.context_menu()
        self._context_menu_builder = PlotlyPlotContextMenu(get_widget=lambda: self)
        self._plot_element.on("contextmenu", self._on_context_menu_event)
        if is_pywebview_desktop():
            ui.timer(0.05, self._install_pywebview_context_menu_guards, once=True)

    @staticmethod
    def _ensure_measurement_drag_css() -> None:
        """Disable Plotly shape vertex handles so line bodies drag as a unit.

        Plotly's shape editor exposes endpoint circles. Dragging a circle moves
        one endpoint and looks like a broken diagonal / “first point” drag.
        Measurement H/V lines should translate as one axis-aligned segment.
        Source: Plotly community guidance for ``config.edits.shapePosition``
        (disable pointer events on shape vertex circles).

        Returns:
            None.
        """
        ui.add_head_html(
            """
<style id="nw-plotly-measurement-drag-css">
/* Prefer dragging the line body, not endpoint vertex circles. */
.nw-plotly-plot .js-plotly-plot .draglayer circle,
.nw-plotly-plot .js-plotly-plot g.draglayer circle {
  pointer-events: none !important;
}
</style>
""",
            shared=True,
        )

    @property
    def display_options(self) -> PlotlyPlotDisplayOptions:
        """Return mutable display options used by context-menu actions."""
        return self._display_options

    @property
    def placeholder_text(self) -> str | None:
        """Return the current centered placeholder message, if any."""
        return self._placeholder_text

    def set_placeholder_text(self, message: str | None) -> None:
        """Show or hide centered placeholder text over the plot area.

        Args:
            message: Human-readable empty-state text, or ``None`` to hide the
                placeholder overlay.

        Returns:
            None.
        """
        clean = str(message).strip() if message is not None else ""
        if not clean:
            self._placeholder_text = None
            self._placeholder_container.set_visibility(False)
            return
        self._placeholder_text = clean
        self._placeholder_label.text = clean
        self._placeholder_container.set_visibility(True)

    @property
    def series_menu_items(self) -> tuple[PlotlySeriesMenuItem, ...]:
        """Return registered trace/scatter context-menu items."""
        return tuple(self._series_menu_items)

    @property
    def on_build_context_menu(self) -> Callable[[PlotlyPlotWidget], None] | None:
        """Return optional callback that adds custom context-menu items."""
        return self._on_build_context_menu

    def set_on_build_context_menu(
        self,
        callback: Callable[[PlotlyPlotWidget], None] | None,
    ) -> None:
        """Set or clear the custom context-menu build callback.

        Args:
            callback: Invoked while rebuilding the right-click menu, or ``None``.

        Returns:
            None.
        """
        self._on_build_context_menu = callback

    def register_series_menu_items(self, items: Sequence[PlotlySeriesMenuItem]) -> None:
        """Register trace/scatter items shown in the right-click context menu.

        Existing visibility choices are preserved for series names that were
        registered previously in this widget instance.

        Args:
            items: Menu item definitions keyed by stable series names.

        Returns:
            None.
        """
        self._series_menu_items = list(items)
        for item in items:
            if item.series_name not in self._series_visibility:
                self._series_visibility[item.series_name] = bool(item.default_visible)

    def is_series_visible(self, series_name: str) -> bool:
        """Return whether one registered or loaded series is visible.

        Args:
            series_name: Stable trace or scatter overlay name.

        Returns:
            True when the series should render in the plot.
        """
        clean = str(series_name).strip()
        if clean in self._series_visibility:
            return bool(self._series_visibility[clean])
        return True

    def set_series_visible(self, series_name: str, visible: bool) -> None:
        """Set visibility for one loaded trace or scatter overlay.

        Args:
            series_name: Existing trace or scatter overlay name.
            visible: Whether the series should be visible.

        Raises:
            KeyError: If the series does not exist in the current figure.
        """
        clean = str(series_name).strip()
        self._series_visibility[clean] = bool(visible)
        if clean in self._traces:
            current = self._traces[clean]
            data = PlotlyTraceData.from_sequences(
                name=clean,
                x=current.x,
                y=current.y,
                visible=bool(visible),
                y_axis=current.y_axis,
                line_color=current.line_color,
                line_dash=current.line_dash,
            )
            self._traces[clean] = data
            index = self._series_index(clean, "trace")
            trace = self._trace_to_plotly(data)
            self._figure["data"][index] = trace
            self._restyle_plotly_trace(index, trace)
            self._refresh_yaxis2_layout()
            self._pin_x_axis_after_series_update()
            return
        if clean in self._scatters:
            current = self._scatters[clean]
            data = PlotlyScatterData.from_sequences(
                name=clean,
                x=current.x,
                y=current.y,
                visible=bool(visible),
                y_axis=current.y_axis,
            )
            self._scatters[clean] = data
            index = self._series_index(clean, "scatter")
            trace = self._scatter_to_plotly(data)
            self._figure["data"][index] = trace
            self._restyle_plotly_trace(index, trace)
            self._refresh_yaxis2_layout()
            self._pin_x_axis_after_series_update()
            return
        raise KeyError(f"series {clean!r} does not exist")

    def set_series_visible_state(self, series_name: str, visible: bool) -> None:
        """Set desired visibility for a series that may not be loaded yet.

        Unlike :meth:`set_series_visible`, this never raises for an unknown
        series. When the series is already loaded it restyles immediately;
        otherwise the visibility is stored and applied the next time the series
        is added. This supports restoring visibility before plot data exists
        (for example on reconnect hydrate).

        Args:
            series_name: Trace or scatter overlay name.
            visible: Whether the series should be visible.

        Returns:
            None.
        """
        clean = str(series_name).strip()
        if clean in self._traces or clean in self._scatters:
            self.set_series_visible(clean, visible)
            return
        self._series_visibility[clean] = bool(visible)

    def set_y2_label(self, label: str) -> None:
        """Set the secondary right y-axis title text.

        Decorations appear only when y-axis labels are enabled and at least one
        right-axis trace or scatter is visible.

        Args:
            label: Y2 axis title, or ``""`` to clear.

        Returns:
            None.
        """
        self._y2_label = str(label)
        if self._has_yaxis2():
            self._refresh_yaxis2_layout()

    def set_x_label(self, label: str) -> None:
        """Set the primary x-axis title text.

        Args:
            label: X-axis title, or ``""`` to clear.

        Returns:
            None.
        """
        self._set_primary_axis_label(axis_name="xaxis", label=str(label), attr="_x_label")

    def set_y_label(self, label: str) -> None:
        """Set the primary left y-axis title text.

        Args:
            label: Y-axis title, or ``""`` to clear.

        Returns:
            None.
        """
        self._set_primary_axis_label(axis_name="yaxis", label=str(label), attr="_y_label")

    def _set_primary_axis_label(self, *, axis_name: str, label: str, attr: str) -> None:
        """Update one primary axis title in memory and optionally relayout."""
        setattr(self, attr, label)
        layout = self._figure.setdefault("layout", {})
        axis = layout.setdefault(axis_name, {})
        if not isinstance(axis, dict):
            axis = {}
            layout[axis_name] = axis
        title = axis.setdefault("title", {})
        if not isinstance(title, dict):
            title = {}
            axis["title"] = title
        visible = (
            bool(self._display_options.show_x_axis_labels)
            if axis_name == "xaxis"
            else bool(self._display_options.show_y_axis_labels)
        )
        title["text"] = label if visible else ""
        if visible:
            self._relayout({f"{axis_name}.title.text": label})

    def _any_axis_labels_visible(self) -> bool:
        """Return whether any axis decorations are visible for margin layout."""
        return any_axis_labels_visible(
            show_x_axis_labels=self._display_options.show_x_axis_labels,
            show_y_axis_labels=self._display_options.show_y_axis_labels,
        )

    def toggle_series_visible(self, series_name: str) -> bool:
        """Toggle visibility for one registered trace or scatter overlay.

        Args:
            series_name: Stable trace or scatter overlay name.

        Returns:
            Visibility after the toggle.

        Raises:
            KeyError: If ``series_name`` is not a registered menu item.
        """
        clean = str(series_name).strip()
        if not any(item.series_name == clean for item in self._series_menu_items):
            raise KeyError(f"series {clean!r} is not registered in the context menu")
        new_visible = not self.is_series_visible(clean)
        if clean in self._traces or clean in self._scatters:
            self.set_series_visible(clean, new_visible)
        else:
            self._series_visibility[clean] = new_visible
        if self._on_series_visibility_changed is not None:
            self._on_series_visibility_changed(clean, new_visible)
        return new_visible

    def set_x_axis_labels_visible(self, visible: bool) -> None:
        """Show or hide x-axis title text, ticks, lines, and grid lines.

        Args:
            visible: Whether x-axis decorations should be visible.

        Returns:
            None.
        """
        self._display_options.show_x_axis_labels = bool(visible)
        self._sync_axis_labels_to_plotly_dict()
        self._sync_margins_to_plotly_dict()
        self._sync_axis_stabilization_to_plotly_dict()
        self._relayout_axis_labels_and_margins()

    def set_y_axis_labels_visible(self, visible: bool) -> None:
        """Show or hide left and right y-axis title text, ticks, lines, and grid lines.

        Args:
            visible: Whether y-axis decorations should be visible.

        Returns:
            None.
        """
        self._display_options.show_y_axis_labels = bool(visible)
        self._sync_axis_labels_to_plotly_dict()
        self._sync_margins_to_plotly_dict()
        self._sync_axis_stabilization_to_plotly_dict()
        self._relayout_axis_labels_and_margins()

    def set_plotly_toolbar_visible(self, visible: bool) -> None:
        """Set Plotly modebar visibility.

        Args:
            visible: Whether Plotly's modebar should be visible.

        Returns:
            None.
        """
        self._display_options.show_plotly_toolbar = bool(visible)
        self._sync_plotly_config_to_plotly_dict()
        self._react_plotly_config()

    def set_hover_info_visible(self, visible: bool) -> None:
        """Set Plotly hover-info visibility for all plot traces.

        Args:
            visible: Whether hover info should be visible.

        Returns:
            None.
        """
        self._display_options.show_hover_info = bool(visible)
        self._sync_hover_info_to_plotly_dict()
        self._restyle_hover_info()

    def set_legend_visible(self, visible: bool) -> None:
        """Show or hide the Plotly legend.

        When shown, the legend uses the widget's bottom horizontal layout
        (``orientation='h'`` centered below the plot).

        Args:
            visible: Whether the legend should be visible.

        Returns:
            None.
        """
        self._display_options.show_legend = bool(visible)
        self._sync_legend_to_plotly_dict()
        self._sync_margins_to_plotly_dict()
        self._relayout_legend()

    async def copy_plot_to_clipboard(self) -> None:
        """Copy the current Plotly plot image to the active clipboard.

        Native desktop mode uses ``pyperclipimg``. Browser mode uses the
        Clipboard API with a Plotly PNG export.

        Returns:
            None.
        """
        try:
            if is_pywebview_desktop():
                png_bytes = await get_plotly_png_bytes(self._plot_element)
                copy_png_bytes_to_native_clipboard(png_bytes)
            else:
                await copy_plotly_png_to_browser_clipboard(self._plot_element)
            ui.notify("Plot copied to clipboard.", type="positive")
        except Exception as exc:
            logger.exception("Failed to copy Plotly plot to clipboard.")
            ui.notify(f"Copy failed: {exc}", type="negative")

    def _on_context_menu_event(self, _event: Any) -> None:
        """Rebuild and open the Plotly plot context menu."""
        if self._ctx_menu is None or self._context_menu_builder is None:
            return
        with self._ctx_menu.clear():
            self._context_menu_builder.build()
        self._ctx_menu.open()

    def _install_pywebview_context_menu_guards(self) -> None:
        """Install desktop-only capture listeners so secondary taps open the menu."""
        js = pywebview_plotly_plot_context_menu_guard_js(plot_id=self._plot_element.id)
        try:
            self._plot_element.client.run_javascript(js, timeout=2.0)
        except RuntimeError:
            logger.debug("Could not install pywebview context-menu guards; client unavailable.")

    @property
    def figure(self) -> dict[str, Any]:
        """Return the current Plotly figure dictionary."""
        return self._figure

    def add_trace(
        self,
        *,
        name: str,
        x: Sequence[float],
        y: Sequence[float],
        visible: bool = True,
        y_axis: PlotlyYAxisSide = "left",
        line_color: str | None = None,
        line_dash: str | None = None,
    ) -> None:
        """Add a named continuous ``scattergl`` line trace.

        Args:
            name: Stable caller-defined trace name.
            x: X-axis values (non-empty; equal length to ``y``).
            y: Y-axis values (non-empty; equal length to ``x``).
            visible: Whether the trace should be visible.
            y_axis: Primary ``y`` axis (``"left"``) or overlaid ``y2`` axis
                (``"right"``). Right-axis traces create ``layout.yaxis2``.
            line_color: Optional Plotly line color (CSS color string or Plotly
                color, for example ``"#1f77b4"`` or ``"rgb(31,119,180)"``).
            line_dash: Optional Plotly dash style: ``"solid"``, ``"dot"``,
                ``"dash"``, ``"longdash"``, ``"dashdot"``, or ``"longdashdot"``.

        Raises:
            ValueError: If the name already exists or data are invalid.
        """
        clean = _validate_unique_name(name, self._traces.get(str(name).strip()), label="trace")
        axis = _normalize_y_axis_side(y_axis)
        data = PlotlyTraceData.from_sequences(
            name=clean,
            x=x,
            y=y,
            visible=visible,
            y_axis=axis,
            line_color=line_color,
            line_dash=line_dash,
        )
        self._traces[clean] = data
        self._series_order.append(_SeriesRef(name=clean, kind="trace"))
        self._sync_yaxis2_from_series()
        trace = self._trace_to_plotly(data)
        self._figure["data"].append(trace)
        self._add_plotly_trace(trace)

    def update_trace(
        self,
        *,
        name: str,
        x: Sequence[float],
        y: Sequence[float],
        visible: bool | None = None,
    ) -> None:
        """Replace data for an existing named continuous trace.

        Args:
            name: Existing trace name.
            x: Replacement X-axis values.
            y: Replacement Y-axis values.
            visible: Optional replacement visibility. When ``None``, the
                existing visibility is preserved.

        Raises:
            KeyError: If the trace does not exist.
            ValueError: If replacement data are invalid.
        """
        clean = str(name).strip()
        current = self._traces.get(clean)
        if current is None:
            raise KeyError(f"trace {clean!r} does not exist")
        data = PlotlyTraceData.from_sequences(
            name=clean,
            x=x,
            y=y,
            visible=current.visible if visible is None else visible,
            y_axis=current.y_axis,
            line_color=current.line_color,
            line_dash=current.line_dash,
        )
        self._traces[clean] = data
        index = self._series_index(clean, "trace")
        trace = self._trace_to_plotly(data)
        self._figure["data"][index] = trace
        self._restyle_plotly_trace(index, trace)

    def remove_trace(self, name: str) -> None:
        """Remove a named continuous trace.

        Args:
            name: Existing trace name.

        Raises:
            KeyError: If the trace does not exist.
        """
        clean = str(name).strip()
        index = self._series_index(clean, "trace")
        self._traces.pop(clean)
        self._series_order.pop(index)
        self._figure["data"].pop(index)
        self._delete_plotly_trace(index)
        self._sync_yaxis2_from_series()

    def clear_traces(self) -> None:
        """Remove all continuous traces while preserving scatter overlays."""
        for name in list(self._traces):
            self.remove_trace(name)

    def plot_scatter(
        self,
        *,
        name: str,
        x: Sequence[float],
        y: Sequence[float],
        visible: bool = True,
        y_axis: PlotlyYAxisSide = "left",
    ) -> None:
        """Add a named sparse ``scattergl`` marker overlay.

        Scatter overlays are excluded from :meth:`reset_x_axis_limits` fitting so
        marker padding does not shift the derived line-trace x extent.

        Args:
            name: Stable caller-defined scatter overlay name.
            x: X-axis values (non-empty; equal length to ``y``).
            y: Y-axis values (non-empty; equal length to ``x``).
            visible: Whether the scatter overlay should be visible.
            y_axis: Primary ``y`` axis (``"left"``) or overlaid ``y2`` axis
                (``"right"``). Right-axis scatters create ``layout.yaxis2``.

        Raises:
            ValueError: If the name already exists or data are invalid.
        """
        clean = _validate_unique_name(
            name,
            self._scatters.get(str(name).strip()),
            label="scatter",
        )
        axis = _normalize_y_axis_side(y_axis)
        data = PlotlyScatterData.from_sequences(
            name=clean, x=x, y=y, visible=visible, y_axis=axis
        )
        self._scatters[clean] = data
        self._series_order.append(_SeriesRef(name=clean, kind="scatter"))
        self._sync_yaxis2_from_series()
        trace = self._scatter_to_plotly(data)
        self._figure["data"].append(trace)
        self._add_plotly_trace(trace)

    def update_scatter(
        self,
        *,
        name: str,
        x: Sequence[float],
        y: Sequence[float],
        visible: bool | None = None,
    ) -> None:
        """Replace data for an existing named scatter overlay.

        Args:
            name: Existing scatter overlay name.
            x: Replacement X-axis values.
            y: Replacement Y-axis values.
            visible: Optional replacement visibility. When ``None``, the
                existing visibility is preserved.

        Raises:
            KeyError: If the scatter overlay does not exist.
            ValueError: If replacement data are invalid.
        """
        clean = str(name).strip()
        current = self._scatters.get(clean)
        if current is None:
            raise KeyError(f"scatter {clean!r} does not exist")
        data = PlotlyScatterData.from_sequences(
            name=clean,
            x=x,
            y=y,
            visible=current.visible if visible is None else visible,
            y_axis=current.y_axis,
        )
        self._scatters[clean] = data
        index = self._series_index(clean, "scatter")
        trace = self._scatter_to_plotly(data)
        self._figure["data"][index] = trace
        self._restyle_plotly_trace(index, trace)

    def remove_scatter(self, name: str) -> None:
        """Remove a named scatter overlay.

        Args:
            name: Existing scatter overlay name.

        Raises:
            KeyError: If the scatter overlay does not exist.
        """
        clean = str(name).strip()
        index = self._series_index(clean, "scatter")
        self._scatters.pop(clean)
        self._series_order.pop(index)
        self._figure["data"].pop(index)
        self._delete_plotly_trace(index)
        self._sync_yaxis2_from_series()

    def clear_scatters(self) -> None:
        """Remove all scatter overlays while preserving continuous traces."""
        for name in list(self._scatters):
            self.remove_scatter(name)

    def set_series(
        self,
        *,
        traces: Sequence[PlotlyTraceData] = (),
        scatters: Sequence[PlotlyScatterData] = (),
    ) -> None:
        """Replace all continuous traces and scatter overlays in one browser update.

        Measurement lines and layout shapes are preserved. Existing incremental
        ``add_trace`` / ``plot_scatter`` callers remain available; prefer this
        method when rebuilding the full plot contents at once.

        Args:
            traces: Replacement continuous traces.
            scatters: Replacement scatter overlays.

        Returns:
            None.
        """
        self._traces = {}
        self._scatters = {}
        self._series_order = []
        plotly_data: list[dict[str, Any]] = []
        for data in traces:
            visible = self.is_series_visible(data.name)
            stored = PlotlyTraceData(
                name=data.name,
                x=data.x,
                y=data.y,
                visible=visible,
                y_axis=data.y_axis,
                line_color=data.line_color,
                line_dash=data.line_dash,
            )
            self._traces[stored.name] = stored
            self._series_order.append(_SeriesRef(name=stored.name, kind="trace"))
            plotly_data.append(self._trace_to_plotly(stored))
        for data in scatters:
            visible = self.is_series_visible(data.name)
            stored = PlotlyScatterData(
                name=data.name,
                x=data.x,
                y=data.y,
                visible=visible,
                y_axis=data.y_axis,
            )
            self._scatters[stored.name] = stored
            self._series_order.append(_SeriesRef(name=stored.name, kind="scatter"))
            plotly_data.append(self._scatter_to_plotly(stored))
        self._figure["data"] = plotly_data
        self._sync_hover_info_to_plotly_dict()
        self._sync_yaxis2_from_series()
        self._push_series_data()
        self._pin_x_axis_after_series_update()
        if plotly_data:
            self.set_placeholder_text(None)

    @staticmethod
    def _finite_x_values(values: Sequence[float]) -> list[float]:
        """Return finite x samples from one trace sequence."""
        return [float(value) for value in values if math.isfinite(value)]

    def _derive_x_range_from_visible_line_traces(self) -> tuple[float, float] | None:
        """Return the x extent of visible continuous line traces.

        Scatter overlays are excluded so marker padding does not expand the
        displayed x-axis when the logical range is automatic.
        """
        xs: list[float] = []
        for trace in self._traces.values():
            if not trace.visible:
                continue
            xs.extend(self._finite_x_values(trace.x))
        if not xs:
            return None
        return min(xs), max(xs)

    def _push_x_axis_range_to_browser(self, x_min: float, x_max: float) -> None:
        """Apply x-axis limits to the local figure dict and browser."""
        xaxis = self._figure["layout"].setdefault("xaxis", {})
        xaxis["range"] = [float(x_min), float(x_max)]
        xaxis["autorange"] = False
        self._relayout({"xaxis.range": [float(x_min), float(x_max)], "xaxis.autorange": False})

    def _pin_x_axis_after_series_update(self) -> None:
        """Pin x-axis limits after trace replacement.

        When the logical range is automatic, derive limits from visible line
        traces only. Scatter marker traces otherwise expand autorange padding.
        """
        x_min, x_max = self._x_range.x_min, self._x_range.x_max
        if x_min is None or x_max is None:
            derived = self._derive_x_range_from_visible_line_traces()
            if derived is None:
                return
            x_min, x_max = derived
        self._push_x_axis_range_to_browser(x_min, x_max)

    def set_theme(self, theme: PlotlyThemeName) -> None:
        """Set the Plotly light/dark layout theme.

        Args:
            theme: Theme name, either ``'light'`` or ``'dark'``.

        Returns:
            None.
        """
        self._theme = normalize_plotly_theme(theme)
        self._display_options.theme = self._theme
        self._sync_theme_to_plotly_dict()
        self._relayout_theme()
        # Relayout JS no-ops when the graph is not mounted yet (SPA first paint).
        self._plot_element.update()

    def set_dark_mode(self, enabled: bool) -> None:
        """Set the Plotly layout theme from a dark-mode flag.

        Args:
            enabled: Whether dark mode is enabled.

        Returns:
            None.
        """
        self.set_theme("dark" if enabled else "light")

    def set_x_axis_limits(self, x_min: float | None, x_max: float | None) -> None:
        """Set x-axis limits programmatically.

        Args:
            x_min: Minimum x-axis value, or ``None`` for automatic scaling.
            x_max: Maximum x-axis value, or ``None`` for automatic scaling.

        Raises:
            ValueError: If both bounds are set and ``x_min >= x_max``.
        """
        new_range = (x_min, x_max)
        if _x_range_equal(new_range, (self._x_range.x_min, self._x_range.x_max)):
            self._last_applied_x_range = new_range
            return
        self._x_range = PlotlyAxisRange(x_min=x_min, x_max=x_max)
        self._last_applied_x_range = new_range
        xaxis = self._figure["layout"].setdefault("xaxis", {})
        if x_min is None or x_max is None:
            xaxis.pop("range", None)
            xaxis["autorange"] = True
            self._relayout({"xaxis.autorange": True})
            return
        xaxis["range"] = [float(x_min), float(x_max)]
        xaxis["autorange"] = False
        self._relayout({"xaxis.range": [float(x_min), float(x_max)], "xaxis.autorange": False})

    def reset_x_axis_limits(self) -> None:
        """Reset the x-axis to the full extent of visible line traces.

        When line traces are present, limits are derived from continuous traces
        only so scatter marker padding does not shift x=0. With no line traces,
        falls back to Plotly autorange.
        """
        derived = self._derive_x_range_from_visible_line_traces()
        if derived is not None:
            self._x_range = PlotlyAxisRange(x_min=None, x_max=None)
            self._last_applied_x_range = (None, None)
            self._push_x_axis_range_to_browser(*derived)
            return
        self.set_x_axis_limits(None, None)

    @property
    def x_range_limits(self) -> tuple[float | None, float | None]:
        """Return the widget's current logical x-axis limits."""
        return (self._x_range.x_min, self._x_range.x_max)

    def begin_select_x_range(self) -> None:
        """Enter one-shot box-select mode for user x-range selection.

        While armed, ``plotly_relayout`` payloads carrying ``selections`` x-bounds
        invoke ``on_x_range_selected`` once, then restore zoom mode.
        """
        self._x_range_selection_armed = True
        layout = self._figure.setdefault("layout", {})
        layout["dragmode"] = "select"
        self._relayout({"dragmode": "select"}, source="begin_select_x_range")

    def cancel_select_x_range(self) -> None:
        """Cancel box-select mode and restore zoom dragmode."""
        self._x_range_selection_armed = False
        layout = self._figure.setdefault("layout", {})
        layout["dragmode"] = "zoom"
        layout["selections"] = []
        self._relayout(
            {"dragmode": "zoom", "selections": []},
            source="cancel_select_x_range",
        )

    def add_measurement_line(
        self,
        *,
        name: str,
        orientation: str,
        value: float,
        visible: bool = True,
        y_axis: PlotlyYAxisSide = "left",
        editable: bool = True,
        color: str | None = None,
        dash: str = "dash",
        show_legend: bool = False,
        legend_label: str | None = None,
        on_changed: OnMeasurementChanged | None = None,
    ) -> MeasurementLine:
        """Add a horizontal or vertical measurement line.

        Args:
            name: Stable caller-defined measurement name.
            orientation: ``horizontal``/``h`` or ``vertical``/``v``.
            value: Initial line position in data coordinates.
            visible: Whether the line should be visible.
            y_axis: Y-axis for horizontal lines. ``"right"`` requires an
                existing ``layout.yaxis2`` from a right-axis trace or scatter.
            editable: Whether the user can drag the line.
            color: Plotly line color. ``None`` uses a theme-aware default.
            dash: Plotly dash style (``"solid"``, ``"dot"``, ``"dash"``, ...).
            show_legend: Whether the line appears in the Plotly legend.
            legend_label: Legend text when ``show_legend`` is True. Defaults to
                ``name``.
            on_changed: Optional per-measurement callback. Ignored when
                ``editable`` is False.

        Returns:
            Mutable measurement line object owned by the widget.

        Raises:
            ValueError: If the name already exists, orientation is invalid, or
                a right-axis horizontal line is requested before ``yaxis2`` exists.
        """
        clean = _validate_unique_name(
            name,
            self._measurements.get(str(name).strip()),
            label="measurement",
        )
        normalized = _normalize_orientation(orientation)
        axis = _normalize_y_axis_side(y_axis)
        if normalized == "vertical":
            axis = "left"
        elif axis == "right" and not self._has_yaxis2():
            raise ValueError(
                "cannot add right-axis measurement before a right-axis trace or scatter exists"
            )
        line_color = color if color is not None else self._default_measurement_color()
        line = MeasurementLine(
            name=clean,
            orientation=normalized,
            position=float(value),
            visible=bool(visible),
            y_axis=axis,
            editable=bool(editable),
            color=line_color,
            dash=str(dash),
            show_legend=bool(show_legend),
            legend_label=legend_label,
        )
        self._measurements[clean] = line
        if on_changed is not None and line.editable:
            self._measurement_callbacks[clean] = on_changed
        self._append_measurement_shape(
            clean,
            "line",
            1,
            normalized,
            float(value),
            visible,
            axis,
            editable=line.editable,
            color=line.color,
            dash=line.dash,
            show_legend=line.show_legend,
            legend_label=line.legend_label or clean,
        )
        self._push_shapes()
        return line

    def remove_measurement_line(self, name: str) -> None:
        """Remove a single-line measurement.

        Args:
            name: Existing single-line measurement name.

        Raises:
            KeyError: If the measurement does not exist.
            ValueError: If the measurement is a pair.
        """
        self._remove_measurement(name, expected_kind="line")

    def add_measurement_pair(
        self,
        *,
        name: str,
        orientation: str,
        value1: float,
        value2: float,
        visible: bool = True,
        y_axis: PlotlyYAxisSide = "left",
        on_changed: OnMeasurementChanged | None = None,
    ) -> MeasurementPair:
        """Add a draggable pair of horizontal or vertical measurement lines.

        Args:
            name: Stable caller-defined measurement-pair name.
            orientation: ``horizontal``/``h`` or ``vertical``/``v``.
            value1: Initial first-line position in data coordinates.
            value2: Initial second-line position in data coordinates.
            visible: Whether both lines should be visible.
            y_axis: Y-axis for horizontal lines. ``"right"`` requires an
                existing ``layout.yaxis2`` from a right-axis trace or scatter.
            on_changed: Optional per-measurement callback.

        Returns:
            Mutable measurement pair object owned by the widget.

        Raises:
            ValueError: If the name already exists, orientation is invalid, or
                a right-axis horizontal pair is requested before ``yaxis2`` exists.
        """
        clean = _validate_unique_name(
            name,
            self._measurements.get(str(name).strip()),
            label="measurement",
        )
        normalized = _normalize_orientation(orientation)
        axis = _normalize_y_axis_side(y_axis)
        if normalized == "vertical":
            axis = "left"
        elif axis == "right" and not self._has_yaxis2():
            raise ValueError(
                "cannot add right-axis measurement before a right-axis trace or scatter exists"
            )
        pair = MeasurementPair(
            name=clean,
            orientation=normalized,
            position1=float(value1),
            position2=float(value2),
            visible=bool(visible),
            y_axis=axis,
        )
        self._measurements[clean] = pair
        if on_changed is not None:
            self._measurement_callbacks[clean] = on_changed
        self._append_measurement_shape(
            clean, "pair", 1, normalized, float(value1), visible, axis
        )
        self._append_measurement_shape(
            clean, "pair", 2, normalized, float(value2), visible, axis
        )
        self._push_shapes()
        return pair

    def remove_measurement_pair(self, name: str) -> None:
        """Remove a paired-line measurement.

        Args:
            name: Existing measurement-pair name.

        Raises:
            KeyError: If the measurement does not exist.
            ValueError: If the measurement is a single line.
        """
        self._remove_measurement(name, expected_kind="pair")

    def _series_index(self, name: str, kind: _SeriesKind) -> int:
        """Return the current Plotly trace index for a named series."""
        for index, ref in enumerate(self._series_order):
            if ref.name == name and ref.kind == kind:
                return index
        raise KeyError(f"{kind} {name!r} does not exist")

    def _has_yaxis2(self) -> bool:
        """Return whether the figure layout currently defines ``yaxis2``."""
        layout = self._figure.get("layout", {})
        return isinstance(layout, dict) and "yaxis2" in layout

    def _has_right_axis_series(self) -> bool:
        """Return whether any trace or scatter is bound to the right y-axis."""
        return any(trace.y_axis == "right" for trace in self._traces.values()) or any(
            scatter.y_axis == "right" for scatter in self._scatters.values()
        )

    def _has_visible_right_axis_series(self) -> bool:
        """Return whether any visible trace or scatter uses the right y-axis."""
        return any(trace.y_axis == "right" and trace.visible for trace in self._traces.values()) or any(
            scatter.y_axis == "right" and scatter.visible for scatter in self._scatters.values()
        )

    def _yaxis2_decorations_visible(self) -> bool:
        """Return whether right y-axis title, ticks, and line should show."""
        return bool(self._display_options.show_y_axis_labels) and self._has_visible_right_axis_series()

    def _sync_yaxis2_from_series(self) -> None:
        """Create or remove ``layout.yaxis2`` based on right-axis traces/scatters."""
        if self._has_right_axis_series():
            self._ensure_yaxis2()
        else:
            self._maybe_remove_yaxis2()

    def _refresh_yaxis2_layout(self) -> None:
        """Update ``yaxis2`` decorations and right margin after visibility changes."""
        if self._has_right_axis_series():
            if not self._has_yaxis2():
                self._ensure_yaxis2()
                return
            layout = self._figure.setdefault("layout", {})
            layout["yaxis2"] = self._build_yaxis2_dict()
            self._sync_margins_to_plotly_dict()
            self._relayout_secondary_y_axis()
        else:
            self._maybe_remove_yaxis2()

    def _build_yaxis2_dict(self) -> dict[str, Any]:
        """Return a Plotly ``yaxis2`` layout dictionary for the current theme."""
        theme = theme_for_name(self._theme)
        visible = self._yaxis2_decorations_visible()
        yaxis2: dict[str, Any] = {
            "overlaying": "y",
            "side": "right",
            "autorange": True,
            "color": theme.axis_color,
            "linecolor": theme.axis_color,
            "tickcolor": theme.axis_color,
            "gridcolor": theme.grid_color,
            "zerolinecolor": theme.zero_line_color,
        }
        apply_axis_decorations(yaxis2, label_text=self._y2_label, visible=visible)
        return yaxis2

    def _ensure_yaxis2(self) -> None:
        """Ensure ``layout.yaxis2`` exists and matches current display options."""
        layout = self._figure.setdefault("layout", {})
        layout["yaxis2"] = self._build_yaxis2_dict()
        self._sync_margins_to_plotly_dict()
        self._relayout_secondary_y_axis()

    def _maybe_remove_yaxis2(self) -> None:
        """Remove ``layout.yaxis2`` when no right-axis traces or scatters remain."""
        if self._has_right_axis_series() or not self._has_yaxis2():
            return
        layout = self._figure.setdefault("layout", {})
        layout.pop("yaxis2", None)
        self._sync_margins_to_plotly_dict()
        self._relayout(
            {
                "yaxis2": None,
                "margin": dict(
                    layout.get(
                        "margin",
                        resolve_plot_layout_margins(
                            show_axis_labels=self._any_axis_labels_visible(),
                            show_legend=self._display_options.show_legend,
                            layout_margins_profile=self._layout_margins_profile,
                        ),
                    )
                ),
            },
            source="remove_yaxis2",
        )

    def _relayout_secondary_y_axis(self) -> None:
        """Push ``yaxis2`` and margin layout changes to the browser."""
        layout = self._figure.get("layout", {})
        yaxis2 = layout.get("yaxis2")
        if not isinstance(yaxis2, dict):
            return
        relayout: dict[str, Any] = {
            "yaxis2": yaxis2,
            "margin": dict(
                layout.get(
                    "margin",
                    resolve_plot_layout_margins(
                        show_axis_labels=self._any_axis_labels_visible(),
                        show_legend=self._display_options.show_legend,
                        has_yaxis2=self._yaxis2_decorations_visible(),
                        layout_margins_profile=self._layout_margins_profile,
                    ),
                )
            ),
        }
        self._relayout(relayout, source="yaxis2")

    def _remove_measurement(self, name: str, *, expected_kind: _MeasurementKind) -> None:
        """Remove a measurement and all associated Plotly shapes."""
        clean = str(name).strip()
        measurement = self._measurements.get(clean)
        if measurement is None:
            raise KeyError(f"measurement {clean!r} does not exist")
        is_pair = isinstance(measurement, MeasurementPair)
        if expected_kind == "pair" and not is_pair:
            raise ValueError(f"measurement {clean!r} is not a pair")
        if expected_kind == "line" and is_pair:
            raise ValueError(f"measurement {clean!r} is not a single line")
        self._measurements.pop(clean)
        self._measurement_callbacks.pop(clean, None)
        keep_shapes: list[dict[str, Any]] = []
        keep_refs: list[_ShapeRef] = []
        for shape, ref in zip(self._shapes(), self._shape_refs, strict=True):
            if ref.name == clean:
                continue
            keep_shapes.append(shape)
            keep_refs.append(ref)
        self._figure["layout"]["shapes"] = keep_shapes
        self._shape_refs = keep_refs
        self._push_shapes()

    def _trace_to_plotly(self, data: PlotlyTraceData) -> dict[str, Any]:
        """Return a Plotly ``scattergl`` line trace dictionary."""
        hoverinfo = "all" if self._display_options.show_hover_info else "skip"
        trace: dict[str, Any] = {
            "type": "scattergl",
            "mode": "lines",
            "name": data.name,
            "x": list(data.x),
            "y": list(data.y),
            "visible": True if data.visible else False,
            "hoverinfo": hoverinfo,
        }
        if data.line_color is not None or data.line_dash is not None:
            line: dict[str, str] = {}
            if data.line_color is not None:
                line["color"] = data.line_color
            if data.line_dash is not None:
                line["dash"] = data.line_dash
            trace["line"] = line
        if data.y_axis == "right":
            trace["yaxis"] = "y2"
        return trace

    def _scatter_to_plotly(self, data: PlotlyScatterData) -> dict[str, Any]:
        """Return a Plotly ``scattergl`` marker trace dictionary."""
        hoverinfo = "all" if self._display_options.show_hover_info else "skip"
        trace: dict[str, Any] = {
            "type": "scattergl",
            "mode": "markers",
            "name": data.name,
            "x": list(data.x),
            "y": list(data.y),
            "visible": True if data.visible else False,
            "hoverinfo": hoverinfo,
            "cliponaxis": True,
            "marker": {"size": 8},
        }
        if data.y_axis == "right":
            trace["yaxis"] = "y2"
        return trace

    def _append_measurement_shape(
        self,
        name: str,
        kind: _MeasurementKind,
        line_number: int,
        orientation: PlotlyLineOrientation,
        value: float,
        visible: bool,
        y_axis: PlotlyYAxisSide = "left",
        *,
        editable: bool = True,
        color: str | None = None,
        dash: str = "dash",
        show_legend: bool = False,
        legend_label: str | None = None,
    ) -> None:
        """Append one Plotly layout shape for a measurement line."""
        shape = self._line_shape(
            orientation=orientation,
            value=value,
            visible=visible,
            y_axis=y_axis,
            editable=editable,
            color=color if color is not None else self._default_measurement_color(),
            dash=dash,
            show_legend=show_legend,
            legend_label=legend_label or name,
        )
        self._shapes().append(shape)
        self._shape_refs.append(_ShapeRef(name=name, kind=kind, line_number=line_number))

    def _default_measurement_color(self) -> str:
        """Return a high-contrast measurement line color for the current theme.

        Returns:
            Plotly color string.
        """
        return theme_for_name(self._theme).font_color

    def _line_shape(
        self,
        *,
        orientation: PlotlyLineOrientation,
        value: float,
        visible: bool,
        y_axis: PlotlyYAxisSide = "left",
        editable: bool = True,
        color: str,
        dash: str = "dash",
        show_legend: bool = False,
        legend_label: str,
    ) -> dict[str, Any]:
        """Build one Plotly line shape."""
        line_style = {"width": 3, "dash": str(dash), "color": str(color)}
        if orientation == "horizontal":
            shape: dict[str, Any] = {
                "type": "line",
                "xref": "paper",
                "x0": 0,
                "x1": 1,
                "yref": "y2" if y_axis == "right" else "y",
                "y0": value,
                "y1": value,
                "visible": bool(visible),
                "editable": bool(editable),
                "line": line_style,
            }
        else:
            shape = {
                "type": "line",
                "xref": "x",
                "x0": value,
                "x1": value,
                "yref": "paper",
                "y0": 0,
                "y1": 1,
                "visible": bool(visible),
                "editable": bool(editable),
                "line": line_style,
            }
        # Omit legend keys unless requested. Shape legend/name can change Plotly
        # edit interaction away from whole-shape drag under shapePosition.
        if show_legend:
            shape["name"] = str(legend_label)
            shape["showlegend"] = True
        return shape

    def _shapes(self) -> list[dict[str, Any]]:
        """Return the mutable layout shape list."""
        layout = self._figure.setdefault("layout", {})
        shapes = layout.setdefault("shapes", [])
        if not isinstance(shapes, list):
            raise TypeError("Plotly layout.shapes must be a list")
        return shapes

    def _register_self_relayout(
        self,
        payload: dict[str, object],
        *,
        source: str,
        echo_suppressions: int = 1,
    ) -> None:
        """Register a self-initiated relayout payload for short-lived echo suppression.

        Args:
            payload: Relayout key/value pairs expected back from Plotly.
            source: Short label for debugging.
            echo_suppressions: Matching relayout callbacks to suppress before drop.

        Returns:
            None.
        """
        now = time.perf_counter()
        expires_at = now + _SELF_RELAYOUT_TTL_SEC
        self._pending_self_relayouts = [
            item
            for item in self._pending_self_relayouts
            if float(item["expires_at"]) >= now
        ]
        self._pending_self_relayouts.append(
            {
                "source": source,
                "expected": dict(payload),
                "expires_at": expires_at,
                "remaining": max(1, int(echo_suppressions)),
            }
        )

    def _pop_matching_self_relayout(self, args: dict[str, object]) -> str | None:
        """Match incoming relayout to a pending self-initiated payload.

        Args:
            args: Incoming Plotly relayout payload.

        Returns:
            Source label when matched, otherwise ``None``.
        """
        now = time.perf_counter()
        self._pending_self_relayouts = [
            item
            for item in self._pending_self_relayouts
            if float(item["expires_at"]) >= now
        ]
        for idx, item in enumerate(self._pending_self_relayouts):
            expected = item["expected"]
            if not isinstance(expected, dict):
                continue
            if all(args.get(key) == value for key, value in expected.items()):
                source = str(item["source"])
                remaining = int(item.get("remaining", 1)) - 1
                if remaining <= 0:
                    self._pending_self_relayouts.pop(idx)
                else:
                    self._pending_self_relayouts[idx]["remaining"] = remaining
                return source
        return None

    def _handle_x_range_selection_relayout(self, args: dict[str, Any]) -> bool:
        """Consume a box-select relayout while selection mode is armed.

        Args:
            args: Plotly relayout event payload.

        Returns:
            ``True`` when the payload was handled as a completed selection.
        """
        if not self._x_range_selection_armed:
            return False
        x0, x1 = extract_rect_selection_x_range_from_relayout(args)
        if x0 is None or x1 is None:
            return False
        self._x_range_selection_armed = False
        layout = self._figure.setdefault("layout", {})
        layout["dragmode"] = "zoom"
        layout["selections"] = []
        self._relayout(
            {"dragmode": "zoom", "selections": []},
            source="selection_complete",
        )
        if self._on_x_range_selected is not None:
            self._on_x_range_selected(float(x0), float(x1))
        return True

    def _should_emit_user_x_range_relayout(self, args: dict[str, Any]) -> bool:
        """Return whether ``args`` looks like a user x-axis range gesture."""
        if self._parse_x_range_event(args) is None:
            return False
        if args.get("xaxis.autorange") is True:
            return True
        if not _relayout_has_axis_range(args):
            return False
        if _is_normalized_only_relayout(args):
            return False
        return _relayout_has_bracket_axis_range(args)

    def _on_plotly_relayout(self, event: Any) -> None:
        """Handle Plotly relayout events from user zooms, selections, and shape drags."""
        args = getattr(event, "args", None)
        if not isinstance(args, dict):
            return

        # logger.info("plotly_relayout args=%s", args)

        if self._ignore_relayout:
            return
        if self._pop_matching_self_relayout(args) is not None:
            return
        if self._handle_x_range_selection_relayout(args):
            return
        self._sync_shape_edits(args)
        if self._should_emit_user_x_range_relayout(args):
            self._emit_x_range_if_needed(args)

    def _on_plotly_doubleclick(self, event: Any) -> None:
        """Reset x-axis limits after Plotly double-click autorange.

        Args:
            event: NiceGUI double-click event (unused).
        """
        _ = event
        self.reset_x_axis_limits()
        if self._on_x_range_changed is not None:
            self._on_x_range_changed(None, None)

    def _emit_x_range_if_needed(self, args: dict[str, Any]) -> None:
        """Emit x-range callback for user axis range changes."""
        parsed = self._parse_x_range_event(args)
        if parsed is None:
            return
        if self._is_x_range_echo(parsed):
            return
        xaxis = self._figure["layout"].setdefault("xaxis", {})
        x_min, x_max = parsed
        if x_min is None or x_max is None:
            xaxis.pop("range", None)
            xaxis["autorange"] = True
        else:
            xaxis["range"] = [x_min, x_max]
            xaxis["autorange"] = False
        if self._on_x_range_changed is not None:
            self._on_x_range_changed(x_min, x_max)
        self._last_applied_x_range = parsed

    def _is_x_range_echo(
        self, new_range: tuple[float | None, float | None]
    ) -> bool:
        """Return whether ``new_range`` echoes the last programmatic apply.

        Args:
            new_range: Candidate ``(x_min, x_max)`` from a relayout event.

        Returns:
            ``True`` when both values match the last applied pair within
            tolerance.
        """
        last = self._last_applied_x_range
        if last is None:
            return False
        return _x_range_equal(last, new_range)

    @staticmethod
    def _parse_x_range_event(args: dict[str, Any]) -> tuple[float | None, float | None] | None:
        """Parse a Plotly relayout payload for x-axis range changes.

        Args:
            args: Plotly relayout event payload.

        Returns:
            ``(x_min, x_max)``, ``(None, None)`` for autorange, or ``None``
            when the event does not describe an x-axis range change.
        """
        if args.get("xaxis.autorange") is True:
            return (None, None)
        if "xaxis.range" in args:
            value = args["xaxis.range"]
            if isinstance(value, Sequence) and len(value) == 2:
                return (float(value[0]), float(value[1]))
        if "xaxis.range[0]" in args and "xaxis.range[1]" in args:
            return (float(args["xaxis.range[0]"]), float(args["xaxis.range[1]"]))
        return None

    def _sync_shape_edits(self, args: dict[str, Any]) -> None:
        """Mirror user-dragged shape coordinates and emit measurement callbacks."""
        changed_indices = self._shape_indices_from_relayout(args)
        if not changed_indices:
            return
        shapes = self._shapes()
        needs_shape_push = False
        for index in changed_indices:
            if index >= len(shapes) or index >= len(self._shape_refs):
                continue
            shape = shapes[index]
            self._apply_shape_args(shape, index, args)
            ref = self._shape_refs[index]
            measurement = self._measurements.get(ref.name)
            if measurement is None:
                continue
            if isinstance(measurement, MeasurementLine) and not measurement.editable:
                continue
            position = self._measurement_position_after_edit(
                shape,
                measurement.orientation,
                index=index,
                args=args,
            )
            if isinstance(measurement, MeasurementLine):
                measurement.position = position
                self._normalize_measurement_shape(shape, measurement)
                needs_shape_push = True
                event = MeasurementChangeEvent(
                    name=measurement.name,
                    kind="line",
                    orientation=measurement.orientation,
                    position=position,
                    y_axis=measurement.y_axis,
                )
            else:
                if ref.line_number == 1:
                    measurement.position1 = position
                else:
                    measurement.position2 = position
                event = MeasurementChangeEvent(
                    name=measurement.name,
                    kind="pair",
                    orientation=measurement.orientation,
                    position=position,
                    position1=measurement.position1,
                    position2=measurement.position2,
                    delta=measurement.delta,
                    y_axis=measurement.y_axis,
                )
            self._emit_measurement_changed(event)
        if needs_shape_push:
            self._push_shapes()

    @staticmethod
    def _shape_indices_from_relayout(args: dict[str, Any]) -> set[int]:
        """Return shape indices touched by a relayout payload."""
        indices: set[int] = set()
        for key in args:
            if key.startswith("shapes["):
                close = key.find("]")
                if close > len("shapes["):
                    try:
                        indices.add(int(key[len("shapes[") : close]))
                    except ValueError:
                        continue
        if not indices and isinstance(args.get("shapes"), list):
            indices.update(range(len(args["shapes"])))
        return indices

    @staticmethod
    def _apply_shape_args(shape: dict[str, Any], index: int, args: dict[str, Any]) -> None:
        """Apply relayout payload shape keys to one local shape dictionary."""
        full_shapes = args.get("shapes")
        if isinstance(full_shapes, list) and index < len(full_shapes) and isinstance(full_shapes[index], dict):
            shape.clear()
            shape.update(full_shapes[index])
            return
        prefix = f"shapes[{index}]."
        for key, value in args.items():
            if key.startswith(prefix):
                shape[key[len(prefix) :]] = value

    @staticmethod
    def _shape_position(shape: dict[str, Any], orientation: PlotlyLineOrientation) -> float:
        """Return the data-coordinate position for a Plotly line shape."""
        if orientation == "horizontal":
            y0 = float(shape.get("y0", shape.get("y1", 0.0)))
            y1 = float(shape.get("y1", y0))
            return (y0 + y1) / 2.0
        x0 = float(shape.get("x0", shape.get("x1", 0.0)))
        x1 = float(shape.get("x1", x0))
        return (x0 + x1) / 2.0

    @classmethod
    def _measurement_position_after_edit(
        cls,
        shape: dict[str, Any],
        orientation: PlotlyLineOrientation,
        *,
        index: int,
        args: dict[str, Any],
    ) -> float:
        """Return the post-drag position for a measurement line.

        Plotly line shapes expose two endpoints. Vertex drags often update only
        ``y0`` or only ``y1`` (or ``x0`` / ``x1``). Prefer the endpoint value(s)
        present in the relayout payload so dragging either handle moves the
        line; then callers normalize back to a single axis-aligned line.

        Args:
            shape: Shape dict after :meth:`_apply_shape_args`.
            orientation: Line orientation.
            index: Shape index in ``layout.shapes``.
            args: Raw Plotly relayout payload.

        Returns:
            Data-coordinate position for the measurement.
        """
        prefix = f"shapes[{index}]."
        if orientation == "horizontal":
            keys = (f"{prefix}y0", f"{prefix}y1")
        else:
            keys = (f"{prefix}x0", f"{prefix}x1")
        changed = [float(args[key]) for key in keys if key in args]
        if len(changed) == 1:
            return changed[0]
        if len(changed) == 2:
            return (changed[0] + changed[1]) / 2.0
        return cls._shape_position(shape, orientation)

    @staticmethod
    def _normalize_measurement_shape(
        shape: dict[str, Any],
        measurement: MeasurementLine,
    ) -> None:
        """Keep single-line measurements axis-aligned after a drag.

        Args:
            shape: Mutable Plotly shape dict that was edited.
            measurement: Owning measurement line.

        Returns:
            None.
        """
        position = float(measurement.position)
        if measurement.orientation == "horizontal":
            shape["y0"] = position
            shape["y1"] = position
            # Keep full-width paper span so the line stays a true H-line.
            shape["xref"] = "paper"
            shape["x0"] = 0
            shape["x1"] = 1
            return
        shape["x0"] = position
        shape["x1"] = position
        shape["yref"] = "paper"
        shape["y0"] = 0
        shape["y1"] = 1

    def _emit_measurement_changed(self, event: MeasurementChangeEvent) -> None:
        """Invoke global and per-measurement callbacks for a measurement change."""
        callback = self._measurement_callbacks.get(event.name)
        if callback is not None:
            callback(event)
        if self._on_measurement_changed is not None:
            self._on_measurement_changed(event)

    def _js_plotly_graph_div(self) -> str:
        """Return JavaScript that resolves this NiceGUI Plotly graph div."""
        plot_id = self._plot_element.id
        return f"""const host = getElement({plot_id}).$el;
if (!host) return;
const plotDiv = host.querySelector('.js-plotly-plot') || host;
if (!plotDiv || !plotDiv.data) return;
"""

    def _add_plotly_trace(self, trace: dict[str, Any]) -> None:
        """Push a newly added trace to the browser.

        Incremental ``Plotly.addTraces`` is used when the live graph exists.
        Also sync via NiceGUI ``update()``: on first SPA navigation into a page
        that builds traces during construction, the graph div is often not
        mounted yet and the JS path no-ops, which previously left an empty
        chart despite a populated Python figure dict.
        """
        js = f"""
{self._js_plotly_graph_div()}
Plotly.addTraces(plotDiv, [{json.dumps(trace)}]);
"""
        self._run_plotly_javascript(js)
        self._plot_element.update()

    def _restyle_plotly_trace(self, index: int, trace: dict[str, Any]) -> None:
        """Push trace replacement values to the browser with ``Plotly.restyle``."""
        restyle = {key: [value] for key, value in trace.items() if key != "type"}
        js = f"""
{self._js_plotly_graph_div()}
Plotly.restyle(plotDiv, {json.dumps(restyle)}, [{index}]);
"""
        self._run_plotly_javascript(js)
        self._plot_element.update()

    def _delete_plotly_trace(self, index: int) -> None:
        """Remove one Plotly trace from the browser."""
        js = f"""
{self._js_plotly_graph_div()}
Plotly.deleteTraces(plotDiv, [{index}]);
"""
        self._run_plotly_javascript(js)
        self._plot_element.update()

    def _relayout(self, payload: dict[str, Any], *, source: str = "relayout") -> None:
        """Push a Plotly relayout payload to the browser."""
        self._register_self_relayout(payload, source=source)
        js = f"""
{self._js_plotly_graph_div()}
Plotly.relayout(plotDiv, {json.dumps(payload)});
"""
        self._run_plotly_javascript(js)

    def _push_shapes(self) -> None:
        """Push the current layout shapes to the browser."""
        self._apply_event_overlays()

    def _apply_event_overlays(self) -> None:
        """Merge measurement shapes with event overlays and relayout."""
        measurement_shapes = self._shapes()[: len(self._shape_refs)]
        combined = measurement_shapes + self.events.build_plotly_shapes()
        self._figure["layout"]["shapes"] = combined
        self._relayout({"shapes": combined}, source="event_overlays")
        # Relayout JS no-ops when the graph is not mounted yet (SPA first paint).
        self._plot_element.update()

    def _sync_theme_to_plotly_dict(self) -> None:
        """Synchronize the selected light/dark theme into the local figure dict."""
        layout = self._figure.setdefault("layout", {})
        if not isinstance(layout, dict):
            layout = {}
            self._figure["layout"] = layout
        apply_plotly_theme_to_layout(layout, self._theme)

    def _sync_axis_labels_to_plotly_dict(self) -> None:
        """Synchronize axis decoration visibility into the local figure dict."""
        layout = self._figure.setdefault("layout", {})
        axis_specs = (
            ("xaxis", self._x_label, self._display_options.show_x_axis_labels),
            ("yaxis", self._y_label, self._display_options.show_y_axis_labels),
        )
        for axis_name, label_text, visible in axis_specs:
            axis = layout.setdefault(axis_name, {})
            if not isinstance(axis, dict):
                axis = {}
                layout[axis_name] = axis
            apply_axis_decorations(axis, label_text=label_text, visible=bool(visible))
        if self._has_yaxis2():
            yaxis2 = layout.setdefault("yaxis2", self._build_yaxis2_dict())
            if isinstance(yaxis2, dict):
                deco_visible = self._yaxis2_decorations_visible()
                apply_axis_decorations(
                    yaxis2,
                    label_text=self._y2_label,
                    visible=deco_visible,
                )
                yaxis2["showgrid"] = False

    def _sync_margins_to_plotly_dict(self) -> None:
        """Synchronize layout margins with axis-label and legend visibility."""
        layout = self._figure.setdefault("layout", {})
        layout["margin"] = resolve_plot_layout_margins(
            show_axis_labels=self._any_axis_labels_visible(),
            show_legend=bool(self._display_options.show_legend),
            has_yaxis2=self._yaxis2_decorations_visible(),
            layout_margins_profile=self._layout_margins_profile,
        )

    def _sync_axis_stabilization_to_plotly_dict(self) -> None:
        """Apply stack-profile axis stabilization into the local figure dict."""
        if self._layout_margins_profile is None:
            return
        layout = self._figure.setdefault("layout", {})
        if isinstance(layout, dict):
            self._layout_margins_profile.apply_axis_stabilization(layout)

    def _sync_legend_to_plotly_dict(self) -> None:
        """Synchronize legend visibility and bottom horizontal layout into the figure dict."""
        layout = self._figure.setdefault("layout", {})
        layout["showlegend"] = bool(self._display_options.show_legend)
        legend = layout.setdefault("legend", {})
        if not isinstance(legend, dict):
            legend = {}
            layout["legend"] = legend
        if self._display_options.show_legend:
            legend.update(dict(_PLOTLY_PLOT_LEGEND))

    def _sync_plotly_config_to_plotly_dict(self) -> None:
        """Synchronize Plotly config options into the local figure dict."""
        config = self._figure.setdefault("config", {})
        if not isinstance(config, dict):
            config = {}
            self._figure["config"] = config
        config["displayModeBar"] = bool(self._display_options.show_plotly_toolbar)
        config["editable"] = True
        config["edits"] = {
            "shapePosition": True,
            "titleText": False,
            "axisTitleText": False,
            "legendText": False,
            "legendPosition": False,
        }

    def _sync_hover_info_to_plotly_dict(self) -> None:
        """Synchronize hover-info visibility into all trace dictionaries."""
        hoverinfo = "all" if self._display_options.show_hover_info else "skip"
        for trace in self._figure.get("data", []):
            if isinstance(trace, dict):
                trace["hoverinfo"] = hoverinfo

    def _restyle_hover_info(self) -> None:
        """Push hover-info changes to the browser via ``Plotly.restyle``."""
        if not self._figure.get("data"):
            return
        hoverinfo = "all" if self._display_options.show_hover_info else "skip"
        indices = list(range(len(self._figure["data"])))
        js = f"""
{self._js_plotly_graph_div()}
Plotly.restyle(plotDiv, {{hoverinfo: {json.dumps(hoverinfo)}}}, {json.dumps(indices)});
"""
        self._run_plotly_javascript(js)

    def _react_plotly_config(self) -> None:
        """Push Plotly config changes to the browser."""
        config = self._figure.get("config", {})
        js = f"""
{self._js_plotly_graph_div()}
Plotly.react(plotDiv, plotDiv.data, plotDiv.layout, {json.dumps(config)});
"""
        self._run_plotly_javascript(js)

    def _relayout_axis_labels_and_margins(self) -> None:
        """Push axis-label and margin layout changes to the browser."""
        layout = self._figure.get("layout", {})
        relayout: dict[str, Any] = {"margin": layout.get("margin", {})}
        for axis_name in ("xaxis", "yaxis"):
            axis = layout.get(axis_name, {})
            if not isinstance(axis, dict):
                continue
            title = axis.get("title", {})
            if isinstance(title, dict):
                relayout[f"{axis_name}.title.text"] = title.get("text", "")
                relayout[f"{axis_name}.title.font.size"] = PLOTLY_AXIS_LABEL_FONT_SIZE
            relayout[f"{axis_name}.tickfont.size"] = PLOTLY_AXIS_LABEL_FONT_SIZE
            relayout[f"{axis_name}.showticklabels"] = axis.get("showticklabels", False)
            relayout[f"{axis_name}.ticks"] = axis.get("ticks", "")
            relayout[f"{axis_name}.showline"] = axis.get("showline", False)
            relayout[f"{axis_name}.zeroline"] = axis.get("zeroline", False)
            relayout[f"{axis_name}.showgrid"] = axis.get("showgrid", False)
            if "automargin" in axis:
                relayout[f"{axis_name}.automargin"] = axis.get("automargin")
        yaxis2 = layout.get("yaxis2")
        if isinstance(yaxis2, dict):
            title = yaxis2.get("title", {})
            if isinstance(title, dict):
                relayout["yaxis2.title.text"] = title.get("text", "")
                relayout["yaxis2.title.font.size"] = PLOTLY_AXIS_LABEL_FONT_SIZE
            relayout["yaxis2.tickfont.size"] = PLOTLY_AXIS_LABEL_FONT_SIZE
            relayout["yaxis2.showticklabels"] = yaxis2.get("showticklabels", False)
            relayout["yaxis2.ticks"] = yaxis2.get("ticks", "")
            relayout["yaxis2.showline"] = yaxis2.get("showline", False)
            relayout["yaxis2.showgrid"] = yaxis2.get("showgrid", False)
        self._relayout(relayout)

    def _relayout_legend(self) -> None:
        """Push legend visibility, layout, and bottom margin to the browser."""
        layout = self._figure.get("layout", {})
        relayout: dict[str, Any] = {
            "showlegend": bool(layout.get("showlegend", True)),
            "margin": layout.get("margin", {}),
        }
        if relayout["showlegend"]:
            legend = layout.get("legend")
            if isinstance(legend, dict):
                relayout["legend"] = legend
        self._relayout(relayout, source="legend_visible")

    def _relayout_theme(self) -> None:
        """Push light/dark theme layout properties to the browser."""
        layout = self._figure.setdefault("layout", {})
        if not isinstance(layout, dict):
            return
        theme = theme_for_name(self._theme)
        relayout: dict[str, Any] = {
            "paper_bgcolor": theme.paper_bgcolor,
            "plot_bgcolor": theme.plot_bgcolor,
            "font.color": theme.font_color,
        }
        for axis_name in ("xaxis", "yaxis"):
            axis = layout.get(axis_name, {})
            if not isinstance(axis, dict):
                continue
            relayout[f"{axis_name}.color"] = axis.get("color", theme.axis_color)
            relayout[f"{axis_name}.linecolor"] = axis.get("linecolor", theme.axis_color)
            relayout[f"{axis_name}.tickcolor"] = axis.get("tickcolor", theme.axis_color)
            relayout[f"{axis_name}.gridcolor"] = axis.get("gridcolor", theme.grid_color)
            relayout[f"{axis_name}.zerolinecolor"] = axis.get("zerolinecolor", theme.zero_line_color)
        yaxis2 = layout.get("yaxis2")
        if isinstance(yaxis2, dict):
            relayout["yaxis2.color"] = yaxis2.get("color", theme.axis_color)
            relayout["yaxis2.linecolor"] = yaxis2.get("linecolor", theme.axis_color)
            relayout["yaxis2.tickcolor"] = yaxis2.get("tickcolor", theme.axis_color)
            relayout["yaxis2.gridcolor"] = yaxis2.get("gridcolor", theme.grid_color)
            relayout["yaxis2.zerolinecolor"] = yaxis2.get("zerolinecolor", theme.zero_line_color)
        self._relayout(relayout)

    def _push_series_data(self) -> None:
        """Push the full trace/scatter data array to the browser in one update."""
        data_json = json.dumps(self._figure["data"])
        js = f"""
{self._js_plotly_graph_div()}
const newData = {data_json};
const oldCount = plotDiv.data ? plotDiv.data.length : 0;
if (oldCount > 0) {{
  Plotly.deleteTraces(plotDiv, [...Array(oldCount).keys()]);
}}
if (newData.length > 0) {{
  Plotly.addTraces(plotDiv, newData);
}}
"""
        self._run_plotly_javascript(js)
        self._plot_element.update()

    def _run_plotly_javascript(self, js: str) -> None:
        """Run Plotly JavaScript while suppressing programmatic relayout echo.

        NiceGUI cannot schedule browser JavaScript until its event loop exists.
        Demo scripts commonly populate widgets before ``ui.run()`` starts that
        loop, so the local figure dictionary remains the source of truth and the
        browser receives the complete state during initial rendering. Incremental
        JavaScript pushes are only needed after the client is live.

        Args:
            js: JavaScript source to execute in the owning browser client.
        """
        if core.loop is None and self._plot_element.client.__class__.__module__.startswith("nicegui"):
            logger.debug("Skipping Plotly JavaScript update before NiceGUI loop starts.")
            return

        self._ignore_relayout = True
        try:
            self._plot_element.client.run_javascript(js, timeout=2.0)
        except RuntimeError:
            logger.warning("Could not run Plotly JavaScript; browser client unavailable.")
        except AssertionError:
            logger.debug("Skipping Plotly JavaScript update before NiceGUI loop starts.")
        except Exception:
            logger.exception("Failed to run Plotly JavaScript update.")
        finally:
            self._ignore_relayout = False

display_options property

display_options: PlotlyPlotDisplayOptions

Return mutable display options used by context-menu actions.

placeholder_text property

placeholder_text: str | None

Return the current centered placeholder message, if any.

series_menu_items property

series_menu_items: tuple[PlotlySeriesMenuItem, ...]

Return registered trace/scatter context-menu items.

on_build_context_menu property

on_build_context_menu: (
    Callable[[PlotlyPlotWidget], None] | None
)

Return optional callback that adds custom context-menu items.

figure property

figure: dict[str, Any]

Return the current Plotly figure dictionary.

x_range_limits property

x_range_limits: tuple[float | None, float | None]

Return the widget's current logical x-axis limits.

set_placeholder_text

set_placeholder_text(message: str | None) -> None

Show or hide centered placeholder text over the plot area.

Parameters:

Name Type Description Default
message str | None

Human-readable empty-state text, or None to hide the placeholder overlay.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def set_placeholder_text(self, message: str | None) -> None:
    """Show or hide centered placeholder text over the plot area.

    Args:
        message: Human-readable empty-state text, or ``None`` to hide the
            placeholder overlay.

    Returns:
        None.
    """
    clean = str(message).strip() if message is not None else ""
    if not clean:
        self._placeholder_text = None
        self._placeholder_container.set_visibility(False)
        return
    self._placeholder_text = clean
    self._placeholder_label.text = clean
    self._placeholder_container.set_visibility(True)

set_on_build_context_menu

set_on_build_context_menu(
    callback: Callable[[PlotlyPlotWidget], None] | None,
) -> None

Set or clear the custom context-menu build callback.

Parameters:

Name Type Description Default
callback Callable[[PlotlyPlotWidget], None] | None

Invoked while rebuilding the right-click menu, or None.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
501
502
503
504
505
506
507
508
509
510
511
512
513
def set_on_build_context_menu(
    self,
    callback: Callable[[PlotlyPlotWidget], None] | None,
) -> None:
    """Set or clear the custom context-menu build callback.

    Args:
        callback: Invoked while rebuilding the right-click menu, or ``None``.

    Returns:
        None.
    """
    self._on_build_context_menu = callback

register_series_menu_items

register_series_menu_items(
    items: Sequence[PlotlySeriesMenuItem],
) -> None

Register trace/scatter items shown in the right-click context menu.

Existing visibility choices are preserved for series names that were registered previously in this widget instance.

Parameters:

Name Type Description Default
items Sequence[PlotlySeriesMenuItem]

Menu item definitions keyed by stable series names.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def register_series_menu_items(self, items: Sequence[PlotlySeriesMenuItem]) -> None:
    """Register trace/scatter items shown in the right-click context menu.

    Existing visibility choices are preserved for series names that were
    registered previously in this widget instance.

    Args:
        items: Menu item definitions keyed by stable series names.

    Returns:
        None.
    """
    self._series_menu_items = list(items)
    for item in items:
        if item.series_name not in self._series_visibility:
            self._series_visibility[item.series_name] = bool(item.default_visible)

is_series_visible

is_series_visible(series_name: str) -> bool

Return whether one registered or loaded series is visible.

Parameters:

Name Type Description Default
series_name str

Stable trace or scatter overlay name.

required

Returns:

Type Description
bool

True when the series should render in the plot.

Source code in src/nicewidgets/plotly_plot/widget.py
532
533
534
535
536
537
538
539
540
541
542
543
544
def is_series_visible(self, series_name: str) -> bool:
    """Return whether one registered or loaded series is visible.

    Args:
        series_name: Stable trace or scatter overlay name.

    Returns:
        True when the series should render in the plot.
    """
    clean = str(series_name).strip()
    if clean in self._series_visibility:
        return bool(self._series_visibility[clean])
    return True

set_series_visible

set_series_visible(series_name: str, visible: bool) -> None

Set visibility for one loaded trace or scatter overlay.

Parameters:

Name Type Description Default
series_name str

Existing trace or scatter overlay name.

required
visible bool

Whether the series should be visible.

required

Raises:

Type Description
KeyError

If the series does not exist in the current figure.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def set_series_visible(self, series_name: str, visible: bool) -> None:
    """Set visibility for one loaded trace or scatter overlay.

    Args:
        series_name: Existing trace or scatter overlay name.
        visible: Whether the series should be visible.

    Raises:
        KeyError: If the series does not exist in the current figure.
    """
    clean = str(series_name).strip()
    self._series_visibility[clean] = bool(visible)
    if clean in self._traces:
        current = self._traces[clean]
        data = PlotlyTraceData.from_sequences(
            name=clean,
            x=current.x,
            y=current.y,
            visible=bool(visible),
            y_axis=current.y_axis,
            line_color=current.line_color,
            line_dash=current.line_dash,
        )
        self._traces[clean] = data
        index = self._series_index(clean, "trace")
        trace = self._trace_to_plotly(data)
        self._figure["data"][index] = trace
        self._restyle_plotly_trace(index, trace)
        self._refresh_yaxis2_layout()
        self._pin_x_axis_after_series_update()
        return
    if clean in self._scatters:
        current = self._scatters[clean]
        data = PlotlyScatterData.from_sequences(
            name=clean,
            x=current.x,
            y=current.y,
            visible=bool(visible),
            y_axis=current.y_axis,
        )
        self._scatters[clean] = data
        index = self._series_index(clean, "scatter")
        trace = self._scatter_to_plotly(data)
        self._figure["data"][index] = trace
        self._restyle_plotly_trace(index, trace)
        self._refresh_yaxis2_layout()
        self._pin_x_axis_after_series_update()
        return
    raise KeyError(f"series {clean!r} does not exist")

set_series_visible_state

set_series_visible_state(
    series_name: str, visible: bool
) -> None

Set desired visibility for a series that may not be loaded yet.

Unlike :meth:set_series_visible, this never raises for an unknown series. When the series is already loaded it restyles immediately; otherwise the visibility is stored and applied the next time the series is added. This supports restoring visibility before plot data exists (for example on reconnect hydrate).

Parameters:

Name Type Description Default
series_name str

Trace or scatter overlay name.

required
visible bool

Whether the series should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def set_series_visible_state(self, series_name: str, visible: bool) -> None:
    """Set desired visibility for a series that may not be loaded yet.

    Unlike :meth:`set_series_visible`, this never raises for an unknown
    series. When the series is already loaded it restyles immediately;
    otherwise the visibility is stored and applied the next time the series
    is added. This supports restoring visibility before plot data exists
    (for example on reconnect hydrate).

    Args:
        series_name: Trace or scatter overlay name.
        visible: Whether the series should be visible.

    Returns:
        None.
    """
    clean = str(series_name).strip()
    if clean in self._traces or clean in self._scatters:
        self.set_series_visible(clean, visible)
        return
    self._series_visibility[clean] = bool(visible)

set_y2_label

set_y2_label(label: str) -> None

Set the secondary right y-axis title text.

Decorations appear only when y-axis labels are enabled and at least one right-axis trace or scatter is visible.

Parameters:

Name Type Description Default
label str

Y2 axis title, or "" to clear.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def set_y2_label(self, label: str) -> None:
    """Set the secondary right y-axis title text.

    Decorations appear only when y-axis labels are enabled and at least one
    right-axis trace or scatter is visible.

    Args:
        label: Y2 axis title, or ``""`` to clear.

    Returns:
        None.
    """
    self._y2_label = str(label)
    if self._has_yaxis2():
        self._refresh_yaxis2_layout()

set_x_label

set_x_label(label: str) -> None

Set the primary x-axis title text.

Parameters:

Name Type Description Default
label str

X-axis title, or "" to clear.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
634
635
636
637
638
639
640
641
642
643
def set_x_label(self, label: str) -> None:
    """Set the primary x-axis title text.

    Args:
        label: X-axis title, or ``""`` to clear.

    Returns:
        None.
    """
    self._set_primary_axis_label(axis_name="xaxis", label=str(label), attr="_x_label")

set_y_label

set_y_label(label: str) -> None

Set the primary left y-axis title text.

Parameters:

Name Type Description Default
label str

Y-axis title, or "" to clear.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
645
646
647
648
649
650
651
652
653
654
def set_y_label(self, label: str) -> None:
    """Set the primary left y-axis title text.

    Args:
        label: Y-axis title, or ``""`` to clear.

    Returns:
        None.
    """
    self._set_primary_axis_label(axis_name="yaxis", label=str(label), attr="_y_label")

toggle_series_visible

toggle_series_visible(series_name: str) -> bool

Toggle visibility for one registered trace or scatter overlay.

Parameters:

Name Type Description Default
series_name str

Stable trace or scatter overlay name.

required

Returns:

Type Description
bool

Visibility after the toggle.

Raises:

Type Description
KeyError

If series_name is not a registered menu item.

Source code in src/nicewidgets/plotly_plot/widget.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def toggle_series_visible(self, series_name: str) -> bool:
    """Toggle visibility for one registered trace or scatter overlay.

    Args:
        series_name: Stable trace or scatter overlay name.

    Returns:
        Visibility after the toggle.

    Raises:
        KeyError: If ``series_name`` is not a registered menu item.
    """
    clean = str(series_name).strip()
    if not any(item.series_name == clean for item in self._series_menu_items):
        raise KeyError(f"series {clean!r} is not registered in the context menu")
    new_visible = not self.is_series_visible(clean)
    if clean in self._traces or clean in self._scatters:
        self.set_series_visible(clean, new_visible)
    else:
        self._series_visibility[clean] = new_visible
    if self._on_series_visibility_changed is not None:
        self._on_series_visibility_changed(clean, new_visible)
    return new_visible

set_x_axis_labels_visible

set_x_axis_labels_visible(visible: bool) -> None

Show or hide x-axis title text, ticks, lines, and grid lines.

Parameters:

Name Type Description Default
visible bool

Whether x-axis decorations should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
def set_x_axis_labels_visible(self, visible: bool) -> None:
    """Show or hide x-axis title text, ticks, lines, and grid lines.

    Args:
        visible: Whether x-axis decorations should be visible.

    Returns:
        None.
    """
    self._display_options.show_x_axis_labels = bool(visible)
    self._sync_axis_labels_to_plotly_dict()
    self._sync_margins_to_plotly_dict()
    self._sync_axis_stabilization_to_plotly_dict()
    self._relayout_axis_labels_and_margins()

set_y_axis_labels_visible

set_y_axis_labels_visible(visible: bool) -> None

Show or hide left and right y-axis title text, ticks, lines, and grid lines.

Parameters:

Name Type Description Default
visible bool

Whether y-axis decorations should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def set_y_axis_labels_visible(self, visible: bool) -> None:
    """Show or hide left and right y-axis title text, ticks, lines, and grid lines.

    Args:
        visible: Whether y-axis decorations should be visible.

    Returns:
        None.
    """
    self._display_options.show_y_axis_labels = bool(visible)
    self._sync_axis_labels_to_plotly_dict()
    self._sync_margins_to_plotly_dict()
    self._sync_axis_stabilization_to_plotly_dict()
    self._relayout_axis_labels_and_margins()

set_plotly_toolbar_visible

set_plotly_toolbar_visible(visible: bool) -> None

Set Plotly modebar visibility.

Parameters:

Name Type Description Default
visible bool

Whether Plotly's modebar should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
738
739
740
741
742
743
744
745
746
747
748
749
def set_plotly_toolbar_visible(self, visible: bool) -> None:
    """Set Plotly modebar visibility.

    Args:
        visible: Whether Plotly's modebar should be visible.

    Returns:
        None.
    """
    self._display_options.show_plotly_toolbar = bool(visible)
    self._sync_plotly_config_to_plotly_dict()
    self._react_plotly_config()

set_hover_info_visible

set_hover_info_visible(visible: bool) -> None

Set Plotly hover-info visibility for all plot traces.

Parameters:

Name Type Description Default
visible bool

Whether hover info should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
751
752
753
754
755
756
757
758
759
760
761
762
def set_hover_info_visible(self, visible: bool) -> None:
    """Set Plotly hover-info visibility for all plot traces.

    Args:
        visible: Whether hover info should be visible.

    Returns:
        None.
    """
    self._display_options.show_hover_info = bool(visible)
    self._sync_hover_info_to_plotly_dict()
    self._restyle_hover_info()

set_legend_visible

set_legend_visible(visible: bool) -> None

Show or hide the Plotly legend.

When shown, the legend uses the widget's bottom horizontal layout (orientation='h' centered below the plot).

Parameters:

Name Type Description Default
visible bool

Whether the legend should be visible.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def set_legend_visible(self, visible: bool) -> None:
    """Show or hide the Plotly legend.

    When shown, the legend uses the widget's bottom horizontal layout
    (``orientation='h'`` centered below the plot).

    Args:
        visible: Whether the legend should be visible.

    Returns:
        None.
    """
    self._display_options.show_legend = bool(visible)
    self._sync_legend_to_plotly_dict()
    self._sync_margins_to_plotly_dict()
    self._relayout_legend()

copy_plot_to_clipboard async

copy_plot_to_clipboard() -> None

Copy the current Plotly plot image to the active clipboard.

Native desktop mode uses pyperclipimg. Browser mode uses the Clipboard API with a Plotly PNG export.

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
async def copy_plot_to_clipboard(self) -> None:
    """Copy the current Plotly plot image to the active clipboard.

    Native desktop mode uses ``pyperclipimg``. Browser mode uses the
    Clipboard API with a Plotly PNG export.

    Returns:
        None.
    """
    try:
        if is_pywebview_desktop():
            png_bytes = await get_plotly_png_bytes(self._plot_element)
            copy_png_bytes_to_native_clipboard(png_bytes)
        else:
            await copy_plotly_png_to_browser_clipboard(self._plot_element)
        ui.notify("Plot copied to clipboard.", type="positive")
    except Exception as exc:
        logger.exception("Failed to copy Plotly plot to clipboard.")
        ui.notify(f"Copy failed: {exc}", type="negative")

add_trace

add_trace(
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool = True,
    y_axis: PlotlyYAxisSide = 'left',
    line_color: str | None = None,
    line_dash: str | None = None,
) -> None

Add a named continuous scattergl line trace.

Parameters:

Name Type Description Default
name str

Stable caller-defined trace name.

required
x Sequence[float]

X-axis values (non-empty; equal length to y).

required
y Sequence[float]

Y-axis values (non-empty; equal length to x).

required
visible bool

Whether the trace should be visible.

True
y_axis PlotlyYAxisSide

Primary y axis ("left") or overlaid y2 axis ("right"). Right-axis traces create layout.yaxis2.

'left'
line_color str | None

Optional Plotly line color (CSS color string or Plotly color, for example "#1f77b4" or "rgb(31,119,180)").

None
line_dash str | None

Optional Plotly dash style: "solid", "dot", "dash", "longdash", "dashdot", or "longdashdot".

None

Raises:

Type Description
ValueError

If the name already exists or data are invalid.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def add_trace(
    self,
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool = True,
    y_axis: PlotlyYAxisSide = "left",
    line_color: str | None = None,
    line_dash: str | None = None,
) -> None:
    """Add a named continuous ``scattergl`` line trace.

    Args:
        name: Stable caller-defined trace name.
        x: X-axis values (non-empty; equal length to ``y``).
        y: Y-axis values (non-empty; equal length to ``x``).
        visible: Whether the trace should be visible.
        y_axis: Primary ``y`` axis (``"left"``) or overlaid ``y2`` axis
            (``"right"``). Right-axis traces create ``layout.yaxis2``.
        line_color: Optional Plotly line color (CSS color string or Plotly
            color, for example ``"#1f77b4"`` or ``"rgb(31,119,180)"``).
        line_dash: Optional Plotly dash style: ``"solid"``, ``"dot"``,
            ``"dash"``, ``"longdash"``, ``"dashdot"``, or ``"longdashdot"``.

    Raises:
        ValueError: If the name already exists or data are invalid.
    """
    clean = _validate_unique_name(name, self._traces.get(str(name).strip()), label="trace")
    axis = _normalize_y_axis_side(y_axis)
    data = PlotlyTraceData.from_sequences(
        name=clean,
        x=x,
        y=y,
        visible=visible,
        y_axis=axis,
        line_color=line_color,
        line_dash=line_dash,
    )
    self._traces[clean] = data
    self._series_order.append(_SeriesRef(name=clean, kind="trace"))
    self._sync_yaxis2_from_series()
    trace = self._trace_to_plotly(data)
    self._figure["data"].append(trace)
    self._add_plotly_trace(trace)

update_trace

update_trace(
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool | None = None,
) -> None

Replace data for an existing named continuous trace.

Parameters:

Name Type Description Default
name str

Existing trace name.

required
x Sequence[float]

Replacement X-axis values.

required
y Sequence[float]

Replacement Y-axis values.

required
visible bool | None

Optional replacement visibility. When None, the existing visibility is preserved.

None

Raises:

Type Description
KeyError

If the trace does not exist.

ValueError

If replacement data are invalid.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def update_trace(
    self,
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool | None = None,
) -> None:
    """Replace data for an existing named continuous trace.

    Args:
        name: Existing trace name.
        x: Replacement X-axis values.
        y: Replacement Y-axis values.
        visible: Optional replacement visibility. When ``None``, the
            existing visibility is preserved.

    Raises:
        KeyError: If the trace does not exist.
        ValueError: If replacement data are invalid.
    """
    clean = str(name).strip()
    current = self._traces.get(clean)
    if current is None:
        raise KeyError(f"trace {clean!r} does not exist")
    data = PlotlyTraceData.from_sequences(
        name=clean,
        x=x,
        y=y,
        visible=current.visible if visible is None else visible,
        y_axis=current.y_axis,
        line_color=current.line_color,
        line_dash=current.line_dash,
    )
    self._traces[clean] = data
    index = self._series_index(clean, "trace")
    trace = self._trace_to_plotly(data)
    self._figure["data"][index] = trace
    self._restyle_plotly_trace(index, trace)

remove_trace

remove_trace(name: str) -> None

Remove a named continuous trace.

Parameters:

Name Type Description Default
name str

Existing trace name.

required

Raises:

Type Description
KeyError

If the trace does not exist.

Source code in src/nicewidgets/plotly_plot/widget.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
def remove_trace(self, name: str) -> None:
    """Remove a named continuous trace.

    Args:
        name: Existing trace name.

    Raises:
        KeyError: If the trace does not exist.
    """
    clean = str(name).strip()
    index = self._series_index(clean, "trace")
    self._traces.pop(clean)
    self._series_order.pop(index)
    self._figure["data"].pop(index)
    self._delete_plotly_trace(index)
    self._sync_yaxis2_from_series()

clear_traces

clear_traces() -> None

Remove all continuous traces while preserving scatter overlays.

Source code in src/nicewidgets/plotly_plot/widget.py
925
926
927
928
def clear_traces(self) -> None:
    """Remove all continuous traces while preserving scatter overlays."""
    for name in list(self._traces):
        self.remove_trace(name)

plot_scatter

plot_scatter(
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool = True,
    y_axis: PlotlyYAxisSide = 'left',
) -> None

Add a named sparse scattergl marker overlay.

Scatter overlays are excluded from :meth:reset_x_axis_limits fitting so marker padding does not shift the derived line-trace x extent.

Parameters:

Name Type Description Default
name str

Stable caller-defined scatter overlay name.

required
x Sequence[float]

X-axis values (non-empty; equal length to y).

required
y Sequence[float]

Y-axis values (non-empty; equal length to x).

required
visible bool

Whether the scatter overlay should be visible.

True
y_axis PlotlyYAxisSide

Primary y axis ("left") or overlaid y2 axis ("right"). Right-axis scatters create layout.yaxis2.

'left'

Raises:

Type Description
ValueError

If the name already exists or data are invalid.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def plot_scatter(
    self,
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool = True,
    y_axis: PlotlyYAxisSide = "left",
) -> None:
    """Add a named sparse ``scattergl`` marker overlay.

    Scatter overlays are excluded from :meth:`reset_x_axis_limits` fitting so
    marker padding does not shift the derived line-trace x extent.

    Args:
        name: Stable caller-defined scatter overlay name.
        x: X-axis values (non-empty; equal length to ``y``).
        y: Y-axis values (non-empty; equal length to ``x``).
        visible: Whether the scatter overlay should be visible.
        y_axis: Primary ``y`` axis (``"left"``) or overlaid ``y2`` axis
            (``"right"``). Right-axis scatters create ``layout.yaxis2``.

    Raises:
        ValueError: If the name already exists or data are invalid.
    """
    clean = _validate_unique_name(
        name,
        self._scatters.get(str(name).strip()),
        label="scatter",
    )
    axis = _normalize_y_axis_side(y_axis)
    data = PlotlyScatterData.from_sequences(
        name=clean, x=x, y=y, visible=visible, y_axis=axis
    )
    self._scatters[clean] = data
    self._series_order.append(_SeriesRef(name=clean, kind="scatter"))
    self._sync_yaxis2_from_series()
    trace = self._scatter_to_plotly(data)
    self._figure["data"].append(trace)
    self._add_plotly_trace(trace)

update_scatter

update_scatter(
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool | None = None,
) -> None

Replace data for an existing named scatter overlay.

Parameters:

Name Type Description Default
name str

Existing scatter overlay name.

required
x Sequence[float]

Replacement X-axis values.

required
y Sequence[float]

Replacement Y-axis values.

required
visible bool | None

Optional replacement visibility. When None, the existing visibility is preserved.

None

Raises:

Type Description
KeyError

If the scatter overlay does not exist.

ValueError

If replacement data are invalid.

Source code in src/nicewidgets/plotly_plot/widget.py
 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
def update_scatter(
    self,
    *,
    name: str,
    x: Sequence[float],
    y: Sequence[float],
    visible: bool | None = None,
) -> None:
    """Replace data for an existing named scatter overlay.

    Args:
        name: Existing scatter overlay name.
        x: Replacement X-axis values.
        y: Replacement Y-axis values.
        visible: Optional replacement visibility. When ``None``, the
            existing visibility is preserved.

    Raises:
        KeyError: If the scatter overlay does not exist.
        ValueError: If replacement data are invalid.
    """
    clean = str(name).strip()
    current = self._scatters.get(clean)
    if current is None:
        raise KeyError(f"scatter {clean!r} does not exist")
    data = PlotlyScatterData.from_sequences(
        name=clean,
        x=x,
        y=y,
        visible=current.visible if visible is None else visible,
        y_axis=current.y_axis,
    )
    self._scatters[clean] = data
    index = self._series_index(clean, "scatter")
    trace = self._scatter_to_plotly(data)
    self._figure["data"][index] = trace
    self._restyle_plotly_trace(index, trace)

remove_scatter

remove_scatter(name: str) -> None

Remove a named scatter overlay.

Parameters:

Name Type Description Default
name str

Existing scatter overlay name.

required

Raises:

Type Description
KeyError

If the scatter overlay does not exist.

Source code in src/nicewidgets/plotly_plot/widget.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def remove_scatter(self, name: str) -> None:
    """Remove a named scatter overlay.

    Args:
        name: Existing scatter overlay name.

    Raises:
        KeyError: If the scatter overlay does not exist.
    """
    clean = str(name).strip()
    index = self._series_index(clean, "scatter")
    self._scatters.pop(clean)
    self._series_order.pop(index)
    self._figure["data"].pop(index)
    self._delete_plotly_trace(index)
    self._sync_yaxis2_from_series()

clear_scatters

clear_scatters() -> None

Remove all scatter overlays while preserving continuous traces.

Source code in src/nicewidgets/plotly_plot/widget.py
1026
1027
1028
1029
def clear_scatters(self) -> None:
    """Remove all scatter overlays while preserving continuous traces."""
    for name in list(self._scatters):
        self.remove_scatter(name)

set_series

set_series(
    *,
    traces: Sequence[PlotlyTraceData] = (),
    scatters: Sequence[PlotlyScatterData] = (),
) -> None

Replace all continuous traces and scatter overlays in one browser update.

Measurement lines and layout shapes are preserved. Existing incremental add_trace / plot_scatter callers remain available; prefer this method when rebuilding the full plot contents at once.

Parameters:

Name Type Description Default
traces Sequence[PlotlyTraceData]

Replacement continuous traces.

()
scatters Sequence[PlotlyScatterData]

Replacement scatter overlays.

()

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def set_series(
    self,
    *,
    traces: Sequence[PlotlyTraceData] = (),
    scatters: Sequence[PlotlyScatterData] = (),
) -> None:
    """Replace all continuous traces and scatter overlays in one browser update.

    Measurement lines and layout shapes are preserved. Existing incremental
    ``add_trace`` / ``plot_scatter`` callers remain available; prefer this
    method when rebuilding the full plot contents at once.

    Args:
        traces: Replacement continuous traces.
        scatters: Replacement scatter overlays.

    Returns:
        None.
    """
    self._traces = {}
    self._scatters = {}
    self._series_order = []
    plotly_data: list[dict[str, Any]] = []
    for data in traces:
        visible = self.is_series_visible(data.name)
        stored = PlotlyTraceData(
            name=data.name,
            x=data.x,
            y=data.y,
            visible=visible,
            y_axis=data.y_axis,
            line_color=data.line_color,
            line_dash=data.line_dash,
        )
        self._traces[stored.name] = stored
        self._series_order.append(_SeriesRef(name=stored.name, kind="trace"))
        plotly_data.append(self._trace_to_plotly(stored))
    for data in scatters:
        visible = self.is_series_visible(data.name)
        stored = PlotlyScatterData(
            name=data.name,
            x=data.x,
            y=data.y,
            visible=visible,
            y_axis=data.y_axis,
        )
        self._scatters[stored.name] = stored
        self._series_order.append(_SeriesRef(name=stored.name, kind="scatter"))
        plotly_data.append(self._scatter_to_plotly(stored))
    self._figure["data"] = plotly_data
    self._sync_hover_info_to_plotly_dict()
    self._sync_yaxis2_from_series()
    self._push_series_data()
    self._pin_x_axis_after_series_update()
    if plotly_data:
        self.set_placeholder_text(None)

set_theme

set_theme(theme: PlotlyThemeName) -> None

Set the Plotly light/dark layout theme.

Parameters:

Name Type Description Default
theme PlotlyThemeName

Theme name, either 'light' or 'dark'.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
def set_theme(self, theme: PlotlyThemeName) -> None:
    """Set the Plotly light/dark layout theme.

    Args:
        theme: Theme name, either ``'light'`` or ``'dark'``.

    Returns:
        None.
    """
    self._theme = normalize_plotly_theme(theme)
    self._display_options.theme = self._theme
    self._sync_theme_to_plotly_dict()
    self._relayout_theme()
    # Relayout JS no-ops when the graph is not mounted yet (SPA first paint).
    self._plot_element.update()

set_dark_mode

set_dark_mode(enabled: bool) -> None

Set the Plotly layout theme from a dark-mode flag.

Parameters:

Name Type Description Default
enabled bool

Whether dark mode is enabled.

required

Returns:

Type Description
None

None.

Source code in src/nicewidgets/plotly_plot/widget.py
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
def set_dark_mode(self, enabled: bool) -> None:
    """Set the Plotly layout theme from a dark-mode flag.

    Args:
        enabled: Whether dark mode is enabled.

    Returns:
        None.
    """
    self.set_theme("dark" if enabled else "light")

set_x_axis_limits

set_x_axis_limits(
    x_min: float | None, x_max: float | None
) -> None

Set x-axis limits programmatically.

Parameters:

Name Type Description Default
x_min float | None

Minimum x-axis value, or None for automatic scaling.

required
x_max float | None

Maximum x-axis value, or None for automatic scaling.

required

Raises:

Type Description
ValueError

If both bounds are set and x_min >= x_max.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def set_x_axis_limits(self, x_min: float | None, x_max: float | None) -> None:
    """Set x-axis limits programmatically.

    Args:
        x_min: Minimum x-axis value, or ``None`` for automatic scaling.
        x_max: Maximum x-axis value, or ``None`` for automatic scaling.

    Raises:
        ValueError: If both bounds are set and ``x_min >= x_max``.
    """
    new_range = (x_min, x_max)
    if _x_range_equal(new_range, (self._x_range.x_min, self._x_range.x_max)):
        self._last_applied_x_range = new_range
        return
    self._x_range = PlotlyAxisRange(x_min=x_min, x_max=x_max)
    self._last_applied_x_range = new_range
    xaxis = self._figure["layout"].setdefault("xaxis", {})
    if x_min is None or x_max is None:
        xaxis.pop("range", None)
        xaxis["autorange"] = True
        self._relayout({"xaxis.autorange": True})
        return
    xaxis["range"] = [float(x_min), float(x_max)]
    xaxis["autorange"] = False
    self._relayout({"xaxis.range": [float(x_min), float(x_max)], "xaxis.autorange": False})

reset_x_axis_limits

reset_x_axis_limits() -> None

Reset the x-axis to the full extent of visible line traces.

When line traces are present, limits are derived from continuous traces only so scatter marker padding does not shift x=0. With no line traces, falls back to Plotly autorange.

Source code in src/nicewidgets/plotly_plot/widget.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
def reset_x_axis_limits(self) -> None:
    """Reset the x-axis to the full extent of visible line traces.

    When line traces are present, limits are derived from continuous traces
    only so scatter marker padding does not shift x=0. With no line traces,
    falls back to Plotly autorange.
    """
    derived = self._derive_x_range_from_visible_line_traces()
    if derived is not None:
        self._x_range = PlotlyAxisRange(x_min=None, x_max=None)
        self._last_applied_x_range = (None, None)
        self._push_x_axis_range_to_browser(*derived)
        return
    self.set_x_axis_limits(None, None)

begin_select_x_range

begin_select_x_range() -> None

Enter one-shot box-select mode for user x-range selection.

While armed, plotly_relayout payloads carrying selections x-bounds invoke on_x_range_selected once, then restore zoom mode.

Source code in src/nicewidgets/plotly_plot/widget.py
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
def begin_select_x_range(self) -> None:
    """Enter one-shot box-select mode for user x-range selection.

    While armed, ``plotly_relayout`` payloads carrying ``selections`` x-bounds
    invoke ``on_x_range_selected`` once, then restore zoom mode.
    """
    self._x_range_selection_armed = True
    layout = self._figure.setdefault("layout", {})
    layout["dragmode"] = "select"
    self._relayout({"dragmode": "select"}, source="begin_select_x_range")

cancel_select_x_range

cancel_select_x_range() -> None

Cancel box-select mode and restore zoom dragmode.

Source code in src/nicewidgets/plotly_plot/widget.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def cancel_select_x_range(self) -> None:
    """Cancel box-select mode and restore zoom dragmode."""
    self._x_range_selection_armed = False
    layout = self._figure.setdefault("layout", {})
    layout["dragmode"] = "zoom"
    layout["selections"] = []
    self._relayout(
        {"dragmode": "zoom", "selections": []},
        source="cancel_select_x_range",
    )

add_measurement_line

add_measurement_line(
    *,
    name: str,
    orientation: str,
    value: float,
    visible: bool = True,
    y_axis: PlotlyYAxisSide = 'left',
    editable: bool = True,
    color: str | None = None,
    dash: str = 'dash',
    show_legend: bool = False,
    legend_label: str | None = None,
    on_changed: OnMeasurementChanged | None = None,
) -> MeasurementLine

Add a horizontal or vertical measurement line.

Parameters:

Name Type Description Default
name str

Stable caller-defined measurement name.

required
orientation str

horizontal/h or vertical/v.

required
value float

Initial line position in data coordinates.

required
visible bool

Whether the line should be visible.

True
y_axis PlotlyYAxisSide

Y-axis for horizontal lines. "right" requires an existing layout.yaxis2 from a right-axis trace or scatter.

'left'
editable bool

Whether the user can drag the line.

True
color str | None

Plotly line color. None uses a theme-aware default.

None
dash str

Plotly dash style ("solid", "dot", "dash", ...).

'dash'
show_legend bool

Whether the line appears in the Plotly legend.

False
legend_label str | None

Legend text when show_legend is True. Defaults to name.

None
on_changed OnMeasurementChanged | None

Optional per-measurement callback. Ignored when editable is False.

None

Returns:

Type Description
MeasurementLine

Mutable measurement line object owned by the widget.

Raises:

Type Description
ValueError

If the name already exists, orientation is invalid, or a right-axis horizontal line is requested before yaxis2 exists.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def add_measurement_line(
    self,
    *,
    name: str,
    orientation: str,
    value: float,
    visible: bool = True,
    y_axis: PlotlyYAxisSide = "left",
    editable: bool = True,
    color: str | None = None,
    dash: str = "dash",
    show_legend: bool = False,
    legend_label: str | None = None,
    on_changed: OnMeasurementChanged | None = None,
) -> MeasurementLine:
    """Add a horizontal or vertical measurement line.

    Args:
        name: Stable caller-defined measurement name.
        orientation: ``horizontal``/``h`` or ``vertical``/``v``.
        value: Initial line position in data coordinates.
        visible: Whether the line should be visible.
        y_axis: Y-axis for horizontal lines. ``"right"`` requires an
            existing ``layout.yaxis2`` from a right-axis trace or scatter.
        editable: Whether the user can drag the line.
        color: Plotly line color. ``None`` uses a theme-aware default.
        dash: Plotly dash style (``"solid"``, ``"dot"``, ``"dash"``, ...).
        show_legend: Whether the line appears in the Plotly legend.
        legend_label: Legend text when ``show_legend`` is True. Defaults to
            ``name``.
        on_changed: Optional per-measurement callback. Ignored when
            ``editable`` is False.

    Returns:
        Mutable measurement line object owned by the widget.

    Raises:
        ValueError: If the name already exists, orientation is invalid, or
            a right-axis horizontal line is requested before ``yaxis2`` exists.
    """
    clean = _validate_unique_name(
        name,
        self._measurements.get(str(name).strip()),
        label="measurement",
    )
    normalized = _normalize_orientation(orientation)
    axis = _normalize_y_axis_side(y_axis)
    if normalized == "vertical":
        axis = "left"
    elif axis == "right" and not self._has_yaxis2():
        raise ValueError(
            "cannot add right-axis measurement before a right-axis trace or scatter exists"
        )
    line_color = color if color is not None else self._default_measurement_color()
    line = MeasurementLine(
        name=clean,
        orientation=normalized,
        position=float(value),
        visible=bool(visible),
        y_axis=axis,
        editable=bool(editable),
        color=line_color,
        dash=str(dash),
        show_legend=bool(show_legend),
        legend_label=legend_label,
    )
    self._measurements[clean] = line
    if on_changed is not None and line.editable:
        self._measurement_callbacks[clean] = on_changed
    self._append_measurement_shape(
        clean,
        "line",
        1,
        normalized,
        float(value),
        visible,
        axis,
        editable=line.editable,
        color=line.color,
        dash=line.dash,
        show_legend=line.show_legend,
        legend_label=line.legend_label or clean,
    )
    self._push_shapes()
    return line

remove_measurement_line

remove_measurement_line(name: str) -> None

Remove a single-line measurement.

Parameters:

Name Type Description Default
name str

Existing single-line measurement name.

required

Raises:

Type Description
KeyError

If the measurement does not exist.

ValueError

If the measurement is a pair.

Source code in src/nicewidgets/plotly_plot/widget.py
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
def remove_measurement_line(self, name: str) -> None:
    """Remove a single-line measurement.

    Args:
        name: Existing single-line measurement name.

    Raises:
        KeyError: If the measurement does not exist.
        ValueError: If the measurement is a pair.
    """
    self._remove_measurement(name, expected_kind="line")

add_measurement_pair

add_measurement_pair(
    *,
    name: str,
    orientation: str,
    value1: float,
    value2: float,
    visible: bool = True,
    y_axis: PlotlyYAxisSide = 'left',
    on_changed: OnMeasurementChanged | None = None,
) -> MeasurementPair

Add a draggable pair of horizontal or vertical measurement lines.

Parameters:

Name Type Description Default
name str

Stable caller-defined measurement-pair name.

required
orientation str

horizontal/h or vertical/v.

required
value1 float

Initial first-line position in data coordinates.

required
value2 float

Initial second-line position in data coordinates.

required
visible bool

Whether both lines should be visible.

True
y_axis PlotlyYAxisSide

Y-axis for horizontal lines. "right" requires an existing layout.yaxis2 from a right-axis trace or scatter.

'left'
on_changed OnMeasurementChanged | None

Optional per-measurement callback.

None

Returns:

Type Description
MeasurementPair

Mutable measurement pair object owned by the widget.

Raises:

Type Description
ValueError

If the name already exists, orientation is invalid, or a right-axis horizontal pair is requested before yaxis2 exists.

Source code in src/nicewidgets/plotly_plot/widget.py
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
def add_measurement_pair(
    self,
    *,
    name: str,
    orientation: str,
    value1: float,
    value2: float,
    visible: bool = True,
    y_axis: PlotlyYAxisSide = "left",
    on_changed: OnMeasurementChanged | None = None,
) -> MeasurementPair:
    """Add a draggable pair of horizontal or vertical measurement lines.

    Args:
        name: Stable caller-defined measurement-pair name.
        orientation: ``horizontal``/``h`` or ``vertical``/``v``.
        value1: Initial first-line position in data coordinates.
        value2: Initial second-line position in data coordinates.
        visible: Whether both lines should be visible.
        y_axis: Y-axis for horizontal lines. ``"right"`` requires an
            existing ``layout.yaxis2`` from a right-axis trace or scatter.
        on_changed: Optional per-measurement callback.

    Returns:
        Mutable measurement pair object owned by the widget.

    Raises:
        ValueError: If the name already exists, orientation is invalid, or
            a right-axis horizontal pair is requested before ``yaxis2`` exists.
    """
    clean = _validate_unique_name(
        name,
        self._measurements.get(str(name).strip()),
        label="measurement",
    )
    normalized = _normalize_orientation(orientation)
    axis = _normalize_y_axis_side(y_axis)
    if normalized == "vertical":
        axis = "left"
    elif axis == "right" and not self._has_yaxis2():
        raise ValueError(
            "cannot add right-axis measurement before a right-axis trace or scatter exists"
        )
    pair = MeasurementPair(
        name=clean,
        orientation=normalized,
        position1=float(value1),
        position2=float(value2),
        visible=bool(visible),
        y_axis=axis,
    )
    self._measurements[clean] = pair
    if on_changed is not None:
        self._measurement_callbacks[clean] = on_changed
    self._append_measurement_shape(
        clean, "pair", 1, normalized, float(value1), visible, axis
    )
    self._append_measurement_shape(
        clean, "pair", 2, normalized, float(value2), visible, axis
    )
    self._push_shapes()
    return pair

remove_measurement_pair

remove_measurement_pair(name: str) -> None

Remove a paired-line measurement.

Parameters:

Name Type Description Default
name str

Existing measurement-pair name.

required

Raises:

Type Description
KeyError

If the measurement does not exist.

ValueError

If the measurement is a single line.

Source code in src/nicewidgets/plotly_plot/widget.py
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def remove_measurement_pair(self, name: str) -> None:
    """Remove a paired-line measurement.

    Args:
        name: Existing measurement-pair name.

    Raises:
        KeyError: If the measurement does not exist.
        ValueError: If the measurement is a single line.
    """
    self._remove_measurement(name, expected_kind="pair")

nicewidgets.plotly_plot.display_options.PlotlyPlotDisplayOptions dataclass

User-facing display toggles for :class:PlotlyPlotWidget.

Parameters:

Name Type Description Default
show_x_axis_labels bool

Whether x-axis title text, tick labels, ticks, axis lines, and grid lines are visible.

False
show_y_axis_labels bool

Whether primary left and secondary right y-axis title text, tick labels, ticks, axis lines, and grid lines are visible.

False
show_plotly_toolbar bool

Whether Plotly's modebar is visible.

False
show_hover_info bool

Whether Plotly emits hover labels for plot traces.

False
show_legend bool

Whether the Plotly legend is visible.

True
theme PlotlyThemeName

Plotly layout color theme.

'light'
Source code in src/nicewidgets/plotly_plot/display_options.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@dataclass(slots=True)
class PlotlyPlotDisplayOptions:
    """User-facing display toggles for :class:`PlotlyPlotWidget`.

    Args:
        show_x_axis_labels: Whether x-axis title text, tick labels, ticks, axis
            lines, and grid lines are visible.
        show_y_axis_labels: Whether primary left and secondary right y-axis title
            text, tick labels, ticks, axis lines, and grid lines are visible.
        show_plotly_toolbar: Whether Plotly's modebar is visible.
        show_hover_info: Whether Plotly emits hover labels for plot traces.
        show_legend: Whether the Plotly legend is visible.
        theme: Plotly layout color theme.
    """

    show_x_axis_labels: bool = False
    show_y_axis_labels: bool = False
    show_plotly_toolbar: bool = False
    show_hover_info: bool = False
    show_legend: bool = True
    theme: PlotlyThemeName = "light"

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-serializable representation of these options.

        Returns:
            Mapping with one entry per field. ``theme`` is a plain string.
        """
        return {
            "show_x_axis_labels": bool(self.show_x_axis_labels),
            "show_y_axis_labels": bool(self.show_y_axis_labels),
            "show_plotly_toolbar": bool(self.show_plotly_toolbar),
            "show_hover_info": bool(self.show_hover_info),
            "show_legend": bool(self.show_legend),
            "theme": normalize_plotly_theme(str(self.theme)),
        }

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> PlotlyPlotDisplayOptions:
        """Build display options from a mapping produced by :meth:`to_dict`.

        Unknown keys are ignored and missing keys fall back to field defaults,
        so the widget stays robust across schema evolution.

        Args:
            data: Mapping of option names to values.

        Returns:
            New :class:`PlotlyPlotDisplayOptions` instance.
        """
        known = {field.name for field in fields(cls)}
        kwargs: dict[str, Any] = {
            key: value for key, value in data.items() if key in known
        }
        if "theme" in kwargs:
            kwargs["theme"] = normalize_plotly_theme(str(kwargs["theme"]))
        return cls(**kwargs)

to_dict

to_dict() -> dict[str, Any]

Return a JSON-serializable representation of these options.

Returns:

Type Description
dict[str, Any]

Mapping with one entry per field. theme is a plain string.

Source code in src/nicewidgets/plotly_plot/display_options.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable representation of these options.

    Returns:
        Mapping with one entry per field. ``theme`` is a plain string.
    """
    return {
        "show_x_axis_labels": bool(self.show_x_axis_labels),
        "show_y_axis_labels": bool(self.show_y_axis_labels),
        "show_plotly_toolbar": bool(self.show_plotly_toolbar),
        "show_hover_info": bool(self.show_hover_info),
        "show_legend": bool(self.show_legend),
        "theme": normalize_plotly_theme(str(self.theme)),
    }

from_dict classmethod

from_dict(data: dict[str, Any]) -> PlotlyPlotDisplayOptions

Build display options from a mapping produced by :meth:to_dict.

Unknown keys are ignored and missing keys fall back to field defaults, so the widget stays robust across schema evolution.

Parameters:

Name Type Description Default
data dict[str, Any]

Mapping of option names to values.

required

Returns:

Name Type Description
New PlotlyPlotDisplayOptions

class:PlotlyPlotDisplayOptions instance.

Source code in src/nicewidgets/plotly_plot/display_options.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@classmethod
def from_dict(cls, data: dict[str, Any]) -> PlotlyPlotDisplayOptions:
    """Build display options from a mapping produced by :meth:`to_dict`.

    Unknown keys are ignored and missing keys fall back to field defaults,
    so the widget stays robust across schema evolution.

    Args:
        data: Mapping of option names to values.

    Returns:
        New :class:`PlotlyPlotDisplayOptions` instance.
    """
    known = {field.name for field in fields(cls)}
    kwargs: dict[str, Any] = {
        key: value for key, value in data.items() if key in known
    }
    if "theme" in kwargs:
        kwargs["theme"] = normalize_plotly_theme(str(kwargs["theme"]))
    return cls(**kwargs)