I would like to select dates in several tables, using dash_table . This worked when using a different date picker for each table, but not when using a single date picker for all separate tables.
A simple reproducible example shows a single table, and data can be selected and displayed for different dates (here 1st, 2nd, or 3rd January). My question: how to make three tables, – one for each country --, using a single date picker (not three). Thank you very much in advance for any suggestions!
The modules:
import pandas as pd
import plotly.graph_objs as go
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, Event
import datetime
from datetime import datetime as dt
Fictive data frame:
df = pd.DataFrame({'dd':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-02', '2019-01-02', '2019-01-02', '2019-01-03', '2019-01-03'], 'country':['Belgium', 'Belgium','France', 'France', 'Belgium', 'France', 'Belgium', 'Germany'], 'value':[10,20,30,10,15,25,5,70]})
Script:
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config['suppress_callback_exceptions']=True
currentday = 1
currentmonth = 1
currentyear = 2019
app.layout = html.Div(
[
html.H4('All countries'),
dcc.DatePickerSingle(
id='my-date-picker-single1',
min_date_allowed=dt(2012, 1, 1),
max_date_allowed=dt(2019, 2, 25),
initial_visible_month=dt(currentyear, currentmonth, currentday),
date=dt(currentyear, currentmonth, currentday),
disabled=False
),
dcc.Store(id="selected-rows1", storage_type="memory"),
html.Div(id="tables-container1"),
dash_table.DataTable(
id="table1",
columns=[{"name": i, "id": i} for i in ['dd', 'country', 'value'] ],
style_cell_conditional=[
{
'if':{'filter':'Country eq "France"'},
'backgroundColor':'rgb(150, 150, 150)'
}
] + [
{'if': {'column_id': c},
'textAlign': 'left'
} for c in ['dd', 'country']
],
sorting=True,
sorting_type='multi',
sorting_settings=[],
)
]
)
@app.callback(
Output("selected-rows1", "data"),
[Input("my-date-picker-single1", "date")],
[State("selected-rows1", "data")],
)
def display_output(value, storage):
if value is not None:
return {"selected_rows1": df[df["dd"].str.contains(value)].to_json()}
@app.callback(
Output("table1", "data"),
[Input("table1", "sorting_settings"), Input("selected-rows1", "data")],
)
def update_graph(sorting_settings, rows):
_df = pd.read_json(rows["selected_rows1"])
if sorting_settings is not None and len(sorting_settings):
for setting in sorting_settings:
_df.sort_values(
by=setting["column_id"],
ascending=(setting["direction"] == "asc"),
inplace=True,
)
return _df.to_dict("rows")
else:
return _df.to_dict("rows")
if __name__ == "__main__":
app.run_server(debug=True)
Your advice is highly appreciated!