How to make bar plot with colors according to the discrete sequence

Problem The color argument groups individual labels. I want them to be shown as they appear in data frame.
Details

I have a data frame that has two columns “Emotions” and “Gender”.
There are only three types of Emotions : “Anger”, “Sadness” and “Neutral”.

I use the following code, in which each column denotes the labels as they appear in the datagram.

import plotly.express as px
fig = px.bar(df, x="Emotions", 
             y="Gender", 
             barmode='relative', 
             orientation='h',
             height=400,
             title='Sequence of Emotions)
fig.show()

Now, I want to color the three labels (i.e. three types of Emotions") as they appear in the column of the datagram. I use the following code.

import plotly.express as px
fig = px.bar(df, x="Emotions", 
             y="Gender", 
             color="Emotions",
             barmode='relative', 
             orientation='h',
             height=400,
             title='Sequence of Emotions')
fig.show()

But the data pertaining to emotions is merged all together as if it was a sequential data. How to make colors appear as they are in the column?

@Emmanuelle Can you please help? Thank you so much!

@digli-dang-dang If you change the shape of your data a little you can achieve this:

import plotly.express as px
fig = px.bar(
    df,
    x=df.index, 
    y="Male", 
    color="Emotions",
    barmode='relative',
    height=400,
    title='Sequence of Emotions',
    labels={"index": "Emotions"}
).update_layout(
    bargap=0,
    xaxis_showticklabels=False,
    yaxis_showticklabels=False
)

fig.show()

And the result:

1 Like

wow! Thank you so much @RenaudLN. I must have spent more than an hour on this and could not find the solution. This is perfect!