How to create a pie chart in dash app under a particular tab


#1

I have implemented tabs in my UI. The UI has 4 tabs totally. The code by which tabs was created is shown below:

html.Div([
    dcc.Tabs(
        tabs=[
            {'label': 'Home', 'value': 1},
            {'label': 'Test Accuracy', 'value': 2},
            {'label': 'Help', 'value': 3},
            {'label': 'About', 'value': 4},
        ],
        value=1,
        id='tabs',
        vertical = vertical
    ),
    html.Div(id='tab-output')
], style={
    'width': '80%',
    'fontFamily': 'Sans-Serif',
    'margin-left': '1cm',
    'margin-right': 'auto'
})

In the above code, when tab number 2 with value=‘2’ is clicked by the user, I want to display an attractive pie chart which depicts the value 95 out of 100 (95/100). I have no idea on how to invoke an app callback when tab number 2 is clicked. I tried the following callback piece of code and it didn’t work:

@app.callback(Output(‘pie-chart’, ‘children’), [], [State(‘tabs’, ‘value’)], [Event(‘tabs’, ‘click’)])

Any code that was defined in the above block didn’t work. Also please suggest on how to implement the pie chart.


#2

The Dash user guide is quite helpful: https://plot.ly/dash/. Adapted from one of @chriddyp’s examples:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

app = dash.Dash()

def app_layout():
    return(
            html.Div([
                    dcc.Tabs(
                            tabs=[{'label': 'Pie1', 'value': 1},
                                  {'label': 'Pie2', 'value': 2},
                                  {'label': 'Pie3', 'value': 3},
                                  {'label': 'Pie4', 'value': 4}
                                  ],
                            value=1,
                            id='tabs'
                            ),
                    html.Div(id='output-tab')
                    ])
    )

app.layout=app_layout()

@app.callback(Output('output-tab', 'children'),
              [Input('tabs', 'value')])
def display_content(value):
    data = [
        {
            'values': [[10,90],[5, 95],[15,85],[20,80]][int(value)-1],
            'type': 'pie',
        },
    ]

    return html.Div([
        dcc.Graph(
            id='graph',
            figure={
                'data': data,
                'layout': {
                    'margin': {
                        'l': 30,
                        'r': 0,
                        'b': 30,
                        't': 0
                    },
                    'legend': {'x': 0, 'y': 1}
                }
            }
        )
    ])
if __name__ == '__main__':
    app.server.run(debug=True)


#3

Thanks @emunson. Found this really helpful!!


#4

@emunson How do I change the font size of the displayed values in these pie-charts? I also want to display my own legends