使用plotly.graph_objects生成Sunburst图表显示空白页,换plotly.express正常求解
Sunburst图表用plotly.graph_objects显示空白但plotly.express正常的原因分析
问题描述
我尝试编写函数生成Sunburst图表,但图表显示空白页面且无任何报错信息。使用如下简单测试数据验证时问题依然存在,但改用plotly.express替代plotly.graph_objects后即可正常生成图表。请问该问题的原因是什么?
使用plotly.graph_objects的代码(显示空白)
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')
使用plotly.express的代码(正常显示)
# 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()
原因分析
- 层级结构不完整:plotly.graph_objects的
go.Sunburst要求传入的labels和parents必须构成完整的树形结构——顶层节点(比如示例中的A、B)的父节点必须是空字符串或None,但你当前的代码里只传入了子节点(A1、A2、B1、B2)作为labels,父节点是A、B,但没有把A、B本身作为顶层节点加入到数据中,导致图表无法识别完整的层级关系,所以渲染空白。 - plotly.express的自动封装:px.sunburst会自动根据
path参数(['Category', 'Subcategory'])构建完整的层级结构,它会自动把Category中的A、B作为顶层节点计算并添加,不需要手动处理顶层数据,因此能正常渲染出图表。
修正后的plotly.graph_objects代码
import pandas as pd import plotly.graph_objects as go data = { 'Category': ['A', 'A', 'B', 'B'], 'Subcategory': ['A1', 'A2', 'B1', 'B2'], 'Value': [10, 20, 30, 40] } df = pd.DataFrame(data) # 构建顶层节点数据:A、B的父节点为空,值为对应子节点的总和 top_nodes = pd.DataFrame({ 'labels': ['A', 'B'], 'parents': ['', ''], 'values': [df[df['Category'] == 'A']['Value'].sum(), df[df['Category'] == 'B']['Value'].sum()] }) # 转换子节点数据格式 child_nodes = pd.DataFrame({ 'labels': df['Subcategory'], 'parents': df['Category'], 'values': df['Value'] }) # 合并顶层和子节点数据 full_hierarchy = pd.concat([top_nodes, child_nodes], ignore_index=True) # 生成Sunburst图表 fig = go.Figure(go.Sunburst( labels=full_hierarchy['labels'], parents=full_hierarchy['parents'], values=full_hierarchy['values'] )) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) fig.write_html('fixed_sunburst_chart.html')
内容的提问来源于stack exchange,提问作者paofanlv
相关产品推荐
相关产品推荐

