Created
April 6, 2022 15:06
-
-
Save akirayou/0c71ed487eac2eff7d517750283f7672 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import session | |
import streamlit as st | |
import plotly.express as px | |
import pandas as pd | |
from streamlit_plotly_events import plotly_events | |
import numpy as np | |
#乱数のダミーデータがパラメータ変更毎に変更されるとうざいのでcacheする | |
@st.cache | |
def get_data(): | |
x = np.arange(1000) | |
y = np.random.randn(1000) | |
df=[] | |
df= pd.DataFrame(df) | |
df['time']= x | |
df['inten']= y | |
return df | |
df=get_data() | |
x=df["time"] | |
y=df["inten"] | |
#グラフを作るが、表示するのはplotly_events関数 | |
fig = px.line(df, x="time", y="inten", title='graph',markers=True) | |
fig.update_traces(marker={'size': 1}) | |
#デフォルトの選択範囲 | |
if "range" not in st.session_state: | |
st.session_state.range=(0,0) | |
#選択範囲を赤く染める | |
fig.update_layout( | |
shapes=[ | |
dict( | |
type="rect", | |
xref="x", | |
yref="y", | |
x0=st.session_state.range[0], | |
y0=np.max(y), | |
x1=st.session_state.range[1], | |
y1=np.min(y), | |
fillcolor="pink", | |
opacity=1.0, | |
line_width=0, | |
layer="below" | |
), | |
] | |
) | |
#選択モードをデフォルトにしておく | |
fig.update_layout(dragmode="select") | |
selected = plotly_events(fig,key="graph_select",click_event=False, select_event=True) | |
#選択されているmarkerがあったらその範囲の最大最小を範囲としてsession_state.rangeに記録 | |
if len (selected)>0: | |
xs=[s["x"] for s in selected] | |
st.session_state.range=(min(xs),max(xs)) | |
del st.session_state["graph_select"] #無限ループしないように、plotly_eventsのデータを消す必要がある | |
st.experimental_rerun() #上のグラフを書き換えるために強制reload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment