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

Time:12-28

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!

CodePudding user response:

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 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'])
  • Related