AltijdGoed
AltijdGoed

Reputation: 55

How do I change the color of a sunburst plot in plot.ly?

I want all the Mammals to be yellow, and all reptiles to be green. I can't use plot express because my school doesn't allow it. Code is as follows:

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()

Upvotes: 2

Views: 1727

Answers (1)

rpanai
rpanai

Reputation: 13447

I think there is a better way if you can make a df out of your data but doing some reverse engineering from px version you could try

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

Upvotes: 2

Related Questions