Plotly linechart functionalities

I want to create multiple interactive linecharts that can influence each other. This is what i am trying to imitate: https://run.gfstool.com/output/GFS_IndicatorsTool/get_Indicators/cbcdd4cb62740556029a6f0c7b5df72c/interactive_plot_copy.html

.selection of st.plotly_chart seems to be the function im looking for so i wrote a short test script to see if it works:

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

# Create example dataset
data = {
    'Year': ['2000', '2000', '2000', '2010', '2010', '2010', '2020', '2020', '2020'],
    'Value': [100, 150, 200, 110, 160, 210, 120, 170, 220],
    'pop': ['pop_1', 'pop_2', 'pop_3', 'pop_1', 'pop_2', 'pop_3', 'pop_1', 'pop_2', 'pop_3']
}

habitat_area = pd.DataFrame(data)

# Create line plot
fig = px.line(habitat_area, x='Year', y='Value', color='pop', title='Habitat Area')

# Display plot in Streamlit
event = st.plotly_chart(fig, key="habitat", on_select="rerun")

# Access the selected data
if event:
    selected_data = event.selection
    st.write("Selected data:", selected_data)

Unfortunately the .selection function does not seem to work with linecharts and does not return any information on the interacted part of the chart. Is this an error on my side or is there any other method to achieve this?

Best wishes,
Simon

You can update the figure to show the point markers and enable selection. (If you want to hide the points, you can style them transparently, but I think they need to “exist” to be selected.)

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

# Create example dataset
data = {
    'Year': ['2000', '2000', '2000', '2010', '2010', '2010', '2020', '2020', '2020'],
    'Value': [100, 150, 200, 110, 160, 210, 120, 170, 220],
    'pop': ['pop_1', 'pop_2', 'pop_3', 'pop_1', 'pop_2', 'pop_3', 'pop_1', 'pop_2', 'pop_3']
}

habitat_area = pd.DataFrame(data)

# Create line plot
fig = px.line(habitat_area, x='Year', y='Value', color='pop', title='Habitat Area')
fig.update_layout(clickmode='select') ### Add this ###
fig.update_traces(mode="lines+markers") ### And this ###

# Display plot in Streamlit
event = st.plotly_chart(fig, key="habitat", on_select="rerun")

# Access the selected data
if event:
    selected_data = event.selection
    st.write("Selected data:", selected_data)
1 Like