Plotly:后续如何使用graph_objects创建旭日形子图?

Plotly: Follow-up How to create sunburst subplot using graph_objects?

尝试了之前问题中的示例,但我无法正确“渲染”它:

# imports
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

# data
df = pd.DataFrame({'BA':  ['BA1', 'BA2', 'BA3', 'BA4','BA2'],
                   'RS':   [12, 13,15, 20, 18],
                   'RC':    ['medium','medium', 'high','high','high'] })

# plotly express figure
fig = px.sunburst(df, path=["BA", "RC"])

fig.show()

# plotly graph_objects figure
fig2=go.Figure(go.Sunburst(
                labels=fig['data'][0]['labels'].tolist(),
                parents=fig['data'][0]['parents'].tolist(),
                            )
                )
fig2.show()

结果:

enter image description here enter image description here

我做错了什么? (我希望它看起来像第一张图片)..使用 conda + jupyter lab

如果你看一下 fig['data'],你会看到有一个名为 ids 的字段告诉 Plotly 如何将父级连接到标签。您还需要将其指定为参数。

编辑:如果您想以与 px.sunburst 相同的方式显示值,您还需要包含参数 branchvalues='total'

# plotly graph_objects figure
fig2=go.Figure(go.Sunburst(
    branchvalues='total',
    ids=fig['data'][0]['ids'].tolist(),
    labels=fig['data'][0]['labels'].tolist(),
    parents=fig['data'][0]['parents'].tolist(),
    values=fig['data'][0]['values'].tolist()
    )
)
fig2.show()