0

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?

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That worked nicely! It is a little counter intuitive for me that calling fig.add_trace twice behaves this way. I was expecting some sort of overwrite. But it is actually appending (adding as the name suggest) to the figure. It seems that the order a, b is kept regardless of their order in the loop. Interesting. Now I'm left with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.