5

I am creating a dashboard with multiple tabs and each tab triggers and .py file that renders different elements of plotly objects.

For instance, my callback functions return plots, charts and I am looking to return Datatable.

I am able to do render pandas dataframe with go.Table as shown in the example, but not with DataTable, which is newer and offers an enhanced user experience.

import pandas as pd
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc
import plotly.plotly as py
from plotly import graph_objs as go
from plotly.graph_objs import *
import dash_table
import flask
from datetime import datetime as dt
from app import app


layout = html.Div([

    html.Div([

        dcc.Dropdown(
                id='select',
                options=[{'label': i, 'value': i} for i in List],
                value='abc',
                placeholder="xyz",
                style={'width': '100%'}

        ), 

    ], style={"width": "15%", "margin-left": "20%", "margin-right": "35%"}), 


    html.Div([

        dash_table.DataTable(

            id='my-table',
            columns=[{"name": i, "id": i} for i in df_lease.columns],

        )
    ])
])


@app.callback(Output('my-table', 'data'),
              [
                  Input("landlord-select", "value")
              ]
             )
def render_table(company, market):

    df_sub1 = df_lease[(df_lease['Landlord'] == company)] 

    df_sub1 = df_sub1[['UnitNo',
                       'Commencement_Date',
                       'Expiration_Date'
                       ]]

    return df_sub1.to_dict(orient='records')

Expected behavior is to render the pandas dataframe as DataTable.

File structure:

- app.py
- index.py
- apps
   |-- __init__.py
   |-- app1.py
   |-- app2.py

index.py includes all the code that renders multi-page/tab layout, and the children property of dcc.Tabs is updated as layout object from template file (app1.py) is passed. This is where, I believe, the error is generated from.

app.layout = html.Div([

    # tabs
    html.Div([

        dcc.Tabs(
            id="tabs",
            style={"height":"60","verticalAlign":"middle"},
            children=[
                 dcc.Tab(label="Marketing", value="marketing_tab"),
                 dcc.Tab(label="Tenants", value="tenants_tab"),
                 dcc.Tab(label="Portfolio", value="portfolio_tab"),
            ],
            value="marketing_tab",
        )

        ],

        className="row tabs_div"
        ),

        # Tab content
        html.Div(id="tab_content", style={"margin": "2% 3%"})

])

@app.callback(Output("tab_content", "children"),
          [
              Input("tabs", "value")
          ]
         )
def render_content(tab):
    """
    For user selections, return the relevant tab
    """
    if tab == "marketing_tab":
        return marketing.layout
    elif tab == "tenants_tab":
        return tenants.layout
    elif tab == "portfolio_tab":
        return portfolio.layout
    else:
        return marketing.layout


    # In[10]:

    if __name__ == '__main__':
        app.run_server(debug=True)

1 Answer 1

6

This link has some good examples for you to check out. Basically, you'll want your callback to update the data prop of the table. Something like this:

@app.callback(
    Output('my-table', 'data'),
    [Input('dropdown', 'value')])
def callback_a(i):
    df = pd.DataFrame(numpy.arange(30).reshape(5, 6))

    return df.to_dict(orient='records')

It's important that the columns for the table be defined so that the id for each column matches the column name in the dataframe. If you are changing the data in the table, then you may want another callback/output to update the columns prop as well.

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks. So, I attempted to updated the data property. However, I run into InvalidCallbackReturnValue error. The callback for property children of component tab_content returned a value having type module which is not JSON serializable. This could be because of my file structure and multi-page layout as I have pointed out in the question.
Can you update your question with the new code, including as much of the imports and callback structure as possible? I'll take another look and see if I can help.
This link might help: dash.plot.ly/dash-core-components/tabs. The layout is rendered as children property of dcc.Tabs.
@keval, the error is mentioning code not shown above. Is that coming from your other app? Would you be able to share that as well?
pip install dash==1.0.0 <-- Running this fixed the issue.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.