Black Lives Matter. Please consider donating to Campaign Zero's mission of ending police violence in America.
https://www.joincampaignzero.org

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/

Still looking into adding references to the daily aggregate bar charts mentioned above. The problem I am having is that since the x axis is represented by text, I was unable to add line traces on the corresponding grouped bar charts. I also tried the bargap method, but it didn’t seem to work. I am hoping that I can keep using the plotly express way of creating the daily bar charts because the amount of days in my data is variable, so it makes the code very flexible. I have created a mock-up of the chart and line graph that I am trying to create. Is there a fairly simple way to create this in plotly express?