Search code examples
pandasplotly

How to create percentage stacked bar chart in plotly?


I have this code but want to create a stacked % bar chart. How would I do that?

fig = px.bar(df, x='date', y=['var1','var2','var3', 'var4'],barmode='stack')
fig.show()

enter image description here


Solution

  • I think you should make a new column that calculate % of each var and then use it to deploy chart. Please refer my below code:

    import pandas as pd
    import numpy as np
    from datetime import datetime as dt
    import plotly.express as px
    
    df = pd.DataFrame({
        'date': ['2022-01-07','2022-02-07','2022-03-07','2022-04-07','2022-05-07','2022-06-07','2022-07-07','2022-08-07'],
        'var1': [5,7,2,4,6,8,10,9],
        'var2': [6,7,8,5,2,6,3,1],
        'var3':[8,5,6,2,8,3,5,4],
        'var4':[7,9,7,5,3,4,2,1]})
    
    df_melt = df.melt(id_vars=['date'],var_name='var',value_name='Amount',value_vars=df.columns[1:],ignore_index=True)
    
    df_melt['%'] = 100 * df_melt['Amount'] / df_melt.groupby('date')['Amount'].transform('sum')
    
    fig = px.bar(df_melt, x="date", y="%",color='var',
            title="Bar Plot", 
            template="plotly_white")   
    fig.update_layout(barmode="relative")
    fig.update_layout(plot_bgcolor='white')
    fig.update_yaxes(showline=False,showgrid=False)
    fig.update_xaxes(showline=False,showgrid=False)
    fig.show()
    

    And here is the Output: enter image description here