Mar*_*llo 12 python bar-chart pandas stacked-chart seaborn
我正在寻找一种根据“色调”绘制带有堆叠条的计数图的有效方法。标准色调行为是根据第二列的值将计数拆分为平行条,我正在寻找的是一种将色调条堆叠以便快速比较总数的有效方法。
让我用一个来自泰坦尼克号数据集的例子来解释:
import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline
df = sns.load_dataset('titanic')
sns.countplot(x='survived',hue='class',data=df)
Run Code Online (Sandbox Code Playgroud)
提供带有计数图和色调的标准 Seaborn 行为

我正在寻找的是类似于每个色调的堆叠条

为了获得最后一张图片,我使用了以下代码
def aggregate(rows,columns,df):
column_keys = df[columns].unique()
row_keys = df[rows].unique()
agg = { key : [ len(df[(df[rows]==value) & (df[columns]==key)]) for value in row_keys]
for key in column_keys }
aggdf = pd.DataFrame(agg,index = row_keys)
aggdf.index.rename(rows,inplace=True)
return aggdf
aggregate('survived','class',df).plot(kind='bar',stacked=True)
Run Code Online (Sandbox Code Playgroud)
我相信有一些更有效的方法。我知道 seaborn 对堆叠条形不太友好……所以我尝试用我的函数重新排列数据集并使用 matplotlib,但我想还有一种更聪明的方法可以做到这一点。
非常感谢!
ALo*_*llz 24
您的最后一部分基本上就在那里,使用DataFrame.plot()withbar和stacked=True。
aggregate您可以使用groupby+完成您想要的功能,而不是您的功能pivot。
df_plot = df.groupby(['class', 'survived']).size().reset_index().pivot(columns='class', index='survived', values=0)
class First Second Third
survived
0 80 97 372
1 136 87 119
Run Code Online (Sandbox Code Playgroud)
从这里您可以将其绘制为bar带有stacked=True参数的 a
df_plot.plot(kind='bar', stacked=True)
Run Code Online (Sandbox Code Playgroud)