【问题标题】:How to plot aggregated DataFrame using two columns?如何使用两列绘制聚合的 DataFrame?
【发布时间】:2016-08-05 12:59:54
【问题描述】:

我有以下内容,使用具有两列的 DF,我想通过以下方式聚合:

df2.groupby(['airline_clean','sentiment']).size()
airline_clean  sentiment
americanair    -1             14
                0             36
                1           1804
                2            722
                3            171
                4              1
jetblue        -1              2
                0              7
                1           1074
                2            868
                3            250
                4             11
southwestair   -1              4
                0             20
                1           1320
                2            829
                3            237
                4              4
united         -1              7
                0             74
                1           2467
                2           1026
                3            221
                4              5
usairways      -1              5
                0             62
                1           1962
                2            716
                3            155
                4              2
virginamerica  -1              2
                0              2
                1            250
                2            180
                3             69
dtype: int64

绘制聚合视图:

dfc=df2.groupby(['airline_clean','sentiment']).size() dfc.plot(kind='bar',stacked=True,figsize=(18,6))

结果:

我想改变两点:

  • 按航空公司在堆积图中绘制数据
  • 使用 % 而不是原始数字(航空公司也一样)

我不确定如何实现。任何方向表示赞赏。

【问题讨论】:

    标签: pandas plot seaborn


    【解决方案1】:

    最好的方法是绘制这个数据集是先转换为 % 值,然后使用 unstack() 进行绘图:

    airline_sentiment = df3.groupby(['airline_clean', 'sentiment']).agg({'tweet_count': 'sum'})
    airline = df3.groupby(['airline_clean']).agg({'tweet_count': 'sum'})
    p = airline_sentiment.div(airline, level='airline_clean') * 100
    
    p.unstack().plot(kind='bar',stacked=True,figsize=(9, 6),title='Sentiment % distribution by airline')
    

    这会产生一个漂亮的图表:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2021-07-22
      • 2012-06-12
      相关资源
      最近更新 更多