요약하면 드롭 다운에 3 가지 옵션이 표시됩니다. 하나는 원래의 일일 시간 단계, 두 번째는 월별 평균 리샘플링 된 일일 데이터, 세 번째는 선택할 수있는 연간 평균 값입니다.
지금까지 내가 가지고있는 모든 코드는 다음과 같습니다.
import pandas as pd
import numpy as np
from numpy import random
import plotly.express as px
import cufflinks as cf
random.seed(30)
df = pd.DataFrame({
"Site 1": np.random.rand(366),
"Site 2": np.random.rand(366),
"Site 3": np.random.rand(366),
"Site 4": np.random.rand(366),
"Site 5": np.random.rand(366),
"Site 6": np.random.rand(366)})
idx = pd.date_range(start='2000-01-01', end='2000-12-31',freq ='D')
df = df.set_index(idx)
dfmon = df.resample('M').mean()
dfyr = df.resample('AS').mean()
df.index.names = ['Date']
df.reset_index(inplace= True)
dfmon.index.names = ['Date']
dfmon.reset_index(inplace= True)
dfyr.index.names = ['Date']
dfyr.reset_index(inplace= True)
print(df)
dfd_long = dfmon.melt(id_vars='Date',var_name='SiteID', value_name='Values')
dfm_long = dfmon.melt(id_vars='Date',var_name='SiteID', value_name='Values')
dfyr_long = dfyr.melt(id_vars='Date',var_name='SiteID', value_name='Values')
fig = px.line(dfd_long, x=dfd_long['Date'], y="Values", color="SiteID", hover_name="SiteID")
fig.update_layout(updatemenus=list([
dict(
buttons=list([
dict(
args=[{'x': [dfm_long.index], 'y': [dfm_long.Values]}],
label='Monthly',
method='restyle'
),
dict(
args=[{'x': [dfyr_long.index], 'y': [dfyr_long.Values]}],
label='Yearly',
method='restyle'
),
dict(
args=[{'x': [dfd_long.index], 'y': [dfd_long.Values]}],
label='Daily',
method='restyle'
)
]))]))
fig.show()
월별 및 연간 드롭 다운으로 리샘플링하는 것과 관련하여 올바른 방법으로 진행하고 있습니까? 이를 위해 길거나 넓은 데이터 형식을 사용해야합니까? 이 코드로 드롭 다운을 클릭하면 예상했던 6 줄 중 한 줄만 표시됩니다. 이것이 제대로 작동하려면 각 사이트에 대해 별도의 드롭 다운이 필요합니까?
지금까지 Plotly에 대한 경험이 제한되어 있으므로 제공 할 수있는 모든 도움이나 제안이 큰 도움이 될 것입니다!
도움을 주셔서 미리 감사드립니다!
다음은 이러한 옵션에 대해 다음 세 가지 그림을 제공하는 전체 설정입니다.
['daily', 'monthly', 'yearly']
나는 수치를 조금 더 흥미롭게 만들기 위해 약간 비틀어 재현 가능한 데이터에 대한 설정을 사용했습니다 . 예를 들어,을 사용 "Site 1": np.random.rand(366)
하는 동안 np.random.randint(-1, 2, 366).cumsum()
. 이것은 잡음보다는 (확률 적) 추세를 나타낼 가능성이있는 누적 된 계열을 생성합니다. 그리고 이것은 그림에서 일어나는 일, 특히 일일 데이터를 보여주는 버전을 더 쉽게 볼 수있게합니다.
이거 좀 웃기지 않나요? 마지막 옵션에 대해 다음과 같이 변경하려면 알려주십시오.
그리고 주석이 그 내용을 다루지 않는 경우 전체 코드 스 니펫에서 어떤 일이 벌어지고 있는지에 대한 자세한 내용을 원하면 알려주십시오.
import pandas as pd
import numpy as np
from numpy import random
import plotly.express as px
import cufflinks as cf
import plotly.graph_objects as go
random.seed(30)
df = pd.DataFrame({
"Site 1": np.random.randint(-1, 2, 366).cumsum(),
"Site 2": np.random.randint(-1, 2, 366).cumsum(),
"Site 3": np.random.randint(-1, 2, 366).cumsum(),
"Site 4": np.random.randint(-1, 2, 366).cumsum(),
"Site 5": np.random.randint(-1, 2, 366).cumsum(),
"Site 6": np.random.randint(-1, 2, 366).cumsum()})
idx = pd.date_range(start='2000-01-01', end='2000-12-31',freq ='D')
df = df.set_index(idx)
dfmon = df.resample('M').mean()
dfyr = df.resample('AS').mean()
df.index.names = ['Date']
df.reset_index(inplace= True)
dfmon.index.names = ['Date']
dfmon.reset_index(inplace= True)
dfyr.index.names = ['Date']
dfyr.reset_index(inplace= True)
fig = go.Figure()
dfs = {'daily':df, 'monthly': dfmon, 'yearly' :dfyr}
# your setup this far...
# ... here is where I've added my contributions:
# specify visibility for traces accross dataframes
frames = len(dfs) # number of dataframes organized in dict
columns = len(dfs['daily'].columns) - 1 # number of columns i df, minus 1 for Date
scenarios = [list(s) for s in [e==1 for e in np.eye(frames)]]
visibility = [list(np.repeat(e, columns)) for e in scenarios]
# container for buttons
buttons = []
# iterate of dataframes in dfs:
# - i is used to reference visibility attributes
# - k is the name for each dataframe
# - v is the dataframe itself
for i, (k, v) in enumerate(dfs.items()):
print(i)
for c, column in enumerate(v.columns[1:]):
fig.add_scatter(name = column,
x = v['Date'],
y = v[column],
visible=True if k=='daily' else False # 'daily' values are shown from the start
)
# one button per dataframe to trigger the visibility
# of all columns / traces for each dataframe
button = dict(label=k,
method = 'restyle',
args = ['visible',visibility[i]])
buttons.append(button)
# include dropdown updatemenu in layout
fig.update_layout(updatemenus=[dict(type="dropdown",
direction="down",
buttons = buttons)])
fig.show()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다