Plotly px.bar not stacking with barmode='stack'

Viewed 381

I am trying to create a single-column bar chart with the desired result looking something like this enter image description here

I figured the barmode = 'stack' would do the trick but the bars are not stacking

enter image description here

lang    count   percentage
Undetermined    1202    37.56
English (default)   806 25.19
Arabic  529 16.53
French  524 16.38 
German  32  1.00


import plotly.express as px
fig_lang=px.bar(df_lang,
            y='lang',
            x='percentage',
            color='lang',
            color_discrete_sequence=px.colors.qualitative.T10,
            barmode='stack', 
            orientation = 'h',
     text=df_lang['percentage'].apply(lambda x: '{0:1.2f}%'.format(x)))
fig_lang.show()

Any pointers to why or how to accomplish this would be much appreciated!

1 Answers
  • effectively you want to plot all the bars against same x value. Have done this by setting it as a constant in data frame
  • then it's simple case of using color and y
import pandas as pd
import io
import numpy as np
import plotly.express as px

df_lang = pd.read_csv(
    io.StringIO(
        """lang    count   percentage
Undetermined    1202    37.56
English_(default)   806 25.19
Arabic  529 16.53
French  524 16.38 
German  32  1.00"""
    ),
    sep="\s+",
)

px.bar(df_lang.assign(bar=1), color="lang", x="bar", y="percentage").update_layout(
    xaxis_visible=False, autosize=False, width=300
)

enter image description here

Related