Python Seaborn 多个条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38807895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Seaborn multiple barplots
提问by jakko
I have a pandas dataframe that looks like this:
我有一个如下所示的 Pandas 数据框:
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
How would I create a plot using seaborn that looks like this? Do I have to rearrange my data in some way?
我将如何使用 seaborn 创建一个看起来像这样的情节?我是否必须以某种方式重新排列我的数据?
(source: mwaskom at stanford.edu)
回答by ayhan
Yes you need to reshape the DataFrame:
是的,您需要重塑 DataFrame:
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
Now, you can use factorplot (v0.8.1 or earlier):
现在,您可以使用 factorplot(v0.8.1 或更早版本):
sns.factorplot(x='class', y='survival rate', hue='sex', data=df, kind='bar')
For versions 0.9.0 or later, as Matthew noted in the comments, you need to use the renamed version, catplot
.
对于 0.9.0 或更高版本,正如 Matthew 在评论中指出的,您需要使用重命名的版本catplot
.
sns.catplot(x='class', y='survival rate', hue='sex', data=df, kind='bar')
回答by Khaled Almanea
I know my answer came very late but I hope someone benefit from it.
我知道我的回答来得很晚,但我希望有人能从中受益。
to solve the above I used the below code after re-arranging the data of course:
为了解决上述问题,我当然在重新排列数据后使用了以下代码:
Data:
数据:
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")