如何在plot.ly中更改sunburst绘图的颜色?

2024-04-28 19:37:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望所有的哺乳动物都是黄色的,所有的爬行动物都是绿色的。我不能使用plot express,因为我的学校不允许。代码如下:

import plotly.graph_objs as go

fig = go.Figure(go.Sunburst(
    labels=["Animal", "Reptile", "Lizard", "Snake", "Bird", "Salamander", 
            "Canary", "tweetle", "Mammal", "Equine", "Bovine", "Canine", 
            "Horse", "Zebra", "Cow", "Lassle", "Rintintin", "Bessle"],
    parents=["", "Animal", "Reptile", "Reptile", "Reptile", "Lizard",
            "Bird", "Canary", "Animal", "Mammal", "Mammal", "Mammal",
            "Equine", "Equine", "Bovine", "Canine", "Canine", "Cow"],
))


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

fig.show()

Tags: gofigcaninecanary黄色cow哺乳动物animal
1条回答
网友
1楼 · 发布于 2024-04-28 19:37:07

我认为有一个更好的方法,如果你能从你的数据中提取出df,但是从px版本做一些反向工程,你可以试试

import plotly.graph_objs as go

labels = ["Animal", "Reptile", "Lizard", "Snake", "Bird", "Salamander", 
          "Canary", "tweetle", "Mammal", "Equine", "Bovine", "Canine", 
          "Horse", "Zebra", "Cow", "Lassle", "Rintintin", "Bessle"]

parents = ["", "Animal", "Reptile", "Reptile", "Reptile", "Lizard",
           "Bird", "Canary", "Animal", "Mammal", "Mammal", "Mammal",
           "Equine", "Equine", "Bovine", "Canine", "Canine", "Cow"]

colors = []
for p in labels:
    if p in ["Reptile", "Lizard", "Snake", "Bird", "Salamander",
             "Canary", "tweetle"]:
        colors.append("green")
    elif p in ["", "Animal"]:
        colors.append("white")
    else:
        colors.append("yellow")

fig = go.Figure(
    go.Sunburst(
     labels=labels,
     parents=parents,
     marker=dict(colors=colors)
    )
)


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

fig.show()

enter image description here

相关问题 更多 >