Search code examples
pythoncolorsplotlybar-chartplotly-python

How to set specific color to some bars in a plotly bar graph?


I'm trying to set different colors for some bars in a plotly express bar graph:

import plotly.express as px
import pandas as pd

data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',  
         '2020/05', '2020/07', '2020/08'],  
        'Value':[34,56,66,78,99,55,22]}
df = pd.DataFrame(data)

color_discrete_sequence = ['#ec7c34']*len(df)
color_discrete_sequence[5] = '#609cd4'
fig=px.bar(df,x='Name',y='Value',color_discrete_sequence=color_discrete_sequence)
fig.show()

My expectations were that one (the sixth one) bar had a different color, however I got this result:

enter image description here

What am I doing wrong?


Solution

  • This happens because color in px.bar is used to name a category to illustrate traits or dimensions of a dataset using a colorscale. Or in you your case, rather a color cycle since you're dealing with a categorical / discrete case. color_discrete_sequence is then used to specify which color sequence to follow. One way to achieve your goal using your setup here, is to simply define a string variable with unique values, for example like df['category'] [str(i) for i in df.index], and then use:

    fig=px.bar(df,x='Name',y='Value',
               color = 'category',
               color_discrete_sequence=color_discrete_sequence,
               )
    

    Plot:

    enter image description here

    If df['category'] is a numerical value, color_discrete_sequence will be ignored, and a default continuous sequence will be applied:

    enter image description here

    If anything else is unclear, don't hesitate to let me know.

    Complete code:

    import plotly.express as px
    import pandas as pd
    
    data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',  
             '2020/05', '2020/07', '2020/08'],  
            'Value':[34,56,66,78,99,55,22]}
    df = pd.DataFrame(data)
    df['category'] = [str(i) for i in df.index]
    # df['category'] = df.index
    
    color_discrete_sequence = ['#ec7c34']*len(df)
    color_discrete_sequence[5] = '#609cd4'
    fig=px.bar(df,x='Name',y='Value',
               color = 'category',
               color_discrete_sequence=color_discrete_sequence,
               )
    fig.show()