簡體   English   中英

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()跟蹤,然后在“布局”下定義 barmode。 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM