【发布时间】:2021-02-17 05:35:46
【问题描述】:
我希望在 Plotly 中创建一个下拉菜单,以将我原来的每日时间序列切换为月平均值和年平均值。
总的来说,我希望下拉列表中有 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 方面的经验有限,因此您可以提供的任何帮助或建议都会有很大帮助!
提前感谢您的帮助!
【问题讨论】:
-
Right way?也许,但不太可能。Long or wide?宽。但也许在字典中组织为三个不同的数据框。Do you need a separate dropdown for each site?没有。Will my answer solve your challenge?我希望如此。如果没有,请告诉我。
标签: python python-3.x pandas numpy plotly