Python Seaborn多重条形图
我有一个熊猫数据框,看起来像这样:Python Seaborn多重条形图,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我有一个熊猫数据框,看起来像这样: class men woman children 0 first 0.91468 0.667971 0.660562 1 second 0.30012 0.329380 0.882608 2 third 0.11899 0.189747 0.121259 我如何使用seaborn创建一个如下所示的绘图?我是否必须以某种方式重新排列我的数据 (来源:)是的,您需要重塑数据
class men woman children
0 first 0.91468 0.667971 0.660562
1 second 0.30012 0.329380 0.882608
2 third 0.11899 0.189747 0.121259
我如何使用seaborn创建一个如下所示的绘图?我是否必须以某种方式重新排列我的数据
(来源:)是的,您需要重塑数据帧:
df = pd.melt(df, id_vars="class", var_name="sex", value_name="survival rate")
df
Out:
class sex survival rate
0 first men 0.914680
1 second men 0.300120
2 third men 0.118990
3 first woman 0.667971
4 second woman 0.329380
5 third woman 0.189747
6 first children 0.660562
7 second children 0.882608
8 third children 0.121259
现在,您可以使用factorplot(v0.8.1或更早版本):
对于版本0.9.0或更高版本,如Matthew在中所述,您需要使用重命名的版本,catplot
sns.catplot(x='class', y='survival rate', hue='sex', data=df, kind='bar')
我知道我的答案来得很晚,但我希望有人能从中受益 为了解决上述问题,我在重新整理数据后使用了以下代码: 数据:
这是正确的,但我要看一下
pd.melt
。它做同样的整形,但是更干净。很好。我添加了一个额外的编辑,它可以保存一行代码并使结果更加健壮,因为它不依赖于您知道列的顺序。请注意,factorplot已重命名为catplot,如下所述:@Matthew谢谢,我添加了一个注释。
sns.catplot(x='class', y='survival rate', hue='sex', data=df, kind='bar')
d = {'class': ['first', 'second', 'third', 'first', 'second', 'third', 'first', 'second', 'third'], 'sex': ['men', 'men', 'men', 'woman', 'woman', 'woman', 'children', 'children', 'children'], 'survival_rate':[0.914680, 0.300120, 0.118990, 0.667971, 0.329380, 0.189747, 0.660562, 0.882608, 0.121259]}
df = pd.DataFrame(data=d)
sns.factorplot("sex", "survival_rate", col="class", data=df, kind="bar")