Plotly Dash 中的堆积条形图

Stacked bar chart in Plotly Dash

我正在将 CSV 文件读入数据框并尝试绘制堆积条形图。对于每个国家/地区,我必须将正计数、负计数和中性计数堆叠为条形图。

我的数据如下所示。

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

我不会绘图。

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'
            }
        }
    )

输出图不是所需的堆叠格式。

您需要为每个情绪创建一个新的 go.bar() 轨迹,然后在“布局”下定义条形码。 documentation of Ploty 显示了一些有关如何操作的示例。

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)