Hello Streamlit Community,
I’m working on a Streamlit application where I plot time-series data using Plotly and enable the user to zoom or select date ranges. My goal is to store the selected date ranges in a list every time the user interacts with the plot (zooms or selects a range).
Here’s a simplified version of my code:
def plot_load_profile(
self,
*profiles: StandardLoadProfile,
add_annotation:bool=True,
rangeslider_visible=False
) -> go.Figure:
"""Plot the load profile for given profiles."""
fig = go.Figure()
list_profiles = []
for i, profile in enumerate(profiles):
profile_value = pd.DataFrame(profile.value)
name = profile.name if profile.name else f"Profile {i+1}"
color_line = profile.color if profile.color else None
list_profiles.append(profile)
line = (
{
"color": color_line,
"width": 0.6 + i / 500,
}
if profile.name == "Cleaned"
or profile.name == "Original"
else {"color": color_line}
)
fig.add_trace(
go.Scatter(
x=profile_value.index,
y=profile_value[profile_value.columns[0]],
mode="lines",
line=line,
name=name,
showlegend=True,
)
)
fig.update_layout(title=list_profiles[0].title, xaxis_nticks=24)
fig.update_layout(xaxis_title="Time", yaxis_title="Demand kW")
if add_annotation:
fig = self._add_annotation(fig, list_profiles[0])
for trace in fig.data:
self.name.append(trace.name)
self.color.append(trace.line.color)
self.profile_value.append(trace.y)
self._rangeselector(fig, rangeslider_visible)
st.plotly_chart(fig, use_container_width=True)
return fig
def _rangeselector(self, fig, rangeslider_visible:bool=False):
"""Apply rangeselector to fig."""
fig.update_xaxes(
matches="x",
rangeslider_visible=rangeslider_visible,
rangeselector={
"buttons": [
{
"count": 1,
"label": "1d",
"step": "day",
"stepmode": "backward",
},
{
"count": 7,
"label": "7d",
"step": "day",
"stepmode": "backward",
},
{
"count": 1,
"label": "1m",
"step": "month",
"stepmode": "backward",
},
{
"count": 6,
"label": "6m",
"step": "month",
"stepmode": "backward",
},
{
"count": 1,
"label": "1y",
"step": "year",
"stepmode": "backward",
},
]
},
)
My Question:
How can I track Plotly relayout events in Streamlit when a user zooms or selects a date range on the chart?
Thanks in advance for your help!