JA-pythonista
JA-pythonista

Reputation: 1323

Explicitly set colours of the boxplot in ploltly

I am using plotly express to plot boxplot as shown below:

px.box(data_frame=df, 
       y="price", 
       x="products",
       points="all")

However, the boxpots of the products shown up with the same colours. They are four products. I would like to colour each with a different colour, using an additional paramter color_discrete_sequence does not work.

Upvotes: 4

Views: 6336

Answers (2)

Robert Feller
Robert Feller

Reputation: 21

You will need to add, before plotting, this parameter setting (as part of an effective solution) in order to align the (indeed!) newly colored box plots correctly.

fig.update_layout(boxmode = "overlay")

The boxmode setting "overlay" brings the plot back to the normal layout, that is seemingly being overridden (as setting "group") after having set the color.

In the plotly help it says about boxmode:

"Determines how boxes at the same location coordinate are displayed on the graph. If 'group', the boxes are plotted next to one another centered around the shared location. If 'overlay', the boxes are plotted over one another [...]"

Hope this helps! R

Upvotes: 2

M--
M--

Reputation: 28825

I am using plotly.express.data.tips() as an example dataset and am creating a new column called mcolour to show how we can use an additional column for coloring. See below;

## packages
import plotly.express as px
import numpy as np
import pandas as pd
## example dataset:
df = px.data.tips()

## creating a new column with colors
df['mcolour'] = np.where(
     df['day'] == "Sun" , 
    '#636EFA', 
     np.where(
        df['day'] == 'Sat', '#EF553B', '#00CC96'
     )
)
## plot
fig = px.box(df, x="day", y="total_bill", color="mcolour")
fig = fig.update_layout(showlegend=False)
fig.show()

So, as you see, you can simply assign colors based on another column using color argument in plotly.express.box().

Upvotes: 5

Related Questions