【问题标题】:Plotting two dataframe columns with the third as x axis绘制两个数据框列,第三个作为 x 轴
【发布时间】:2021-05-17 07:11:39
【问题描述】:

我有以下数据框:

    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 中快速制作,但我正在生成我在脚本中使用的数据框)

我的代码是这样的:

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 列:

有谁知道我如何修复这些代码中的一个或两个以获得我想要的结果?

【问题讨论】:

    标签: python python-3.x pandas matplotlib seaborn


    【解决方案1】:

    您可能需要融合您的数据框以使其具有正确的形状,然后您应该能够使用 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
    

    输出

    【讨论】:

    • 效果很好,谢谢! (我不得不切换 y 和 hue 列来获得我想要的输出,但效果很好。)
    • 如果这个答案解决了你的问题,请考虑accepting it.
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多