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

问题描述 投票:1回答:1

我的数据框看起来像这样:

    user    age   gender
0    23     12     male
1    24     13     male
2    25     15     female
3    26     20     male
4    27     21     male

并使用

px.sunburst(df, path=["gender", "age"])

为我提供了正确的朝阳图,其中性别在饼图的中间部分,并且对于每个性别,它都具有相关的年龄。

我想使用graph_objects而不是通过图表示来执行此操作,因为我希望两个旭日图可以并排。

来自df,我上面有如何在graph_objects中使用它。我不知道要为标签,父母,身份证等添加什么值...

fig = go.Figure()

fig.add_trace(
    go.Sunburst(
        lables = df.age,
        parents = df.gender,
        domain=dict(column=0)
    )
)

fig.show()

我正在阅读文档,但是我不明白它是如何工作的。如果有人知道,请告诉我如何使用带有以上df的graph_object创建旭日形图。

python plotly
1个回答
0
投票

如果px实际上确实为您提供了所需的朝阳图,则如下:

图1:

enter image description here

代码1:

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

# data
df = pd.DataFrame({'user':  [23, 24, 25,    26, 27],
                   'age':   [12, 13,15, 20, 21],
                   'gender':    ['male','male', 'female','male', 'male'] })

# plotly express figure
fig = px.sunburst(df, path=["gender", "age"])
fig.show()

然后,据我所知,您必须重组数据才能使用graph_objects。当前,您的数据的格式为

enter image description here

[graph_objects将需要label = ['12', '13', '15', '20', '21', 'female', 'male']。所以现在怎么办?经历为每个元素找到正确的数据结构的痛苦痛苦?不,只需使用px构建one图形,然后从那里“窃取”所有图形元素,并在graph_objects图形中使用它:

代码2:

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

# data
df = pd.DataFrame({'user':  [23, 24, 25,    26, 27],
                   'age':   [12, 13,15, 20, 21],
                   'gender':    ['male','male', 'female','male', 'male'] })

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

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

图2:

enter image description here

现在,如果您想在同一图中显示数据集的更多功能,只需将ids=fig['data'][0]['ids'].tolist()添加到混合中:

图3:

enter image description here

完整代码:

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

# data
df = pd.DataFrame({'user':  [23, 24, 25,    26, 27],
                   'age':   [12, 13,15, 20, 21],
                   'gender':    ['male','male', 'female','male', 'male'] })

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

# plotly graph_objects figure
fig2 =go.Figure(go.Sunburst(
    labels=fig['data'][0]['labels'].tolist(),
    parents=fig['data'][0]['parents'].tolist(),
    values=fig['data'][0]['values'].tolist(),
    ids=fig['data'][0]['ids'].tolist(),
    domain={'x': [0.0, 1.0], 'y': [0.0, 1.0]}
))

fig2.show()
© www.soinside.com 2019 - 2024. All rights reserved.