Search code examples
pythonpython-3.xplotlyplotly-pythonplotly-express

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.


Solution

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