Empty page when generating sunburst chart

33 Views Asked by At

I was trying to write a function to generate sunburst chart, but the figure shows a blank page. There are no error message. Then I was testing with simple sample data (see below) but it is still blank. When I use plotly.express instead plotly.graph_objects then it works. Anyone know why? Thanks for the help!

import pandas as pd
import plotly.graph_objects as go
# Sample data
data = {
    'Category': ['A', 'A', 'B', 'B'],
    'Subcategory': ['A1', 'A2', 'B1', 'B2'],
    'Value': [10, 20, 30, 40]
}
df = pd.DataFrame(data)

# Create a basic sunburst chart
fig = go.Figure(go.Sunburst(
    labels=df['Subcategory'],
    parents=df['Category'],
    values=df['Value']
))

fig.update_layout(margin=dict(t=0, l=0, r=0, b=0))

# Save the chart to an HTML file
fig.write_html('basic_hierarchical_sunburst_chart.html')
# using plotly.express then it works
import pandas as pd
import plotly.express as px

# Sample data
data = {
    'Category': ['A', 'A', 'B', 'B'],
    'Subcategory': ['A1', 'A2', 'B1', 'B2'],
    'Value': [10, 20, 30, 40]
}
df = pd.DataFrame(data)

# Create a sunburst chart using Plotly Express
fig = px.sunburst(df, path=['Category', 'Subcategory'], values='Value')

# Show the chart
fig.show()
1

There are 1 best solutions below

3
Oskar Hofmann On

Your example data is not a valid sunburst graph. labels should be a list of all unique elements and parents must contain entries from labels or an empty string if an element has no parent. You define the elements ['A1', 'A2', 'B1', 'B2'] but then assign A and B (which you did not define as elements) as parent elements.

By changing your example data to

data = {
    'Category': ['','A', 'A','', 'B', 'B'],
    'Subcategory': ['A','A1', 'A2','B', 'B1', 'B2'],
    'Value': [10, 20, 30, 40, 10, 20]
}

I get the graph

enter image description here

I am not sure what you mean with "When I use plotly.express instead plotly.graph_objects then it works." Can you provide the full code for that? With your data, plotly.express also leads to a blank page for me.