我正在尝试将下拉菜单添加到 plotly express 折线图。此菜单将决定 X 轴上的日期按日、月或年分组。这是我现在拥有的代码:
import plotly.express as px
import pandas as pd
def group_dates_by_period(df, column, period):
return df.groupby(df[column].dt.to_period(period))['Id Incidencia'].count()
periods = [('Día', 'D', '%Y-%m-%d'), ('Mes', 'M', '%Y-%m'), ('Año', 'Y', '%Y')]
fig2_data = group_dates_by_period(df, 'Fecha Apertura', periods[0][1])
fig2 = px.line(
x=fig2_data.index.strftime(periods[0][2]),
y=fig2_data.values,
title='Distribución temporal de las incidencias',
labels={
'x': 'Fecha',
'y': 'Nº incidencias'
}
)
buttons = []
for period in periods:
data = group_dates_by_period(df, 'Fecha Apertura', period[1])
new_button = {
'method': 'restyle',
'label': period[0],
'args': [{
'y': data.values,
'x': data.index.strftime(period[2])
}]
}
buttons.append(new_button)
fig2.update_layout(updatemenus=[dict(active=0, buttons=buttons)])
尽管图表初始化时使用的“按天分组”数据已正确绘制,但当我单击任何下拉选项时,图表变为空白,X 轴设置为 [-1,5]。< /p>
“group_dates_by_period”函数返回的数据是正确的,就像我用 group-by month 或 group-by year 选项初始化图表一样,它按预期工作。所以我猜肯定是dropdwon菜单有问题。
数据样本:
{'index': [0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19],
'columns': ['Id Incidencia', 'Fecha Apertura'],
'data': [['INC000006722157', Timestamp('2020-12-07 12:28:30')],
['INC000006722000', Timestamp('2020-12-07 09:52:06')],
['INC000006721939', Timestamp('2020-12-07 10:13:06')],
['INC000006708347', Timestamp('2020-12-02 09:02:45')],
['INC000006723090', Timestamp('2020-12-07 20:37:53')],
['INC000006736601', Timestamp('2020-12-12 00:35:16')],
['INC000006736721', Timestamp('2020-12-12 00:46:48')],
['INC000006724926', Timestamp('2020-12-08 15:21:15')],
['INC000006725331', Timestamp('2020-12-08 20:04:14')],
['INC000006725229', Timestamp('2020-12-08 18:33:54')],
['INC000006722542', Timestamp('2020-12-07 15:52:59')],
['INC000006722729', Timestamp('2020-12-07 18:33:22')],
['INC000006723246', Timestamp('2020-12-07 23:56:08')],
['INC000006722574', Timestamp('2020-12-07 17:11:05')],
['INC000006741563', Timestamp('2020-12-14 13:31:05')],
['INC000006722571', Timestamp('2020-12-07 17:06:55')],
['INC000006741632', Timestamp('2020-12-14 13:44:35')],
['INC000006741568', Timestamp('2020-12-14 13:33:40')],
['INC000006741636', Timestamp('2020-12-14 13:46:38')],
['INC000006741640', Timestamp('2020-12-14 13:51:34')]]}