Search code examples
pythonbar-chartplotly-dashplotly-python

Stacked bar chart in Plotly Dash


I am reading a CSV file into dataframe and trying to plot a stacked bar chart. For each country, I have to stack, positive counts, negative counts, and neutral counts as a bar chart.

My data looks like below.

country         sentiment           count
India           positive            10
India           negative            7
Pakistan        positive            120
Pakistan        negative            10
Pakistan        neutral             3
Australi        positive            35
NewZealand      positive            20
NewZealand      negative            20
NewZealand      neutral             0

I'm not able to plot.

df = pd.read_csv("C:\\Users\\sentiment_by_location.csv")
df = df.sort_values(by=['count'], ascending=False)

    html.H2(children='''Sentiments by Location'''),
    dcc.Graph(
        id='sentimet-location',
        figure={
            'data': [
                go.Bar(
                    x=df['location'],
                    y=[df['sentiment'], df['count']]
                )
            ],
            'layout': {
                'title': 'Sentiment By Location'
            }
        }
    )

enter image description here

The output plot is not in desired stacked format.


Solution

  • You need to create for each sentiment an new go.bar() trace and then define under "layout" the barmode. The documentation of Ploty shows a few examples on how to do it.

    import pandas as pd
    import plotly.graph_objects as go
    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    
    
    df = pd.read_csv("C:\\Users\\sentiment_by_location.csv")
    df = df.sort_values(by=['count'], ascending=False)
    
    bars = []
    for sentiment in df['sentiment'].unique():
        bar = go.Bar(name=sentiment, x=df[df['sentiment'] == sentiment]
                     ['country'], y=df[df['sentiment'] == sentiment]['count'])
        bars.append(bar)
    
    
    fig = go.Figure(data=bars)
    fig.update_layout(barmode='stack', title='Sentiment By Location')
    
    app = dash.Dash()
    app.layout = html.Div([
        dcc.Graph(figure=fig)
    ])
    
    app.run_server(debug=True, use_reloader=False)