L idhUddlmZddlZddlmZddlmZmZmZm Z m Z m Z m Z m Z mZddlmZddlmZddlmZmZddlmZdd lmZmZmZdd lmZdd lmZdd l m!Z!m"Z"m#Z#dd l$m%Z%ddl&m'Z'ddl(m)Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0m1Z1ddl2m3Z3erddl4m5Z5ddl6Z7ddl8m9Z:ddl;mZ>ee dZ?de@d<e e?eAe?eBeCe?fddfZDde@d<e dZEde@d<hdZFd e@d!<e'eGZHd"e@d#<Gd$d%e d&'ZIGd(d)e d&'ZJeGd*d+ZK d0d,ZLd1d-ZMGd.d/ZNy)2) annotationsN) dataclass) TYPE_CHECKINGAnyFinalLiteral TypeAlias TypedDictUnioncastoverload)Required) type_util)make_deprecated_name_warningshow_deprecation_warning)current_form_id) LayoutConfigWidthvalidate_width)check_widget_policies) configure_streamlit_plotly_theme)Keycompute_and_register_element_idto_key)StreamlitAPIException) get_logger) PlotlyChart)gather_metrics)get_script_run_ctx)WidgetCallbackregister_widget)AttributeDictionary)Iterable) BaseFigure)DeltaGenerator)z go.Figurezgo.Datar _AtomicFigureOrDatar$zmpl.figure.Figure FigureOrData)lassopointsbox SelectionMode>r*r(r)zFinal[set[SelectionMode]]_SELECTION_MODESr_LOGGERc:eZdZUdZded<ded<ded<ded<y) PlotlySelectionStateat The schema for the Plotly chart selection state. The selection state is stored in a 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": [] >>> } zRequired[list[dict[str, Any]]]r)zRequired[list[int]] point_indicesr*r(N__name__ __module__ __qualname____doc____annotations__e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/streamlit/elements/plotly_chart.pyr/r/Zs#Ob +*&& '' ))r8r/F)totalceZdZUdZded<y) PlotlyStatea The schema for the Plotly chart event state. The event state is stored in a 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 the ``PlotlySelectionState`` dictionary schema. 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 zRequired[PlotlySelectionState] selectionNr1r7r8r9r<r<s%N.-r8r<c eZdZdZddZddZy)PlotlyChartSelectionSerdeziPlotlyChartSelectionSerde is used to serialize and deserialize the Plotly Chart selection state. cdggggdi}||n'tdttj|}d|vr|}tdt|S)Nr=)r)r0r*r(r<)r r"jsonloads)selfui_valueempty_selection_stateselection_states r9 deserializez%PlotlyChartSelectionSerde.deserializesk !# .  "m%8H9M%NO  o -3OM#6#GHHr8c8tj|tS)N)default)rAdumpsstr)rCrFs r9 serializez#PlotlyChartSelectionSerde.serializeszz/377r8N)rDz str | Nonereturnr<)rFr<rMrK)r2r3r4r5rGrLr7r8r9r?r?sI*8r8r?ct|tr|h}n t|}|jtst d|dtg}|D]}|dk(r*|j tjj2|dk(r*|j tjja|dk(sg|j tjjt|S)z2Parse and check the user provided selection modes.zInvalid selection mode: z. Valid options are: r)r(r*) isinstancerKsetissubsetr,rappendPlotlyChartProtor+POINTSLASSOBOX)selection_modeselection_mode_setparsed_selection_modesmodes r9parse_selection_moder[s.#&,-!0  & &'7 8#&~&67""2!3 5   "N 8  " ) )*:*H*H*O*O P W_ " ) )*:*H*H*N*N O U] " ) )*:*H*H*L*L M N % &&r8cL|dk7r|Sd}t|tr"|jdijd}n |jj}|&t|ttfr|dkDr t|Sy#t t f$rtjdYOwxYw)a6Resolve "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) contentNlayoutwidthz!Could not parse width from figureri) rOdictgetr^r_AttributeError TypeErrorr-debugintfloat)r_figure figure_widths r9_resolve_content_widthris(  L&$zz(B/33G<  ?!==..L  |c5\ 2 1 <    * ? MM= > ?sA<<$B#"B#c eZdZe dddddd ddZe ddddddd dd Zed  ddddd ddd  dd ZeddZy) PlotlyMixinNstretch streamlit)r)r*r()r_themekeyrWc yNr7 rCfigure_or_datause_container_widthr_rnro on_selectrWkwargss r9 plotly_chartzPlotlyMixin.plotly_chartHs r8rerun)r_rnrorurWc yrqr7rrs r9rwzPlotlyMixin.plotly_chartZs r8rwignore)r_rnrorurWconfigc P|2ttdddddd|rd }nt|tsd }t |d d dl} d dl} | r td|dvrtd|d|dvrt|std|dt|}|dk7} | r4t|} t|j|| r td|nddd| tj|dr| jj!|} n| jj#|d } t%}|xsd|_t)|j|_|xsi}| j,j/| d|_t3j4||_t9}t;d|d|j|j0|j6|| || |_t?|| }| r|j@jCtE|tG}tI|j<t|r|nd|jJ|jL|d}tO| }|jjQd||!|jRStO| }|jjQd||!S)"a^"Display an interactive Plotly chart. `Plotly `_ is a charting library for Python. The arguments to this function closely follow the ones for Plotly's ``plot()`` function. To show Plotly charts in Streamlit, call ``st.plotly_chart`` wherever you would call Plotly's ``py.plot`` or ``py.iplot``. .. 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 (except Bokeh) 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. 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 An optional string to use for giving this element a stable identity. If ``key`` is ``None`` (default), this element's identity will be determined based on the values of the other parameters. Additionally, 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. 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 `_. **kwargs Additional arguments accepted by Plotly's ``plot()`` function. This supports ``config``, a dictionary of Plotly configuration options. For more information about Plotly configuration options, see Plotly's documentation on `Configuration in Python `_. .. deprecated:: ``**kwargs`` are deprecated and will be removed in a future release. Use ``config`` instead. Returns ------- element or dict If ``on_select`` is ``"ignore"`` (default), this command returns an internal placeholder for the chart element. Otherwise, this command returns a dictionary-like object that supports both key and attribute notation. The attributes are described by the ``PlotlyState`` dictionary schema. 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) .. 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 Nrtr_z 2025-12-31znFor `use_container_width=True`, use `width='stretch'`. For `use_container_width=False`, use `width='content'`.F)include_st_prefix)show_in_browserrlr]T) allow_contentrzThe keyword arguments have been deprecated and will be removed in a future release. Use `config` instead to specify Plotly configuration options.)rmNzYou set theme="us" while Streamlit charts only support theme=”streamlit” or theme=None to fallback to the default library theme.)rzrxzYou have passed zH to `on_select`. But only 'ignore', 'rerun', or a callable is supported.rzr ) on_change default_valuewrites_allowedenable_check_callback_ruleszmatplotlib.figure.Figure)validate_figure)validaterw) user_keykey_as_main_identitydg plotly_spec plotly_configrWis_selection_activatedrnr_ string_value)on_change_handler deserializer serializerctx value_type)r_) layout_config)*rrrOrer plotly.io plotly.toolsrcallablerrrr ris_typetools mpl_to_plotly!return_figure_from_figure_or_datarSrnrform_idioto_jsonspecrArJr{rridrirWextendr[r?r!rGrLr_enqueuevalue)rCrsrtr_rnrorurWr{rvplotlyr is_callbackrgplotly_chart_protor final_widthserde widget_staters r9rwzPlotlyMixin.plotly_chartlsp  * $,) N&+ !& #!s+!uD1  $)  + +'!%)!!  / /8K'"9+.77  Sk!*h!6 !#9-K !?J$/;PT"$,7     ^-G H\\//?F\\CCDF./#(;B %4TWW%="2"())"3"3FU"3"K$(JJv$6! " !@ !&ww*//,33)#9 ! -UF; !  - - 4 4$^4 ./E*"%%/7 /B)".. ??) L){;M GG   2-   %% %$;7 ww .m   r8ctd|S)zGet our DeltaGenerator.r%)r )rCs r9rzPlotlyMixin.dgs$d++r8rq)rsr'rt bool | Noner_rrnLiteral['streamlit'] | Nonero Key | NoneruzLiteral['ignore']rW'SelectionMode | Iterable[SelectionMode]rvrrMr%)rsr'rtrr_rrnrrorruz!Literal['rerun'] | WidgetCallbackrWrrvrrMr<)rsr'rtrr_rrnrrorruz+Literal['rerun', 'ignore'] | WidgetCallbackrWrr{zdict[str, Any] | NonervrrMzDeltaGenerator | PlotlyState)rMr%)r2r3r4r rwrpropertyrr7r8r9rkrkGs ,0 !-8C $)   + %@ ",0 !-87>C $)   + 5@ "N#,0T !-8AIC )-T $T )T  T + T T ?T @T &T T &!T $T l ,,r8rk)rWrrMz-set[PlotlyChartProto.SelectionMode.ValueType])r_rrgrrMr)O __future__rrA dataclassesrtypingrrrrr r r r r typing_extensionsrrmrstreamlit.deprecation_utilrr!streamlit.elements.lib.form_utilsr#streamlit.elements.lib.layout_utilsrrrstreamlit.elements.lib.policiesr-streamlit.elements.lib.streamlit_plotly_themerstreamlit.elements.lib.utilsrrrstreamlit.errorsrstreamlit.loggerrstreamlit.proto.PlotlyChart_pb2rrSstreamlit.runtime.metrics_utilr7streamlit.runtime.scriptrunner_utils.script_run_contextrstreamlit.runtime.stater r!streamlit.utilr"collections.abcr# matplotlibmplplotly.graph_objs graph_objsgoplotly.basedatatypesr$streamlit.delta_generatorr%r&r6listr`rKr'r+r,r2r-r/r<r?r[rirkr7r8r9rs\# !   '> BVU2'K9VC.("/8!"!&"Y   ! !"  i ##;< y<.H+HH%%U*9EU*p(.)5(.V 88 8<';'2'8,^,,r8