情节:后续如何使用graph_objects创建旭日子图?

时间:2020-09-15 22:05:08

标签: python plotly sunburst-diagram

在先前的问题中尝试过该示例,但我无法使其正确“呈现”:

# 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

1 个答案:

答案 0 :(得分:2)

如果您查看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()

enter image description here