Setting color scheme on bar chart grouped by two columns

Hello. I am a newbie.

I am trying to create a specific grouped bar chart. I need to be able to load data that has different numbers of days in a dataframe that has the following columns: provider, days, speed. The graph groups correctly when I set the color to the “day” column, but I would like to set the graph colors to be unique to the provider column with four colors and remain grouped not stacked. Is this possible?

import plotly.express as px

(px.bar(dayDf, x=“provider”,y=“speed”, color=“day”,
barmode=“group”)
.update_layout(title_font_size=24)
.update_xaxes(showgrid=True)
).show()

Output:

Data:
image

Hello @radair, welcome to the forum!

The px.bar call creates one bar trace per unique value of day. You can later on update each trace with custom colors for each bar (each value of the provider in your case). Below is an example using a dataset from px

import plotly.express as px
df = px.data.gapminder().query("continent == 'Oceania'")
df['year'] = df['year'].astype(str) # to have categorical values
fig = px.bar(df, x='country', y='pop', color='year', barmode='group')
fig.update_traces(marker_color=['red', 'blue'], showlegend=False)
fig.show()

Below I used the text attribute so that the year is displayed since it’s not in the legend any more.

1 Like

Thanks for your fast response. That is perfect.

Is there an easy way to add a reference line(s) horizontally on the y-axis to each of the bar chart groups with plotly express?

Can you please give more details? Not sure I understand. Anyway, you can create first a figure with plotly express and then add other traces, shapes, annotations etc. with fig.add_traces, fig.update_layout etc.

See https://plot.ly/python/creating-and-updating-figures/