Repository navigation
Expand file tree
/
Copy pathplotly_chart.py
More file actions
970 lines (816 loc) · 35.4 KB
/
Copy pathplotly_chart.py
File metadata and controls
970 lines (816 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
Union,
cast,
overload,
)
from streamlit import type_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib import agent_data, agent_spec
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.streamlit_plotly_theme import (
configure_streamlit_plotly_theme,
)
from streamlit.elements.lib.utils import (
Key,
compute_and_register_element_id,
normalize_alt,
to_key,
)
from streamlit.errors import StreamlitValueError
from streamlit.logger import get_logger
from streamlit.proto.PlotlyChart_pb2 import PlotlyChart as PlotlyChartProto
from streamlit.runtime.agent import json_encoding
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import (
WidgetCallback,
register_widget,
validate_on_change_mode,
)
from streamlit.util import ReadOnlyAttributeDictionary
if TYPE_CHECKING:
from collections.abc import Iterable
import plotly.graph_objs as go
from matplotlib.figure import Figure as MatplotlibFigure
from plotly.basedatatypes import BaseFigure
from streamlit.delta_generator import DeltaGenerator
# We need to configure the Plotly theme before any Plotly figures are created:
configure_streamlit_plotly_theme()
_AtomicFigureOrData: TypeAlias = Union[
"go.Figure",
"go.Data",
]
FigureOrData: TypeAlias = Union[
_AtomicFigureOrData,
list[_AtomicFigureOrData],
# It is kind of hard to figure out exactly what kind of dict is supported
# here, as plotly hasn't embraced typing yet. This version is chosen to
# align with the docstring.
dict[str, _AtomicFigureOrData],
"BaseFigure",
"MatplotlibFigure",
]
SelectionMode: TypeAlias = Literal["lasso", "points", "box"]
_SELECTION_MODES: Final[set[SelectionMode]] = {"lasso", "points", "box"}
_SELECTION_MODE_FROM_PROTO: Final[dict[int, SelectionMode]] = {
PlotlyChartProto.SelectionMode.POINTS: "points",
PlotlyChartProto.SelectionMode.BOX: "box",
PlotlyChartProto.SelectionMode.LASSO: "lasso",
}
_LOGGER: Final = get_logger(__name__)
# What a Plotly template can add to a figure's content rather than its styling,
# such as a "DRAFT" annotation. Kept when the agent API drops the rest of the
# template.
_TEMPLATE_CONTENT: Final = ("annotations", "shapes", "images")
class PlotlySelectionState(ReadOnlyAttributeDictionary):
"""
The schema for the Plotly chart selection state.
The selection state is stored in a read-only dictionary-like object that
supports both key and attribute notation. Selection states cannot be
programmatically changed or set through Session State.
Attributes
----------
points : list[dict[str, Any]]
The selected data points in the chart, including the data points
selected by the box and lasso mode. The data includes the values
associated to each point and a point index used to populate
``point_indices``. If additional information has been assigned to your
points, such as size or legend group, this is also included.
point_indices : list[int]
The numerical indices of all selected data points in the chart. The
details of each identified point are included in ``points``.
box : list[dict[str, Any]]
The metadata related to the box selection. This includes the
coordinates of the selected area.
lasso : list[dict[str, Any]]
The metadata related to the lasso selection. This includes the
coordinates of the selected area.
Example
-------
When working with more complicated graphs, the ``points`` attribute
displays additional information. Try selecting points in the following
example:
>>> import plotly.express as px
>>> import streamlit as st
>>>
>>> df = px.data.iris()
>>> fig = px.scatter(
... df,
... x="sepal_width",
... y="sepal_length",
... color="species",
... size="petal_length",
... hover_data=["petal_width"],
... )
>>>
>>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
>>>
>>> event.selection
.. output::
https://doc-chart-events-plotly-selection-state.streamlit.app
height: 600px
This is an example of the selection state when selecting a single point:
>>> {
>>> "points": [
>>> {
>>> "curve_number": 2,
>>> "point_number": 9,
>>> "point_index": 9,
>>> "x": 3.6,
>>> "y": 7.2,
>>> "customdata": [
>>> 2.5
>>> ],
>>> "marker_size": 6.1,
>>> "legendgroup": "virginica"
>>> }
>>> ],
>>> "point_indices": [
>>> 9
>>> ],
>>> "box": [],
>>> "lasso": []
>>> }
"""
points: list[dict[str, Any]]
point_indices: list[int]
box: list[dict[str, Any]]
lasso: list[dict[str, Any]]
@overload
def __getitem__(self, key: Literal["points"]) -> list[dict[str, Any]]: ...
@overload
def __getitem__(self, key: Literal["point_indices"]) -> list[int]: ...
@overload
def __getitem__(self, key: Literal["box"]) -> list[dict[str, Any]]: ...
@overload
def __getitem__(self, key: Literal["lasso"]) -> list[dict[str, Any]]: ...
@overload
def __getitem__(self, key: Any) -> Any: ...
def __getitem__(self, key: Any) -> Any:
return super().__getitem__(key)
class PlotlyState(ReadOnlyAttributeDictionary):
"""
The schema for the Plotly chart event state.
To use this type in an annotation, import it from ``streamlit.typing``.
The event state is stored in a read-only dictionary-like object that
supports both key and attribute notation. Event states cannot be
programmatically changed or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The attributes are described by ``PlotlySelectionState``.
Example
-------
Try selecting points by any of the three available methods (direct click,
box, or lasso). The current selection state is available through Session
State or as the output of the chart function.
>>> import plotly.express as px
>>> import streamlit as st
>>>
>>> df = px.data.iris()
>>> fig = px.scatter(df, x="sepal_width", y="sepal_length")
>>>
>>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
>>>
>>> event
.. output::
https://doc-chart-events-plotly-state.streamlit.app
height: 600px
"""
selection: PlotlySelectionState
# ReadOnlyAttributeDictionary routes attribute access through __getitem__,
# so the override below is enough to keep `selection` typed as
# PlotlySelectionState. Use dict.__getitem__ for the selection key so the
# read-only base class does not re-wrap the already-typed nested instance.
@overload
def __getitem__(self, key: Literal["selection"]) -> PlotlySelectionState: ...
@overload
def __getitem__(self, key: Any) -> Any: ...
def __getitem__(self, key: Any) -> Any:
if key == "selection":
item = dict.__getitem__(self, key)
if not isinstance(item, PlotlySelectionState):
item = PlotlySelectionState(item)
# Cache so repeated bracket/attribute access stays identity-stable.
dict.__setitem__(self, key, item)
return item
return super().__getitem__(key)
@dataclass
class PlotlyChartSelectionSerde:
"""PlotlyChartSelectionSerde is used to serialize and deserialize the Plotly Chart
selection state.
"""
def deserialize(self, ui_value: str | None) -> PlotlyState:
empty_selection_state = PlotlyState(
{
"selection": PlotlySelectionState(
{
"points": [],
"point_indices": [],
"box": [],
"lasso": [],
}
),
}
)
if ui_value is None:
return empty_selection_state
parsed = json.loads(ui_value)
if "selection" not in parsed: # pragma: no cover - defensive
return empty_selection_state
# Eagerly wrap selection so bracket access returns a stable typed
# instance instead of creating a shallow copy on every access.
parsed["selection"] = PlotlySelectionState(parsed["selection"])
return PlotlyState(parsed)
def serialize(self, selection_state: PlotlyState) -> str:
return json.dumps(selection_state, default=str)
def parse_selection_mode(
selection_mode: SelectionMode | Iterable[SelectionMode],
) -> set[PlotlyChartProto.SelectionMode.ValueType]:
"""Parse and check the user provided selection modes."""
if isinstance(selection_mode, str):
# Only a single selection mode was passed
selection_mode_set = {selection_mode}
else:
# Multiple selection modes were passed
selection_mode_set = set(selection_mode)
if not selection_mode_set.issubset(_SELECTION_MODES):
raise StreamlitValueError(
"selection_mode",
[f"'{mode}'" for mode in sorted(_SELECTION_MODES)],
)
parsed_selection_modes = []
for mode in selection_mode_set:
if mode == "points":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.POINTS)
elif mode == "lasso":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.LASSO)
elif mode == "box":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.BOX)
return set(parsed_selection_modes)
def _resolve_content_width(width: Width, figure: Any) -> Width:
"""Resolve "content" width by inspecting the figure's layout width.
For content width, we check if the plotly figure has an explicit width
in its layout. If so, we use that as a pixel width. If not, we default
to 700 pixels which matches the plotly.js default width.
Args
----
width : Width
The original width parameter
figure : Any
The plotly figure object (Figure, dict, or other supported formats)
Returns
-------
Width
The resolved width (either original width, figure width as pixels, or 700)
"""
if width != "content":
return width
# Extract width from the figure's layout
# plotly.tools.mpl_to_plotly() returns Figure objects with .layout attribute
# plotly.tools.return_figure_from_figure_or_data() returns dictionaries
figure_width = None
if isinstance(figure, dict):
figure_width = figure.get("layout", {}).get("width")
else:
# Handle Figure objects from matplotlib conversion
try:
figure_width = figure.layout.width
except (AttributeError, TypeError):
_LOGGER.debug("Could not parse width from figure")
if (
figure_width is not None
and isinstance(figure_width, (int, float))
and figure_width > 0
):
return int(figure_width)
# Default to 700 pixels (plotly.js default) when no width is specified
return 700
def _resolve_content_height(height: Height, figure: Any) -> Height:
"""Resolve "content" height by inspecting the figure's layout height.
For content height, we check if the plotly figure has an explicit height
in its layout. If so, we use that as a pixel height. If not, we default
to 450 pixels which matches the plotly.js default height.
Args
----
height : Height
The original height parameter
figure : Any
The plotly figure object (Figure, dict, or other supported formats)
Returns
-------
Height
The resolved height (either original height, figure height as pixels, or 450)
"""
if height != "content":
return height
# Extract height from the figure's layout
# plotly.tools.mpl_to_plotly() returns Figure objects with .layout attribute
# plotly.tools.return_figure_from_figure_or_data() returns dictionaries
figure_height = None
if isinstance(figure, dict):
figure_height = figure.get("layout", {}).get("height")
else:
# Handle Figure objects from matplotlib conversion
try:
figure_height = figure.layout.height
except (AttributeError, TypeError):
_LOGGER.debug("Could not parse height from figure")
if (
figure_height is not None
and isinstance(figure_height, (int, float))
and figure_height > 0
):
return int(figure_height)
# Default to 450 pixels (plotly.js default) when no height is specified
return 450
def _plotly_data(spec_json: str) -> dict[str, Any] | None:
"""A Plotly figure's agent ``data``, whose values live inside its specification.
The theme is dropped, because it is weight without meaning for a non-visual
client: Plotly's `layout.template` is about nine tenths of a small figure.
Dropping it is named in `spec_omitted`, so a client can tell a trimmed
figure from one the app never configured. A template can also carry
content, such as a "DRAFT" annotation, and that is kept.
Nothing beyond the template is dropped, at any size: the specification
holds the figure's values, so trimming further would remove the only part
worth reading, and a large figure is large because it plots a lot of data,
the same bytes the app already sends its own client. The figure is
therefore `complete`, and a client has no `url` to look for.
"""
spec = agent_data.parse_spec(spec_json)
if spec is None:
return None
data: dict[str, Any] = {}
layout = spec.get("layout") if isinstance(spec, dict) else None
if isinstance(layout, dict) and "template" in layout:
template = layout["template"]
template_layout = template.get("layout") if isinstance(template, dict) else None
if not isinstance(template_layout, dict):
template_layout = {}
content = {
name: template_layout[name]
for name in _TEMPLATE_CONTENT
if template_layout.get(name)
}
trimmed_layout = {
name: value for name, value in layout.items() if name != "template"
}
if content:
trimmed_layout["template"] = {"layout": content}
data["spec_omitted"] = [
f"layout.template.{name}" for name in template if name != "layout"
] + [
f"layout.template.layout.{name}"
for name in template_layout
if name not in content
]
else:
data["spec_omitted"] = ["layout.template"]
spec = {**spec, "layout": trimmed_layout}
data["spec"] = _expand_typed_arrays(spec)
data["complete"] = True
return data
def _expand_typed_arrays(value: Any) -> Any:
"""Expand Plotly's base64 typed arrays into lists of numbers, at any depth.
Plotly writes a NumPy array as `{"dtype": "f8", "bdata": "<base64>"}`,
which a browser decodes and a language model cannot read. Those arrays are
the values that make a figure `complete`, so they are reported as numbers,
at the cost of a longer specification.
"""
if isinstance(value, list):
return [_expand_typed_arrays(item) for item in value]
if not isinstance(value, dict):
return value
if (
isinstance(value.get("bdata"), str)
and isinstance(value.get("dtype"), str)
and set(value) <= {"bdata", "dtype", "shape"}
):
try:
return _decode_typed_array(value)
except Exception:
_LOGGER.debug("Could not decode a Plotly typed array.", exc_info=True)
return value
return {name: _expand_typed_arrays(item) for name, item in value.items()}
def _decode_typed_array(value: dict[str, Any]) -> Any:
"""Decode a Plotly base64 typed array (``bdata``) into JSON-compatible values."""
import base64
import numpy as np
# Plotly.js reads these buffers as little-endian.
dtype = np.dtype(value["dtype"]).newbyteorder("<")
array = np.frombuffer(base64.b64decode(value["bdata"]), dtype=dtype)
if shape := value.get("shape"):
dims = shape if isinstance(shape, list) else str(shape).split(",")
array = array.reshape([int(dim) for dim in dims])
# Through the JSON encoding, so a NaN in a float array becomes null.
return json_encoding.to_json_value(array.tolist())
class PlotlyMixin:
@overload
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["ignore"] = "ignore",
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
config: dict[str, Any] | None = None,
alt: str | None = None,
) -> DeltaGenerator: ...
@overload
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
# No default: omitted on_select must match the "ignore" overload.
on_select: Literal["rerun"] | WidgetCallback,
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
config: dict[str, Any] | None = None,
alt: str | None = None,
) -> PlotlyState: ...
@gather_metrics("plotly_chart")
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
config: dict[str, Any] | None = None,
alt: str | None = None,
) -> DeltaGenerator | PlotlyState:
"""Display an interactive Plotly chart.
`Plotly <https://plot.ly/python>`_ is a charting library for Python.
To show Plotly charts in Streamlit, pass a Plotly ``Figure`` or
``Data`` object to ``st.plotly_chart``.
.. Important::
You must install ``plotly>=4.0.0`` to use this command. Your app's
performance may be enhanced by installing ``orjson`` as well. You
can install all charting dependencies as an extra
with Streamlit:
.. code-block:: shell
pip install streamlit[charts]
Parameters
----------
figure_or_data : plotly.graph_objs.Figure, plotly.graph_objs.Data,\
or dict/list of plotly.graph_objs.Figure/Data
The Plotly ``Figure`` or ``Data`` object to render. See
https://plot.ly/python/ for examples of graph descriptions.
.. note::
If your chart contains more than 1000 data points, Plotly will
use a WebGL renderer to display the chart. Different browsers
have different limits on the number of WebGL contexts per page.
If you have multiple WebGL contexts on a page, you may need to
switch to SVG rendering mode. You can do this by setting
``render_mode="svg"`` within the figure. For example, the
following code defines a Plotly Express line chart that will
render in SVG mode when passed to ``st.plotly_chart``:
``px.line(df, x="x", y="y", render_mode="svg")``.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element expands to fill the
available vertical space in its parent container. When multiple
elements with stretch height are in the same vertical container,
they share the available vertical space evenly. Inside a
container that already has a fixed height, the chart keeps no
minimum height and can shrink to zero when the other elements
fill the container. Use an integer height to keep the chart
visible there. Otherwise, the chart uses its figure's
``layout.height``, or 450 pixels when the figure does not set
one, and still grows to match a taller sibling.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the figure's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the value of ``width``.
- ``True``: Streamlit sets the width of the figure to match the
width of the parent container.
- ``False``: Streamlit sets the width of the figure to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
theme : "streamlit" or None
The theme of the chart. If ``theme`` is ``"streamlit"`` (default),
Streamlit uses its own design default. If ``theme`` is ``None``,
Streamlit falls back to the default behavior of the library.
The ``"streamlit"`` theme can be partially customized through the
configuration options ``theme.chartCategoricalColors`` and
``theme.chartSequentialColors``. Font configuration options are
also applied.
key : str, int, or None
An optional string to use for giving this element a stable
identity. If this is ``None`` (default), the element's identity
will be determined based on the values of the other parameters.
If selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only. For more
details, see `Widget behavior
<https://docs.streamlit.io/develop/concepts/architecture/widget-behavior>`_.
Additionally, if ``key`` is provided, it will be used as a
CSS class name prefixed with ``st-key-``.
on_select : "ignore" or "rerun" or callable
How the figure should respond to user selection events. This
controls whether or not the figure behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the chart. The figure will not behave like an input
widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
data in the chart. In this case, ``st.plotly_chart`` will return
the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the
``callable`` as a callback function before the rest of the app.
In this case, ``st.plotly_chart`` will return the selection data
as a dictionary.
selection_mode : "points", "box", "lasso" or an Iterable of these
The selection mode of the chart. This can be one of the following:
- ``"points"``: The chart will allow selections based on individual
data points.
- ``"box"``: The chart will allow selections based on rectangular
areas.
- ``"lasso"``: The chart will allow selections based on freeform
areas.
- An ``Iterable`` of the above options: The chart will allow
selections based on the modes specified.
All selections modes are activated by default.
config : dict or None
A dictionary of Plotly configuration options. This is passed to
Plotly's ``show()`` function. For more information about Plotly
configuration options, see Plotly's documentation on `Configuration
in Python <https://plotly.com/python/configuration-options/>`_.
alt : str or None
A description of the chart for screen readers and other assistive
technologies. If this is ``None`` (default), Streamlit does not
provide an accessible name for the chart.
An empty or whitespace-only string is treated the same as ``None``
and is logged so authors notice the dual meaning of ``alt=""``
across commands (decorative only on ``st.image`` / ``st.pyplot``).
Prefer a short, specific description; a vague one can be worse than
none. This is a short description of the chart, not a full text
alternative for dense graphics.
Returns
-------
element or PlotlyState
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the chart element. Otherwise, this command
returns a ``PlotlyState`` object. This object is dictionary-like
and supports both key and attribute notation. To use this type in
an annotation, import it from ``streamlit.typing``.
Examples
--------
**Example 1: Basic Plotly chart**
The example below comes from the examples at https://plot.ly/python.
Note that ``plotly.figure_factory`` requires ``scipy`` to run.
>>> import plotly.figure_factory as ff
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> hist_data = [
... rng(0).standard_normal(200) - 2,
... rng(1).standard_normal(200),
... rng(2).standard_normal(200) + 2,
... ]
>>> group_labels = ["Group 1", "Group 2", "Group 3"]
>>>
>>> fig = ff.create_distplot(
... hist_data, group_labels, bin_size=[0.1, 0.25, 0.5]
... )
>>>
>>> st.plotly_chart(
... fig, alt="Distribution of three groups of random samples"
... )
.. output::
https://doc-plotly-chart.streamlit.app/
height: 550px
**Example 2: Plotly Chart with configuration**
By default, Plotly charts have scroll zoom enabled. If you have a
longer page and want to avoid conflicts between page scrolling and
zooming, you can use Plotly's configuration options to disable scroll
zoom. In the following example, scroll zoom is disabled, but the zoom
buttons are still enabled in the modebar.
>>> import plotly.graph_objects as go
>>> import streamlit as st
>>>
>>> fig = go.Figure()
>>> fig.add_trace(
... go.Scatter(
... x=[1, 2, 3, 4, 5],
... y=[1, 3, 2, 5, 4]
... )
... )
>>>
>>> st.plotly_chart(fig, config = {'scrollZoom': False})
.. output::
https://doc-plotly-chart-config.streamlit.app/
height: 550px
"""
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
elif not isinstance(width, int):
width = "content"
validate_width(width, allow_content=True)
validate_height(height, allow_content=True)
import plotly.io
import plotly.tools
# NOTE: "figure_or_data" is the name used in Plotly's .plot() method
# for their main parameter. I don't like the name, but it's best to
# keep it in sync with what Plotly calls it.
if theme not in {"streamlit", None}:
raise StreamlitValueError("theme", ["'streamlit'", "None"])
on_select_callback = validate_on_change_mode(
on_select,
supported_modes=("rerun", "ignore"),
none_supported=False,
param_name="on_select",
)
key = to_key(key)
is_selection_activated = on_select != "ignore"
if is_selection_activated:
# Run some checks that are only relevant when selections are activated
is_callback = on_select_callback is not None
check_widget_policies(
self.dg,
key,
on_change=on_select_callback,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=is_callback,
)
if type_util.is_type(figure_or_data, "matplotlib.figure.Figure"):
# Convert matplotlib figure to plotly figure:
figure = plotly.tools.mpl_to_plotly(figure_or_data)
else:
figure = plotly.tools.return_figure_from_figure_or_data(
figure_or_data, validate_figure=True
)
plotly_chart_proto = PlotlyChartProto()
plotly_chart_proto.theme = theme or ""
plotly_chart_proto.form_id = current_form_id(self.dg)
config = config or {}
plotly_chart_proto.spec = plotly.io.to_json(figure, validate=False)
plotly_chart_proto.config = json.dumps(config)
normalized_alt = normalize_alt(alt)
if normalized_alt is not None:
# Carry alt on its own proto field so it is not baked into the
# wire spec JSON (frontend applies it as the chart accessible name).
plotly_chart_proto.alt = normalized_alt
ctx = get_script_run_ctx()
# Compute an ID for every Plotly chart so the frontend can restore
# state after remount. Always hash command kwargs (including alt),
# even when the author set a key, so changing alt remounts the chart.
plotly_chart_proto.id = compute_and_register_element_id(
"plotly_chart",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
plotly_spec=plotly_chart_proto.spec,
plotly_config=plotly_chart_proto.config,
selection_mode=selection_mode,
is_selection_activated=is_selection_activated,
theme=theme,
width=width,
height=height,
alt=normalized_alt,
)
# Handle "content" width and height by inspecting the figure's natural dimensions
final_width = _resolve_content_width(width, figure)
final_height = _resolve_content_height(height, figure)
if is_selection_activated:
# Selections are activated, treat plotly chart as a widget:
plotly_chart_proto.selection_mode.extend(
parse_selection_mode(selection_mode)
)
serde = PlotlyChartSelectionSerde()
widget_state = register_widget(
plotly_chart_proto.id,
on_change_handler=on_select_callback,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
layout_config = LayoutConfig(width=final_width, height=final_height)
self.dg._enqueue(
"plotly_chart",
plotly_chart_proto,
layout_config=layout_config,
agent_props=agent_spec.element(
"plotly_chart",
key=plotly_chart_proto.id,
data_builder=lambda: _plotly_data(plotly_chart_proto.spec),
support="action_unsupported",
selection_mode=sorted(
_SELECTION_MODE_FROM_PROTO[mode]
for mode in plotly_chart_proto.selection_mode
)
or None,
# A callback reaches the server too, so it is "rerun".
on_select="rerun",
alt=plotly_chart_proto.alt or None,
),
)
return widget_state.value
layout_config = LayoutConfig(width=final_width, height=final_height)
return self.dg._enqueue(
"plotly_chart",
plotly_chart_proto,
layout_config=layout_config,
agent_props=agent_spec.element(
"plotly_chart",
key=key,
data_builder=lambda: _plotly_data(plotly_chart_proto.spec),
alt=plotly_chart_proto.alt or None,
),
)
@property
def dg(self) -> DeltaGenerator:
"""The associated DeltaGenerator."""
return cast("DeltaGenerator", self)