I want to be able to highlight a section of a plotly datetime plot by holding down a key on my keyboard and selecting the section with my mouse. I then want a button that will store the datetime range of the highlighted section into a dataframe.
To upload files, please first save the app
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
# Create sample datetime data
if 'data' not in st.session_state:
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
values = np.random.randn(len(dates)).cumsum()
st.session_state.data = pd.DataFrame({
'date': dates,
'value': values
})
# Initialize stored selections if not exists
if 'stored_selections' not in st.session_state:
st.session_state.stored_selections = pd.DataFrame(columns=['start_date', 'end_date'])
# Create the plot
fig = px.line(st.session_state.data, x='date', y='value', title='Time Series Data')
# Update layout to enable selection
fig.update_layout(
dragmode='select',
selectdirection='h', # horizontal selection
hovermode='x'
)
# Display the plot with selection enabled
selection = st.plotly_chart(
fig,
use_container_width=True,
key="timeseries",
on_select="rerun"
)
# Check if there's a selection
if selection is not None and selection.box:
# Extract the datetime range from the selection
x0, x1 = selection.box[0], selection.box[2]
# Convert to datetime if they're timestamps
start_date = pd.to_datetime(x0)
end_date = pd.to_datetime(x1)
# Create a button to store the selection
if st.button('Store Selected Range'):
new_selection = pd.DataFrame({
'start_date': [start_date],
'end_date': [end_date]
})
st.session_state.stored_selections = pd.concat([
st.session_state.stored_selections,
new_selection
]).reset_index(drop=True)
st.success('Selection stored!')
# Display stored selections
if not st.session_state.stored_selections.empty:
st.subheader('Stored Time Ranges')
st.dataframe(st.session_state.stored_selections)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?