Black Lives Matter. Please consider donating to Black Girls Code today.

Dynamically create plotly/dash-table

How could I create tables dynamically by plotly/ dash-table ?

I know I can create dynamic tables by using plotly graph objects as shown below, but I’d love to use plotly/dash-table since it has better UI.

import dash
import dash_table
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import json
from dash.dependencies import Input, Output, State
from plotly import graph_objs as go

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/solar.csv"
)

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        dcc.Dropdown(
            id="dropdown",
            options=[
                {"label": "California", "value": "California"},
                {"label": "Arizona", "value": "Arizona"},
                {"label": "Nevada", "value": "Nevada"},
            ],
            value="MTL",
        ),
        dcc.Store(id="selected-rows", storage_type="memory"),
        dcc.Graph(id="content"),
    ]
)


@app.callback(
    Output("selected-rows", "data"),
    [Input("dropdown", "value")],
    [State("selected-rows", "data")],
)
def display_output(value, storage):
    if value is not None:
        return {"selected_rows": df[df["State"].str.contains(value)].to_json()}


@app.callback(Output("content", "figure"), [Input("selected-rows", "data")])
def update_output(rows):
    if rows is not None:
       # Here, I could get DataFrames
        _df = pd.read_json(rows["selected_rows"])
    
      # But, have no ideas how to return dash_table.Databales instead ob go.Table
        return {
            "data": [
                go.Table(
                    header=dict(values=_df.columns.values),
                    cells=dict(values=[_df[col] for col in _df.columns.values]),
                )
            ],
            "layout": {"title": "picked row", "hovermode": "closest"},
        }

if __name__ == "__main__":
    app.run_server(debug=True)
1 Like

Just maid it by myself. Grad if I could have some feedbacks…

You can

  1. Update chart dynamically
  2. Sort by mulitple columns
import dash
import dash_table
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import json
from dash.dependencies import Input, Output, State

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv"
)

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        dcc.Dropdown(
            id="dropdown",
            options=[
                {"label": "A", "value": "A"},
                {"label": "B", "value": "B"},
                {"label": "C", "value": "C"},
            ],
            value="MTL",
        ),
        dcc.Store(id="selected-rows", storage_type="memory"),
        html.Div(id="tables-container"),
        html.Div(
            children=dash_table.DataTable(
                id="table",
                columns=[{"name": i, "id": i} for i in df.columns],
                sorting=True,
                sorting_type='multi',
                sorting_settings=[],
            )
        ),
    ]
)


@app.callback(
    Output("selected-rows", "data"),
    [Input("dropdown", "value")],
    [State("selected-rows", "data")],
)
def display_output(value, storage):
    if value is not None:
        return {"selected_rows": df[df["country"].str.contains(value)].to_json()}



@app.callback(
    Output("table", "data"),
    [Input("table", "sorting_settings"), Input("selected-rows", "data")],
)
def update_graph(sorting_settings, rows):
    _df = pd.read_json(rows["selected_rows"])
    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)

2 Likes

Thank you for posting your solution.

This looks very useful, but I tried to do it and I get an error about "TypeError: Unexpected keyword argument sorting"

What does that mean?

Dude any solution in this code I’m also stuck here

See https://dash.plot.ly/dash-1-0-migration

Sorting prop in dash_table has been changed to sort_action