Dror
Dror

Reputation: 13051

Set different colors based on categories when box plotting in Plotly

Assume having the data:

import pandas as pd
df = pd.DataFrame(
    {
        "val": np.random.normal(0, 1, size=100),
        "cat": np.random.choice(["a", "b"], size=100),
    }
)

Next, visualize a box plot:

from plotly import graph_objects as go
fig = go.Figure()
fig.add_trace(go.Box(y=df["val"], x=df["cat"], boxmean="sd",))

I'm using go.Box since I want to visualize the STD. This yields:

enter image description here

How can I set different colors of for the left and right box plots depending on the category?

Upvotes: 0

Views: 742

Answers (1)

r-beginners
r-beginners

Reputation: 35115

You can change the color by looping through each category variable.

for c in df['cat'].unique():
    dff = df[df['cat'] == c]
    fig.add_trace(go.Box(y=dff["val"], x=dff["cat"], boxmean="sd", name=c))

enter image description here

Upvotes: 1

Related Questions