Search code examples
pythonplotly

Use shades of the same colour to colour the bars of a plotly bar chart


I have a grouped bar chart and I would like to colour each group of bars a different shade of the same colour. So for example I want the years 2019-2022 to be coloured the same colour green however starting from a light green and finishing with a dark green.

 pd.DataFrame({
    'Year':['2019','2019','2019','2020','2020','2020','2021','2021','2021','2022','2022','2022'],
    'Event consultation method': ['Face to face','unknown','Telephone','Face to face','unknown','Telephone','unknown','Face to face','Telephone','Face to face','unknown','Telephone'],
    'ES':[8677, 2681, 58, 3270, 2076, 911, 6507, 6272, 2008, 13846, 7455, 1128]
}) 

fig = px.bar(df_es_cons, x=df_es_cons['Event consultation method'], y=df_es_cons['ES'],
         color=df_es_cons['Year'], 
         #color_discrete_sequence=['green']*len(df_es_cons),
         color_discrete_sequence=px.colors.qualitative.Set3,
         barmode='group', text_auto='.2s'
        
        )
fig.update_layout(title_text='Title', title_x=0.5)
fig.show()

    

enter image description here

I have not found the answer anywhere online and I created this bar chart using plotly express.


Solution

  • Update: Change to a graph object and define a list of the three blue colors you want to color-code. A loop process is used to extract the data by year and create a data frame. In order to keep the order in which the category variables are displayed, we create a dictionary of the order and sort them. If this is not done, they will be in numerical order and the colors will not be displayed correctly.Also, the y-axis is extended because the annotation string is cut off.

    colors = [["#87cefa","#3cb371","#ffd700"],["#00bfff","#228b22","#ffa500"],["#6495ed","#008000","#f4a460"],["#1e90ff","#006400","#ff8c00"]]
    
    fig = go.Figure()
    
    # sort order
    dict_order = {'Face to face': 1, 'unknown': 2, 'Telephone': 3}
    
    for y,c in zip(df_es_cons['Year'].unique(), colors):
        df = df_es_cons.query('Year == @y')
        dff = df.copy()
        dff['order'] = dff['Event consultation method'].map(dict_order)
        dff = dff.sort_values('order', na_position='first').reset_index(drop=True).drop(columns='order')
        fig.add_trace(go.Bar(x=dff['Event consultation method'], y=dff['ES'], marker_color=c, text=dff['ES'], name=y, showlegend=False))
    
    fig.update_traces(texttemplate='%{text:.2s}',textposition='outside')
    fig.update_yaxes(range=[0,15000])
    
    fig.show()
    

    enter image description here