Plotly on_select to update current plot

I would like to add annotations to the plot upon selection of the points
what i tried:

    test_data = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [2, 3, 4, 5, 1]})
    fig = px.scatter(test_data, x="x", y="y")
    fig.update_layout(dragmode="lasso", hovermode="closest")

    fig_selected = st.plotly_chart(
        fig, on_select="rerun", selection_mode="lasso", key="selected"
    )
    for i in fig_selected["selection"]["points"]:
        fig.add_annotation(x=i["x"], y=i["y"], text="1")

   # st.write(fig) #this does show the annotations

the second plot does show y annotations, fut the first one does not re-render with the annotations

any suugestions?

From the session state, you can access the plotly state dictionary (PlotlyState in the docs) using the key argument passed to st.plotly_chart.

plotly_select

Code:
import streamlit as st
import pandas as pd
import plotly.express as px

st.title("Plotly selections")
test_data = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [2, 3, 4, 5, 1]})

fig = px.scatter(test_data, x="x", y="y")
fig.update_layout(dragmode="lasso", hovermode="closest")

if "fig_state" in st.session_state:
    for i in st.session_state.fig_state["selection"]["points"]:
        fig.add_annotation(x=i["x"], y=i["y"], text="Hello ⭐")

st.plotly_chart(
    fig,
    use_container_width=True,
    on_select="rerun",
    selection_mode="lasso",
    key="fig_state",
)
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.