Coming soon: chart selections

Hey all! :wave:

Weโ€™re excited to share a prototype for chart selections. This new feature will let your users select data points or areas in charts and return expose that event on the Python side. The current prototype works for both Plotly and Altair charts. :chart_with_upwards_trend:

You can find the demo app with instructions here: https://chart-selections-demo.streamlit.app/

CleanShot 2024-04-09 at 00.06.17

How it works

TLDR: It works just like any other input widget!

To enable selections for your chart, you need to use the new on_select parameter for
st.plotly_chart or st.altair_chart. There are 3 ways to use this parameter and
retrieve the selection data:

  1. Using return values: Set on_select="rerun" or on_select=True. Then,
    Streamlit will rerun the script whenever you select a point in the chart, and
    return the selected data in a dict-like object:

    event_data = st.plotly_chart(fig, on_select="rerun")
    st.write(event_data)
    

    This works just like a return value youโ€™d get from a slider or text input! The
    selection data is stored under event_data["select"]. You can also use dot
    notation for this dict (e.g. event_data.select), similar to how
    st.session_state or st.secrets work.

  2. Using session state: If you additionally set the new key parameter, Streamlit
    will store the event data in session state (in addition to returning it):

    st.plotly_chart(fig, on_select="rerun", key="my_chart")
    st.write(st.session_state.my_chart)
    

    This is the same behavior as for any other input widget if you set key. The
    session state value is just the same dict as the return value (event_dict
    in the example above).

  3. Using callbacks: You can also pass a callback function to on_select. Just like
    with other callbacks in Streamlit (e.g. on_change), this callback function
    will be executed before the rest of the script reruns:

    def callback():
        st.write("Hello from the callback!")
        st.write(st.session_state.my_chart)
    
    st.plotly_chart(fig, on_select=callback, key="my_chart")
    

Timeline

Weโ€™re finishing up the implementation now and are thinking through how we can extend this API to other selections/events in the future. This will take a bit, so Iโ€™d guess we will release an experimental version in the next 1-2 months. There are also a few improvements (e.g. making chart selections work with forms or with app testing) that we might ship as follow-ups.

Feedback

Please let us know what you think, no matter if positive or negative. You can comment below or on the GitHub issue. Also, let us know if you find any bugs!

Happy Streamlit-ing! :balloon:

8 Likes

Iam waiting for this feature badly โ€ฆ