Drill down with a sunburst chart

Hi,

A couple of months ago I made an app to analyze a portfolio, and used a sunburst chart to drill down from an overview to the individual holdings. As you click on the different sunburst segments, all of the charts and tables are updated.

I got some positive feedback on the UI, so I thought it would be helpful to share this small example of using a sunburst chart to filter a table. (I always find examples helpful and haven’t found others like this in my searches)

# -*- coding: utf-8 -*-
import dash
import dash_table
from dash.dependencies import Input, Output

import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px


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

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

df = px.data.tips()

path = ["day", "time", "sex"]

app.layout = html.Div(
    [
        html.H4(id="title"),
        html.Div(
            [
                dcc.Graph(
                    id="sunburst",
                    figure=px.sunburst(df, path=path, values="total_bill"),
                )
            ]
        ),
        html.Div(
            [
                dash_table.DataTable(
                    id="table",
                    columns=[{"name": i, "id": i} for i in df.columns],
                    data=df.to_dict("records"),
                )
            ]
        ),
    ]
)


@app.callback(
    [Output("table", "data"), Output("title", "children")],
    [Input("sunburst", "clickData")],
)
def update_table(clickData):
    click_path = "ALL"
    root = False

    data = df.to_dict("records")
    if clickData:
        click_path = clickData["points"][0]["id"].split("/")
        selected = dict(zip(path, click_path))

        if "sex" in selected:
            dff = df[
                (df["day"] == selected["day"])
                & (df["time"] == selected["time"])
                & (df["sex"] == selected["sex"])
            ]
        elif "time" in selected:
            dff = df[(df["day"] == selected["day"]) & (df["time"] == selected["time"])]
        else:
            dff = df[(df["day"] == selected["day"])]
            root = True
        data = dff.to_dict("records")

        # Show all data when returning to the root from an outer leaf
        percentEntry = (clickData["points"][0]).get("percentEntry")
        if root and percentEntry == 1:
            data = df.to_dict("records")
            click_path = "ALL"

    title = f"Selected from Sunburst Chart: {' '.join(click_path)}"

    return data, title


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

And here is a screenshot from my app

7 Likes