Pandas 具有排序值的堆积条形图

Pandas stacked bar chart with sorted values

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

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 个单独的容器中,称为 barbazfooqux

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

  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 + plot:

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

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

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)