Arthur Coimbra
Arthur Coimbra

Reputation: 477

Plotly: How to display legends for a sunburst diagram?

I'm trying to display legends alongside my plotly sunburst plot.

Example sunburst:

df = px.data.tips()
fig = px.sunburst(df, path=['day', 'time'], values='total_bill')
fig.show()

enter image description here

Ideally, I would like to display the inner or outer values and respective colors inside the black rectangle.

I was used to manually editing the legends in matplotlib (https://stackoverflow.com/a/53324868/10226862), but I can't find a way to do this in plotly.

I've also tried to add annotations, but doing so also adds X and Y-axis.

Upvotes: 3

Views: 4805

Answers (1)

vestland
vestland

Reputation: 61134

Displaying the outer values wouldn't make much sense since you've got three different colors for Dinner. But you could include the inner values in the sunburst diagram using annotations. You're right that this will trigger axes and backgrounds, but we can always remove those again. The snippet below will produce this figure:

enter image description here

Complete code:

import plotly.express as px

df = px.data.tips()
fig = px.sunburst(df, path=['day', 'time'], values='total_bill')
D = df['day'].unique()

colors=['#EF553B',
         '#636EFA',
         '#00CC96',
         '#AB63FA',
         '#FFA15A',
         '#19D3F3',
         '#FF6692',
         '#B6E880',
         '#FF97FF',
         '#FECB52']

for i, m in enumerate(D):
    fig.add_annotation(dict(font=dict(color=colors[i],size=14),
                                        x=0.8,
                                        y=1-(i/10),
                                        showarrow=False,
                                        text=D[i],
                                        textangle=0,
                                        xanchor='left',
                                        xref="paper",
                                        yref="paper"))

fig.update_layout(
    paper_bgcolor='rgba(0,0,0,0)',
    plot_bgcolor='rgba(0,0,0,0)'
)

fig.update_xaxes(tickfont=dict(color='rgba(0,0,0,0)'))
fig.update_yaxes(tickfont=dict(color='rgba(0,0,0,0)'))

fig.show()

Upvotes: 3

Related Questions