Adding a table to my dropdown

Hi everyone

I have been trying to create an a dashboard that has two drop values; (map and a table)
The map part of it seems to be working fine but when i try to change to the table it doesn’t work.
Is it not possible to do because the table is not a chart? if not how exactly can i make it work?

import pandas as pd
import plotly.express as px 
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output, callback
import dash_bootstrap_components as dbc
from dash import dash_table



euros = pd.read_excel('https://query.data.world/s/7aexjzbga5sfznukjz6uor2t3dsikb?dws=00000')
print(euros)



## COMPONENTS
app = Dash(__name__, external_stylesheets=[dbc.themes.LUX])

mytitle = dcc.Markdown(children='# Total Yearly Cost to study in European countries (£)')

mygraph = dcc.Graph(id='euro_map', style={'height': '600px'}, figure={})

dropdown = dcc.Dropdown(options=['Map', 'Table'],
                        value = 'Map',
                        clearable= False)


#LAYOUT
app.layout = dbc.Container([
    dbc.Row([
        dbc.Col([mytitle], width=6)], justify='center'),
    dbc.Row([
        dbc.Col([mygraph], width=12)]),
    dbc.Row([
        dbc.Col([dropdown], width=6)
    ], justify='center'),

  ], fluid=True)

#CALLBACK
@app.callback(
    Output(mygraph, component_property='figure'),
    Input(dropdown, component_property='value')
)


def update_graph(user_input):
    # Plotly Express
    if user_input == 'Map':
        fig = px.choropleth(
            data_frame=euros,
            locationmode='country names',
            locations='Country',
            scope='europe',
            color='Total yearly living costs and fees (£)',
            hover_data=['Country', 'Total yearly living costs and fees (£)'],
            color_continuous_scale=px.colors.sequential.Blues_r,
            labels={'Total yearly living costs and fees (£)': 'Total cost and fee'},

    )
        fig.update_layout(margin={"r":2,"t":2,"l":2,"b":2})


    elif user_input == 'Table':
        dash_table.DataTable(
            id='euro-table',
            data=euros.to_dict('records'),
            columns=[
                {"name": i, "id": i, "deletable": False, "selectable": False} for i in dff.columns
            ],
            editable=False,
            filter_action="native",
            sort_action="native",
            sort_mode="multi",
            row_selectable="multi",
            row_deletable=False,
            selected_rows=[],
            page_action="native",
            page_current= 0,
            page_size= 6,
            # page_action='none',
            # style_cell={
            # 'whiteSpace': 'normal'
            # },
            # fixed_rows={ 'headers': True, 'data': 0 },
            # virtualization=False,
            style_cell_conditional=[
                {'if': {'column_id': 'countriesAndTerritories'},
                 'width': '40%', 'textAlign': 'left'},
                {'if': {'column_id': 'deaths'},
                 'width': '30%', 'textAlign': 'left'},
                {'if': {'column_id': 'cases'},
                 'width': '30%', 'textAlign': 'left'},
            ],
        )





    return fig

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

Hi @ImmanuelOji

The DataTable needs to be returned to the children prop of an html.Div rather than to the figure prop of the dcc.Graph

Try changing the app to this structure:



app.layout = html.Div([
   # ....
    html.Div(id="content")
])

@app.callback(
    Output("content", "children"),
    Input(dropdown, 'value')
)
def update(user_input):
    if user_input == "Table":
        return dash_table.DataTable(
            #...
        )
    
    fig = # ...
    return dcc.Graph(
        figure=fig
        #....
    )

1 Like

I formatted the code for you, I hope you don’t mind. :slight_smile:

1 Like

Hi @AnnMarieW

Thanks for the reply.
Please can you elaborate more, do i have to remove mygraph from the components?
and do i have to change the whole app layout?
what should be in the “content”?

Thanks

HI @ImmanuelOji

Try running this:



import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output, callback
import dash_bootstrap_components as dbc
from dash import dash_table



euros = pd.read_excel('https://query.data.world/s/7aexjzbga5sfznukjz6uor2t3dsikb?dws=00000')
print(euros)


app = Dash(__name__, external_stylesheets=[dbc.themes.LUX])

mytitle = dcc.Markdown(children='# Total Yearly Cost to study in European countries (£)')

mygraph = dcc.Graph(id='euro_map', style={'height': '600px'}, figure={})
content = html.Div(id="content")
dropdown = dcc.Dropdown(options=['Map', 'Table'],
                        value = 'Map',
                        clearable= False)



app.layout = dbc.Container([
    dbc.Row([
        dbc.Col([mytitle], width=6)], justify='center'),
    dbc.Row([
        dbc.Col([content], width=12)]),
    dbc.Row([
        dbc.Col([dropdown], width=6)
    ], justify='center'),

  ], fluid=True)


@app.callback(
    Output(content, component_property='children'),
    Input(dropdown, component_property='value')
)
def update_graph(user_input):
    # Plotly Express
    if user_input == 'Map':
        fig = px.choropleth(
            data_frame=euros,
            locationmode='country names',
            locations='Country',
            scope='europe',
            color='Total yearly living costs and fees (£)',
            hover_data=['Country', 'Total yearly living costs and fees (£)'],
            color_continuous_scale=px.colors.sequential.Blues_r,
            labels={'Total yearly living costs and fees (£)': 'Total cost and fee'},

    )
        fig.update_layout(margin={"r":2,"t":2,"l":2,"b":2})
        return dcc.Graph(id='euro_map', style={'height': '600px'}, figure=fig)


    elif user_input == 'Table':
        return dash_table.DataTable(
            id='euro-table',
            data=euros.to_dict('records'),
            columns=[
                {"name": i, "id": i, "deletable": False, "selectable": False} for i in euros.columns
            ],
            editable=False,
            filter_action="native",
            sort_action="native",
            sort_mode="multi",
            row_selectable="multi",
            row_deletable=False,
            selected_rows=[],
            page_action="native",
            page_current= 0,
            page_size= 6,
            # page_action='none',
            # style_cell={
            # 'whiteSpace': 'normal'
            # },
            # fixed_rows={ 'headers': True, 'data': 0 },
            # virtualization=False,
            style_cell_conditional=[
                {'if': {'column_id': 'countriesAndTerritories'},
                 'width': '40%', 'textAlign': 'left'},
                {'if': {'column_id': 'deaths'},
                 'width': '30%', 'textAlign': 'left'},
                {'if': {'column_id': 'cases'},
                 'width': '30%', 'textAlign': 'left'},
            ],
        )


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



Thank you very much

2 Likes