【问题标题】:Pandas stacked bar chart with sorted values带有排序值的 Pandas 堆积条形图
【发布时间】:2016-11-22 15:34:30
【问题描述】:

我的目标是创建多级数据框的堆叠条形图。数据框如下所示:

import pandas as pd
import numpy as np

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'three'])]

s = pd.Series([10,20,10,22,10,24,10,26, 11], index=arrays)

In[1]: s

Out[1]: 
bar  one      10
     two      20
baz  one      10
     two      22
foo  one      10
     two      24
qux  one      10
     two      26
     three    11
dtype: int64

我有两个目标:

  1. 创建一个堆叠条形图,以便将值堆叠到 4 个单独的 bin,称为 barbazfooqux

  2. 这 4 根钢筋应按尺寸排序。在此示例中,qux 条的高度为 (10+26+11=)47,应位于第一个左侧,然后是高度为 (10+24)=34 的 foo 条。

【问题讨论】:

    标签: python pandas dataframe bar-chart stacked


    【解决方案1】:
    1. 按照总和对一级索引进行排序:

    s_sort = s.groupby(level=[0]).sum().sort_values(ascending=False)
    s_sort
    qux    47
    foo    34
    baz    32
    bar    30
    dtype: int64
    
    1. 使用第一级中新的排序索引值重新索引 + unstack + 绘图:

    cmp = plt.cm.get_cmap('jet')
    s.reindex(index=s_sort.index, level=0).unstack().plot.bar(stacked=True, cmap=cmp)
    

    【讨论】:

    • 不客气!是的,在这个设置中颜色真的很明显。
    【解决方案2】:

    游戏的一个小补充:我们也可以在内部索引级别按值排序

    s1=s.groupby(level=[0]).apply(lambda x:x.groupby(level=[1]).sum().sort_values(ascending=False))
    s1
    

    内层现在已排序。

    bar  two      20
         one      10
    baz  two      22
         one      10
    foo  two      24
         one      10
    qux  two      26
         three    11
         one      10
    dtype: int64
    

    现在我们按照已经提到的方式按外层排序。

    s_sort = s1.groupby(level=[0]).sum().sort_values(ascending=False)
    s2 = s1.reindex(index=s_sort.index, level=0)
    s2
    
    qux  two      26
         three    11
         one      10
    foo  two      24
         one      10
    baz  two      22
         one      10
    bar  two      20
         one      10
    dtype: int64
    

    不幸的是,matplotlib 通过在自己的 X(

    s2.unstack().plot.bar(stacked=True)
    

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多