I am tryng to add a dropdown menu to a plotly express line chart. This menu will decide whereas the dates on the X axis group by day, month or year. This is the code I have by now:
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)])
Although the "group-by day" data with which the chart is initialized is propertly drawn, when I click on any of the dropdown options, the chart becomes blank with the X axis set to [-1,5].
The data returned by the "group_dates_by_period" function is correct, as if I initilize the chart with the group-by month or group-by year option it works as expected. So I guess it must be a problem with the dropdwon menu.
Data Sample:
{'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')]]}