4

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.

M--
  • 25,431
  • 8
  • 61
  • 93
JA-pythonista
  • 1,225
  • 1
  • 21
  • 44

2 Answers2

5

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

M--
  • 25,431
  • 8
  • 61
  • 93
  • 1
    This solution did not work for me. A straightforward solution would be to simply provide the desired color codes in `color_discrete_sequence`. For example, `fig = px.box(df, x="day", y="total_bill", color="sex", color_discrete_sequence=[ "#FF7F0E", "#00CC96"])` – PyLabour Mar 09 '22 at 00:18
  • @PyLabour if you provide a reproducible example, I can investigate further, considering that your solution is essentially the same. – M-- Mar 09 '22 at 00:38
1

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