Plotly: How to specify colors for a group using go.Bar?

You could simply use a dictionary like this:

colors = {'A':'steelblue',
          'B':'firebrick'}

The only challenge lies in grouping the dataframe for each unique type and adding a new trace for each type using a for loop. The code snippet below takes care of that to produce this plot:

enter image description here

# imports
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go

# data
d = {'Scenario': [1, 2, 3, 1, 2,3],
     'Type': ["A", "A", "A", "B", "B", "B"],
     'VAL_1': [100, 200, 300, 400 , 500, 600],
     'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
df = pd.DataFrame(data=d)

# assign colors to type using a dictionary
colors = {'A':'steelblue',
          'B':'firebrick'}

# plotly figure
fig=go.Figure()
for t in df['Type'].unique():
    dfp = df[df['Type']==t]
    fig.add_traces(go.Bar(x=dfp['Scenario'], y = dfp['VAL_1'], name=t,
                         marker_color=colors[t]))

fig.show()

Leave a Comment