【问题标题】:Stacked bar chart in Plotly DashPlotly Dash 中的堆积条形图
【发布时间】:2021-11-14 12:13:21
【问题描述】:

我正在将 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'
            }
        }
    )

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

【问题讨论】:

    标签: python bar-chart plotly-dash plotly-python


    【解决方案1】:

    您需要为每个情绪创建一个新的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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2021-03-09
      • 2020-08-25
      • 2018-11-14
      • 2017-09-25
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多