My bar plot doesn't line up with the xbar and doesn't get the right colors (Plotly/Python)

Question:

I want to build the bar plot using plotly express (px.bar), but when I define the color, the bar plot doesn’t line up with the x bar, just something like this

before defining color

enter image description here

after defining color

bar plot modified

the bar doesn’t line up with the xbar after I define the color parameter, not like default bar plot, and why the color doesn’t match up with the color column in my dataframe?

here’s the code and dataframe

import pandas as pd

df = pd.DataFrame({
    'label': ['Apple', 'Banana', 'Orange', 'Grape', 'Apple', 'Banana', 'Orange', 'Grape', 'Grape'],
    'Count': [1, 2, 2, 2, 3, 5, 6, 3, 3],
    'Color': ['crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'lightslategrey']
})

import plotly.express as px
fig_bar = px.bar(df, x='label', y='Count', color = 'Color',
                 barmode='group')

fig_bar.show()

Dataframe

    label   Count   Color
0   Apple   1   crimson
1   Banana  2   lightslategrey
2   Orange  2   lightslategrey
3   Grape   2   lightslategrey
4   Apple   3   crimson
5   Banana  5   lightslategrey
6   Orange  6   lightslategrey
7   Grape   3   lightslategrey
8   Grape   3   lightslategrey

anyone here knows why that happen? Thanks!

Asked By: naranara

||

Answers:

You need to remove barmode="group"
After removing barmode, the plot performs as intended.

Also to get the colours from the dataframe to display for each bar, you will need to specify the color_discrete_sequence. See this for more detail.

Code

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    'label': ['Apple', 'Banana', 'Orange', 'Grape', 'Apple', 'Banana', 'Orange', 'Grape', 'Grape'],
    'Count': [1, 2, 2, 2, 3, 5, 6, 3, 3],
    'Color': ['crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'lightslategrey']
})

chart_df = df.groupby(by = ['label', 'Color']).sum().reset_index()
fig_bar = px.bar(chart_df, x='label', y='Count', color = 'Color', color_discrete_sequence=chart_df['Color'])
fig_bar.update_layout(showlegend=False)
fig_bar.show()

plot2

Note:

If you wanted to keep the white lines within the bars, then you would use this instead:

fig_bar = px.bar(df, x='label', y='Count', color = 'Color', color_discrete_sequence=df['Color'])
Answered By: ScottC