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

Display tables in Dash

Hi Chris,

I’m attempting to use the dash-table-experiments example you provided while combining it with what you’ve accomplished with tabs.

I’m able to recreate your usage.py without issue on its own and have had no issues creating apps with tabs. However, when I attempt to package the app.layout from your example into a ‘children Div’ to show when clicking a tab, the platform hangs and cannot switch between tabs… nor does it show the table and graphs.

Here is the full code:

'import dash
’from dash.dependencies import Input, Output, State
’import dash_core_components as dcc
’import dash_html_components as html
’import dash_table_experiments as dt
’import pandas as pd
’import plotly

'app = dash.Dash()

'app.scripts.config.serve_locally = True
’app.config.supress_callback_exceptions = True

‘DF_GAPMINDER = pd.read_csv(
’ ‘https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv
)
'DF_GAPMINDER = DF_GAPMINDER[DF_GAPMINDER[‘year’] == 2007]
'DF_GAPMINDER.loc[0:20]

'test_layout = html.Div([

’ html.H4(‘Gapminder DataTable’),
’ dt.DataTable(
’ rows=DF_GAPMINDER.to_dict(‘records’),

’ # optional - sets the order of columns
’ columns=sorted(DF_GAPMINDER.columns),

’ row_selectable=True,
’ filterable=True,
’ sortable=True,
’ selected_row_indices=[],
’ id=‘datatable-gapminder’
’ ),
’ html.Div(id=‘selected-indexes’),
’ dcc.Graph(
’ id=‘graph-gapminder’
’ ),
’], className=“container”)

‘app.layout = html.Div([

’ html.Div([
’ html.Div(
’ dcc.Tabs(
’ tabs=[
’ {‘label’:‘First View’, ‘value’:1},
’ {‘label’:‘Second View’, ‘value’:2},
’ {‘label’:‘Third View’, ‘value’:3}
’ ],
’ value=1,
’ id=‘overall-tabs’,
’ vertical=False,
’ style={
’ ‘borderRight’:‘thin lightgrey solid’,
’ ‘textAlign’:‘left’
’ }
’ ),
’ style={‘width’:‘100%’, ‘float’:‘top’}
’ ),
’ html.Div(
’ html.Div(id=‘tab-output’),
’ style={‘width’:‘100%’, ‘float’:‘bottom’}
’ )
’ ],
’ style={‘fontFamily’:‘Dosis’,
’ }),

'# test_layout"""

'])

@app.callback(
’ dash.dependencies.Output(‘tab-output’, ‘children’),
’ [dash.dependencies.Input(‘overall-tabs’, ‘value’)])
‘def display_content(overall_tab):
’ if overall_tab == 1:
’ return html.Div([])
’ elif overall_tab == 2:
’ return html.Div([])
’ elif overall_tab == 3:
’ return test_layout

@app.callback(
’ Output(‘datatable-gapminder’, ‘selected_row_indices’),
’ [Input(‘graph-gapminder’, ‘clickData’)],
’ [State(‘datatable-gapminder’, ‘selected_row_indices’)])
‘def update_selected_row_indices(clickData, selected_row_indices):
’ print ‘make it here?’
’ if clickData:
’ for point in clickData[‘points’]:
’ if point[‘pointNumber’] in selected_row_indices:
’ selected_row_indices.remove(point[‘pointNumber’])
’ else:
’ selected_row_indices.append(point[‘pointNumber’])
’ return selected_row_indices

@app.callback(
’ Output(‘graph-gapminder’, ‘figure’),
’ [Input(‘datatable-gapminder’, ‘rows’),
’ Input(‘datatable-gapminder’, ‘selected_row_indices’)])
‘def update_figure(rows, selected_row_indices):
’ dff = pd.DataFrame(rows)
’ fig = plotly.tools.make_subplots(
’ rows=3, cols=1,
’ subplot_titles=(‘Life Expectancy’, ‘GDP Per Capita’, ‘Population’,),
’ shared_xaxes=True)
’ marker = {‘color’: [’#0074D9’]*len(dff)}
’ for i in (selected_row_indices or []):
’ marker[‘color’][i] = ‘#FF851B
’ fig.append_trace({
’ ‘x’: dff[‘country’],
’ ‘y’: dff[‘lifeExp’],
’ ‘type’: ‘bar’,
’ ‘marker’: marker
’ }, 1, 1)
’ fig.append_trace({
’ ‘x’: dff[‘country’],
’ ‘y’: dff[‘gdpPercap’],
’ ‘type’: ‘bar’,
’ ‘marker’: marker
’ }, 2, 1)
’ fig.append_trace({
’ ‘x’: dff[‘country’],
’ ‘y’: dff[‘pop’],
’ ‘type’: ‘bar’,
’ ‘marker’: marker
’ }, 3, 1)
’ fig[‘layout’][‘showlegend’] = False
’ fig[‘layout’][‘height’] = 800
’ fig[‘layout’][‘margin’] = {
’ ‘l’: 40,
’ ‘r’: 10,
’ ‘t’: 60,
’ ‘b’: 200
’ }
’ fig[‘layout’][‘yaxis3’][‘type’] = ‘log’
’ return fig

‘if name == ‘main’:
’ app.run_server(debug=True)

I know test_layout produces the original display, it can be shown by uncommenting test_layout within app.layout and commenting the tabs related Div above it. Interestingly, if I try to use both at once, I get test_layout showing up as a tab and as its separate Div.

Any ideas on why it will not show within a tab without including it as its own Div?

Thanks for all the help, great product!

@smcelrea - I suspect that this the same issue as in this comment. Could see if the recommendation in that comment fixes your issue? Thanks for reporting! :slight_smile:

This worked, thanks so much! Apologies for not coming across that comment during the first read.

2 posts were split to a new topic: Dash DataTable - Conditional Formatting

A post was split to a new topic: Dash DataTable - Distinguishing between single row select and multi row select

A post was split to a new topic: Dash DataTable - Controlling size

Hi Chris,

I am facing the issue of Error loading layout". My code for app.layout is as follows:

app.layout = html.Div([
html.Div(dt.DataTable, style={‘display’: ‘none’}),
html.H4(‘Gapminder DataTable’),
dt.DataTable(
rows=DF_GAPMINDER.to_dict(‘records’),

    # optional - sets the order of columns
    columns=sorted(DF_GAPMINDER.columns),

    row_selectable=True,
    filterable=True,
    sortable=True,
    selected_row_indices=[],
    id='datatable-gapminder'
),
html.Div(id='selected-indexes'),
dcc.Graph(
    id='graph-gapminder'
),

], className=“container”)

any help is appreciated!!
image|551x500

If you don’t mind sharing your code a bit ,how did you add the empty record dict to the rows property. I have trying to do this for hours now!

Thanks,
Sud

@sud Please see this comment from @filmcup86 for the actual code

html.Div(dt.DataTable(rows=[{}]), style={'display': 'none'}),

@sud
This simple code.

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import pandas as pd

print(dcc.__version__) # 0.6.0 or above is required

app = dash.Dash()

DF_SIMPLE = pd.DataFrame({
    'x': ['A', 'B', 'C', 'D', 'E', 'F'],
    'y': [4, 3, 1, 2, 3, 6],
    'z': ['a', 'b', 'c', 'a', 'b', 'c']
})


# Since we're adding callbacks to elements that don't exist in the app.layout,
# Dash will raise an exception to warn us that we might be
# doing something wrong.
# In this case, we're adding the elements through a callback, so we can ignore
# the exception.
app.config.supress_callback_exceptions = True
app.scripts.config.serve_locally = True

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content'),
    html.Div(dt.DataTable(rows=[{}]), style={'display': 'none'})
])


index_page = html.Div([
    html.H1('Page Home'),
    html.Br(),
    dcc.Link('Go to Home', href='/'),
    html.Br(),
    dcc.Link('Go to Page 1', href='/page-1'),
])

page_1_layout = html.Div([
    html.H1('Page 1'),
    html.Br(),
    dcc.Link('Go back to home', href='/'),
    
    html.H4('Editable DataTable'),
    dt.DataTable(
        rows=DF_SIMPLE.to_dict('records'),

        # optional - sets the order of columns
        columns=sorted(DF_SIMPLE.columns),

        editable=True,

        id='editable-table'
    ),
    html.Div([
        html.Pre(id='output', className="two columns"),
        html.Div(
            dcc.Graph(
                id='graph',
                style={
                    'overflow-x': 'wordwrap'
                }
            ),
            className="ten columns"
        )
    ], className="row"),

])
            
@app.callback(
    dash.dependencies.Output('output', 'children'),
    [dash.dependencies.Input('editable-table', 'rows')])
def update_selected_row_indices(rows):
    return json.dumps(rows, indent=2)


@app.callback(
    dash.dependencies.Output('graph', 'figure'),
    [dash.dependencies.Input('editable-table', 'rows')])
def update_figure(rows):
    dff = pd.DataFrame(rows)
    return {
        'data': [{
            'x': dff['x'],
            'y': dff['y'],
        }],
        'layout': {
            'margin': {'l': 10, 'r': 0, 't': 10, 'b': 20}
        }
    }

# Update the index
@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/page-1':
        return page_1_layout
    else:
        return index_page
    # You could also return a 404 "URL not found" page here

app.css.append_css({
    'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})

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

Hi guys!

Thank-you so much for response! I think my issue was different and maybe some other people have it as well. Issues are:

  1. in \dash-table-experiments-master\dash_table_experiments_init_.py, the bold link is not accessing bundle.js or bundle.js.map

_js_dist = [
{
“relative_package_path”: “bundle.js”,
“external_url”: (
"https://unpkg.com/dash-table-experiments@{}"
"/dash_table_experiments/bundle.js"
).format(version),
“namespace”: “dash_table_experiments”
}
]
so I went to https://unpkg.com/dash-table-experiments/ and manually downloaded all the files in “https://unpkg.com/dash-table-experiments@0.5.0/dash_table_experiments/” and put them in “\dash-table-experiments-master\dash_table_experiments” folder

  1. Then I ran “python setup.py install”. This spits out correct folder “dash_table_experiments.egg-info”
  2. Then I ran the file with “python usage.py” and it loaded in the browser without any issues.

So I guess the issue that needs addressing is missing index file in https://unpkg.com/dash-table-experiments.

I appreciate everyone’s comments and response here!

Thanks,
Sud

Hi!
I tried to split the app I’m working on into 2 pages using the URL support and it seems that the tables break down the app.
Did someone notice that before?
Below a code example :

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dtable
import pandas as pd
print(dcc.version) # 0.6.0 or above is required
app = dash.Dash()
app.config.supress_callback_exceptions = True
app.layout = html.Div([
dcc.Location(id=‘url’, refresh=False),
html.Div(id=‘page-content’)
])
index_page = html.Div([
dcc.Link(‘Go to Page 1’, href=’/page-1’),
html.Br(),
dcc.Link(‘Go to Page 2’, href=’/page-2’),
])
page_1_layout = html.Div([
html.H1(‘Page 1’),
dcc.Dropdown(
id=‘page-1-dropdown’,
options=[{‘label’: i, ‘value’: i} for i in [‘LA’, ‘NYC’, ‘MTL’]],
value=‘LA’
),
html.Div(id=‘page-1-content’),
html.Br(),
dcc.Link(‘Go to Page 2’, href=’/page-2’),
html.Br(),
dcc.Link(‘Go back to home’, href=’/’),
])
@app.callback(dash.dependencies.Output(‘page-1-content’, ‘children’),
[dash.dependencies.Input(‘page-1-dropdown’, ‘value’)])
def page_1_dropdown(value):
return ‘You have selected “{}”’.format(value)
page_2_layout = html.Div([
html.H1(‘Page 2’),
dcc.RadioItems(
id=‘page-2-radios’,
options=[{‘label’: i, ‘value’: i} for i in [‘Orange’, ‘Blue’, ‘Red’]],
value=‘Orange’
),
dtable.DataTable(
rows=pd.DataFrame({‘a’:[1, 2], ‘b’:[3,4]}).to_dict(‘records’),
id=‘table’),
html.Div(id=‘page-2-content’),
html.Br(),
dcc.Link(‘Go to Page 1’, href=’/page-1’),
html.Br(),
dcc.Link(‘Go back to home’, href=’/’)
])
@app.callback(dash.dependencies.Output(‘page-2-content’, ‘children’),
[dash.dependencies.Input(‘page-2-radios’, ‘value’)])
def page_2_radios(value):
return ‘You have selected “{}”’.format(value)
@app.callback(dash.dependencies.Output(‘page-content’, ‘children’),
[dash.dependencies.Input(‘url’, ‘pathname’)])
def display_page(pathname):
if pathname == ‘/page-1’:
return page_1_layout
elif pathname == ‘/page-2’:
return page_2_layout
else:
return index_page
# You could also return a 404 “URL not found” page here
app.css.append_css({
‘external_url’: ‘https://codepen.io/chriddyp/pen/bWLwgP.css
})
if name == ‘main’:
app.run_server(debug=True)

Thanks! :grinning:

add empty hidden table here. something like
html.Div(dt.DataTable(rows=[{}]), style={'display': 'none'})
After that dash will be able to render other tables.

2 Likes

Hi Roman,
Tanks for the trick! It worked perfectly.
Julien

A post was split to a new topic: Dash DataTable - Unable to use more than 1 table

A post was split to a new topic: Dash DataTable - Disable Ability to Select All Rows

A post was split to a new topic: Multi-Index Tables in Dash

A post was split to a new topic: Dash DataTable - Change Direction of Column Headers

A post was split to a new topic: Dash DataTable - Updating the Number of Rows