JFerro
JFerro

Reputation: 3433

plotly: bar stacking graph

I have a Dataframe with data as follows:

data={'A': {'2020_01': 3, '2020_02': 3, '2020_03': 1, '2020_04': 3, '2020_05': 1},
 'B': {'2020_01': 0, '2020_02': 0, '2020_03': 3, '2020_04': 0, '2020_05': 2},
 'other': {'2020_01': 0,
  '2020_02': 0,
  '2020_03': 3,
  '2020_04': 0,
  '2020_05': 2},
 'total': {'2020_01': 3,
  '2020_02': 3,
  '2020_03': 7,
  '2020_04': 3,
  '2020_05': 5}}
df = pd.DataFrame(data)

I would like to represent with ploty in X the dates and in y stacked values of A, B, other

for one single bar I can do:

import plotly.express as px
fig = px.bar(df, x=df.index, y='A', text_auto=True,
             labels={'A':'bananas'}, height=400)
fig.show()

How to I have to proceed? I checked a bunch of documentation at no avail: https://community.plotly.com/t/plotly-express-bar-ignores-barmode-group/31511 https://plotly.com/python/bar-charts/ Plotly px.bar not stacking with barmode='stack' ... Result: enter image description here

Upvotes: 1

Views: 508

Answers (1)

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9786

All you should do the following:

  1. Reset the index and use it as column.

  2. Use melt function to convert the dataframe in the appropriate form.

  3. Use barmode="stack" to plot the stacked bars.

    import plotly.express as px
    import pandas as pd
    
    df.reset_index(inplace=True)
    df = df.iloc[:,:-1].melt(id_vars='index', var_name='categories', value_name='count')
    fig = px.histogram(df, x="index", y="count", text_auto=True, color="categories", barmode="stack",
         labels={'A':'bananas'}, height=400)
    fig.show()
    

Output:

enter image description here

Upvotes: 2

Related Questions