✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Interaction between tabs in Dash

I was able to create multiple tabs using dash but not able to interact with each other. Can someone give some inputs here.

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

Yearwise = pd.DataFrame({‘Year’:[2015,2016],‘Count of Problem Category’: [3,86]})

Year_ProblemCategorywise = pd.DataFrame({‘Year’:[2015,2015,2016,2016],‘Problem Category’: [‘Cancelled’,‘Installation’,‘Cancelled’,‘Installation’],‘Count of Problem Category’: [2,1,12,3]})

Year_Problem_Productwise = pd.DataFrame({‘Year’:[2015,2015,2015,2016,2016,2016],‘Problem_Category’: [‘Cancelled’,‘Cancelled’,‘Installation’,‘Cancelled’,‘Cancelled’,‘Cancelled’],‘Product Description’: [‘A’,‘B’,‘C’,‘D’,‘E’,‘F’],‘Count of Problem Category’: [1,1,1,1,1,2]})

Year_ProblemDescription = pd.DataFrame({‘Year’:[2015,2015,2015,2016,2016,2016],‘Problem_Category’: [‘Cancelled’,‘Cancelled’,‘Installation’,‘Cancelled’,‘Cancelled’,‘Cancelled’],‘Product’: [‘A’,‘B’,‘C’,‘D’,‘E’,‘F’],‘Product_Description’: [‘A’,‘B’,‘C’,‘D’,‘E’,‘F’],‘Problem_Description’: [‘G’,‘H’,‘I’,‘J’,‘K’,‘L’],‘Count_of_Problem’: [1,1,1,1,1,1]})

prob_cat = Year_ProblemCategorywise.groupby([‘Problem Category’])[‘Count of Problem Category’].sum().reset_index()

product_cat = Year_Problem_Productwise.groupby([‘Product Description’])[‘Count of Problem Category’].sum().reset_index()

app = dash.Dash()

app.layout = html.Div([
dcc.Tabs(id=“tabs”, children=[
dcc.Tab(label=‘Tab one’, children=[
html.Div([
dcc.Graph(
id=‘Yearwise-plot’,
figure={
‘data’: [
go.Pie(labels=list(Yearwise[‘Year’]), values=list(Yearwise[‘Count of Problem Category’]))],
‘layout’: go.Layout(
title = ‘Yearwise Chart’,
hovermode=‘closest’
)
}
)
],style={‘width’:‘100%’,‘display’:‘inline-block’})
]),
dcc.Tab(label=‘Tab two’, children=[
html.Div([
dcc.Graph(id=‘Yearwise_ProblemCategory’,
figure={
‘data’: [
go.Bar(
x = prob_cat[‘Problem Category’],
y = prob_cat[‘Count of Problem Category’]
)
],
‘layout’: go.Layout(
title=‘Count of Problem Category’,
xaxis = {‘title’: ‘Problem Category’},
yaxis = {‘title’: ‘Frequency’},
hovermode=‘closest’
)
}
)], style={‘width’:‘100%’,‘display’:‘inline-block’})
]),
dcc.Tab(label=‘Tab three’, children=[
html.Div([
dcc.Graph(id=‘Yearwise_Problem_Productwise’,
figure={
‘data’: [
go.Bar(
x = product_cat[‘Product Description’],
y = product_cat[‘Count of Problem Category’]
)
],
‘layout’: go.Layout(
title=‘Count of Product Category’,
xaxis = {‘title’: ‘Product Category’},
yaxis = {‘title’: ‘Frequency’},
hovermode=‘closest’
)
}
)], style={‘width’:‘100%’,‘display’:‘inline-block’})
]),
dcc.Tab(label = ‘Tab Four’, children =[
html.Div([
dcc.Graph(id = ‘table’,
figure={
‘data’: [
go.Table(
header = dict(values = list(Year_ProblemDescription.columns),
fill = dict(color = ‘#C2D4FF’),
align = [‘left’]*5),
cells = dict(values = [Year_ProblemDescription[‘Year’],Year_ProblemDescription[‘Product’],Year_ProblemDescription[‘Product_Description’],Year_ProblemDescription[‘Problem_Category’],Year_ProblemDescription[‘Problem_Description’],Year_ProblemDescription[‘Count_of_Problem’]],
fill = dict(color=’#F5F8FF’),
align = [‘left’]*5)
)
],
‘layout’: go.Layout(
title=‘Problem list’,
hovermode=‘closest’
)
})
],style = {‘width’:‘100%’,‘display’: ‘inline-block’})
])
])
])

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

Can you specify what are you trying to achieve?

  • and maybe provide some mock data to run this code

By clicking graph (clickData functionality) on first tab, graph on the second tab will be updated automatically by using filter condition.

I that case you should use the hoverData property of the graph to get data on the exact location and data that was clicked on, then assign in to a callback, filter, and output the filtered data as you like.

Here is a standalone Wallmart stores example (modified to click event):

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

df = pd.read_csv(
    'https://raw.githubusercontent.com/'
    'plotly/datasets/master/'
    '1962_2006_walmart_store_openings.csv')
print(df.columns)
app.layout = html.Div([
    html.H1('Walmart Store Openings'),
    html.Div(id='text-content'),
    dcc.Graph(id='map', figure={
        'data': [{
            'lat': df['LAT'],
            'lon': df['LON'],
            'marker': {
                'color': df['YEAR'],
                'size': 8,
                'opacity': 0.6
            },
            'customdata': df['storenum'],
            'type': 'scattermapbox'
        }],
        'layout': {
            'mapbox': {
                'accesstoken': 'pk.eyJ1IjoiY2hyaWRkeXAiLCJhIjoiY2ozcGI1MTZ3MDBpcTJ3cXR4b3owdDQwaCJ9.8jpMunbKjdq1anXwU5gxIw'
            },
            'hovermode': 'closest',
            'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0}
        }
    })
])


@app.callback(
    dash.dependencies.Output('text-content', 'children'),
    [dash.dependencies.Input('map', 'clickData')],
    [dash.dependencies.State('map', 'hoverData')])
def update_text(clickEvent,hoverData):
    print(hoverData)
    s = df[df['storenum'] == hoverData['points'][0]['customdata']]
    return html.H3(
        'The {}, {} {} opened in {}'.format(
            s.iloc[0]['STRCITY'],
            s.iloc[0]['STRSTATE'],
            s.iloc[0]['type_store'],
            s.iloc[0]['YEAR']
        )
    )


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

Thanks a lot for this inputs. Could you please provide some example of interactions within tabs?

I have updated the data inside the code itself. You can run this and get to see the plot.

Please provide your comments.

Appreciate your help.