Template request | Bug report | Generate Data Product
Tags: #dash #dashboard #plotly #naas #asset #analytics #dropdown #callback #bootstrap #snippet
Author: Ismail Chihab
Create a basic table that can be updated through a dcc.dropdown menu.
Reference:
- https://dash.plotly.com/datatable
- https://stackoverflow.com/questions/72013085/update-datatable-with-sub-dropdowns-dash-python
import os
try:
import dash
except:
!pip install dash --user
import dash
try:
import dash_bootstrap_components as dbc
except:
!pip install dash_bootstrap_components --user
import dash_bootstrap_components as dbc
from dash import html, Input, Output, dcc, dash_table
import pandas as pd
DASH_PORT = 8050
column_name = ["col1", "col2", "col3"]
data = [[0, 1, 2], [0, 6, 4], [6, 7, 1], [0, 1, 2], [3, 4, 5]]
df = pd.DataFrame(data, columns=column_name)
df
dropdown = dcc.Dropdown(
["option1", "option2", "option3"], "option1", id="demo-dropdown"
)
table = dash_table.DataTable(
id="tbl",
data=df.to_dict("records"),
columns=[{"name": i, "id": i} for i in df.columns],
)
app = dash.Dash(
requests_pathname_prefix=f'/user/{os.environ.get("JUPYTERHUB_USER")}/proxy/{DASH_PORT}/',
external_stylesheets=[dbc.themes.BOOTSTRAP],
meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1.0"}
],
)
app.layout = html.Div([dropdown, table])
@app.callback(Output("tbl", "data"), Input("demo-dropdown", "value"))
def update_output(value):
dff = df.copy()
if str(value) == "option1":
dff = dff[dff["col1"] == 0]
elif str(value) == "option2":
dff = dff[dff["col2"] == 3]
return dff.to_dict("records")
if __name__ == "__main__":
app.run_server(proxy=f"http://127.0.0.1:{DASH_PORT}::https://app.naas.ai")