Python 带排序值的熊猫堆积条形图
我的目标是创建一个多级数据帧的堆叠条形图。数据帧如下所示:Python 带排序值的熊猫堆积条形图,python,pandas,dataframe,bar-chart,stacked,Python,Pandas,Dataframe,Bar Chart,Stacked,我的目标是创建一个多级数据帧的堆叠条形图。数据帧如下所示: 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.
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
我有两个目标:
bar
、baz
、foo
、qux
qux
条的高度为(10+26+11=)47,应位于第一个左侧,然后是高度为(10+24=)34的foo
条unstack
+绘图中新排序的索引值重新编制索引:游戏中增加了一个小功能:我们也可以在内部索引级别按值排序
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上打乱了堆叠条的顺序,从而玩起了破坏性的游戏(
不客气!是的,在这种背景下,颜色真的很独特。
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
s2.unstack().plot.bar(stacked=True)