Search code examples
pythonplotlyinformation-retrieval

how to retrieve values from plotly sunburst chart?


Plotly sunburst charts are great for visualizing hierarchical data. Is it possible to retrieve the values shown in the chart into a dictionary, or an array or something?

Concretely, assume the following dataframe:

Att1   Att2
A      C
A      D
B      D
B      D
B      C

px.sunburst(data, ['Att1', 'Att2']) will generate a chart that in the most inner ring has the value 2 for A and 3 for B. Then for A, it will indicate there is 1 C and 1 D. Similarly, for B it will indicate 2 D and 1 C. All those numbers are the ones I am looking to retrieve. Does plotly have such functionality? or is my best bet to use data.groupby iteratively?


Solution

  • The underlying data from a figure can be accessed and the details can be found here at plotly and summarized below...

    Viewing the underlying data structure for any plotly.graph_objects.Figure object, including those returned by Plotly Express, can be done via print(fig) or, in JupyterLab, with the special fig.show("json") renderer. Figures also support fig.to_dict() and fig.to_json() methods. print()ing the figure will result in the often-verbose layout.template key being represented as ellipses '...' for brevity.

    Several options are available...

    • fig.show("json") is pretty hany if you're in a notebook
    • print(fig) is my go to method

    So for this plotly example:

    import plotly.express as px
    data = dict(
        character=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
        parent=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],
        value=[10, 14, 12, 10, 2, 6, 6, 4, 4])
    
    fig = px.sunburst(
        data,
        names='character',
        parents='parent',
        # values='value',
    )
    fig.show()
    

    print(fig) will return:

    Figure({
        'data': [{'domain': {'x': [0.0, 1.0], 'y': [0.0, 1.0]},
                  'hovertemplate': 'character=%{label}<br>parent=%{parent}<extra></extra>',
                  'labels': array(['Eve', 'Cain', 'Seth', 'Enos', 'Noam', 'Abel', 'Awan', 'Enoch', 'Azura'],
                                  dtype=object),
                  'name': '',
                  'parents': array(['', 'Eve', 'Eve', 'Seth', 'Seth', 'Eve', 'Eve', 'Awan', 'Eve'],
                                   dtype=object),
                  'type': 'sunburst'}],
        'layout': {'legend': {'tracegroupgap': 0}, 'margin': {'t': 60}, 'template': '...'}
    })
    

    And then with some knowledge of tuples you can extract some info, for example...

    print(fig.data[0].labels) will return:

    ['Eve' 'Cain' 'Seth' 'Enos' 'Noam' 'Abel' 'Awan' 'Enoch' 'Azura']