[英]Plotting two dataframe columns with the third as x axis
我有以下 dataframe:
type_of_thing group1 group 2
0 type1 0.030659 0.052632
1 type2 0.099169 0.026316
2 type3 0.184580 0.236842
3 type4 0.469446 0.605263
我想要做的是比较第一组和第二组的每种类型。我想要的图表有点像这样: (在 excel 中快速制作,但我正在生成我在脚本中使用的 dataframe)
我的代码是这样的:
import seaborn as sns
...
rest of code
...
sns.catplot(x='type_of_thing', y=group1,kind="bar", data=df)
或者我有这个代码:
df.plot(kind='bar')
plt.show()
但是这样显示,当我希望 type_of_thing 列用作 x 轴的标签时,完全忽略 type_of_thing 列:
有谁知道我如何修复这些代码中的一个或两个以获得我想要的结果?
您可能需要熔化您的 dataframe 以使其形状正确,然后您应该能够将group
用作您的 x,并将type_of_thing
用作您的色调
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'type_of_thing': ['type1', 'type2', 'type3', 'type4'],
'group1': [0.030659, 0.09916900000000001, 0.18458, 0.46944600000000003],
'group2': [0.052632000000000005, 0.026316000000000003, 0.236842, 0.605263]})
df = df.melt(id_vars='type_of_thing', var_name='group')
# So you can see what happened with melt and why it helps here
print(df)
sns.catplot(data=df, x='group',y='value', kind='bar', hue='type_of_thing')
这是融化的 df 的样子:
type_of_thing group value
0 type1 group1 0.030659
1 type2 group1 0.099169
2 type3 group1 0.184580
3 type4 group1 0.469446
4 type1 group2 0.052632
5 type2 group2 0.026316
6 type3 group2 0.236842
7 type4 group2 0.605263
Output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.