pythonplotlyhistogramvisualization

Plotly python histogram add custom colors to distinct values


I have a dataframe, with 4 distinct values in a column, for each value I need to set the custom colors.

Below is the sample data

val,cluster
118910.000000,3
71209.000000,2
25674.666667,0
109267.666667,3
8.000000,1

Below is the code.

fig = px.histogram(types, x="val",color='cluster')
fig.show()

types is the dataframe name from data given

When I figureI get default colors. Instead I need to get

0:red

2:blue

1:purple

3:green

How can I set the custom colors in python plotly for histogram

Can anyone help on this pls


Solution

  • You can use color_discrete_map.

    import pandas as pd 
    import random
    df = pd.DataFrame([[random.random()*100,random.randint(0,3)]for i in range (100)],columns = ['val','cluster'])
    fig = px.histogram(df, x="cluster",y='val',
                       color = 'cluster',
                        color_discrete_map = {0:'red',1:'blue',2:'purple',3:'green'}
                      )
    fig
    

    enter image description here