【问题标题】:How to make a barplot for the target variable with each predictive variable?如何使用每个预测变量为目标变量制作条形图?
【发布时间】:2023-01-04 20:00:15
【问题描述】:

我有一个 pandas df,看起来像这样(缩放后):

      Age     blood_Press   golucse   Cholesterol
0   1.953859    -1.444088   -1.086684   -1.981315
1   0.357992    -0.123270   -0.585981   0.934929
2   0.997219    0.998712    2.005212    0.019169
3   2.589318    -0.528543   -1.123484   -1.299904
4   2.088141    0.792976    0.021526    -0.777959

和一个二元目标特征:

     y
0   1.0
1   1.0
2   1.0
3   0.0
4   1.0

我想用 y 目标为每个预测特征制作一个条形图。所以 y 值将在 x 轴上,即 10,而在 y 轴上将是预测特征的值。例如,看起来像这样的东西(忽略这里使用的功能,只是我需要的一个例子)。所以这里不是malefemale,而是10...

这个情节的代码是这样的:

myPlot = sns.catplot(data = data, x = 'the y feature' , y = 'the x feature', kind = 'bar')
myPlot.fig.suptitle('title title', size=15, y=1.);
myPlot.set_ylabels('Y label whatever', fontsize=15, x=1.02)
myPlot.fig.set_size_inches(9,8);

但我不想对每个功能都重复它,我相信它比那简单得多。但是怎么办?

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    设置

    print(df)
    
            Age  blood_Press   golucse  Cholesterol    y
    0  1.953859    -1.444088 -1.086684    -1.981315  1.0
    1  0.357992    -0.123270 -0.585981     0.934929  1.0
    2  0.997219     0.998712  2.005212     0.019169  1.0
    3  2.589318    -0.528543 -1.123484    -1.299904  0.0
    4  2.088141     0.792976  0.021526    -0.777959  1.0
    

    Melt 从宽格式转换为长格式的数据框

    m = df.melt(id_vars=['y'], var_name='feature')
    print(m)
    
    #       y      feature     value
    # 0   1.0          Age  1.953859
    # 1   1.0          Age  0.357992
    # 2   1.0          Age  0.997219
    # 3   0.0          Age  2.589318
    # 4   1.0          Age  2.088141
    # 5   1.0  blood_Press -1.444088
    # 6   1.0  blood_Press -0.123270
    # 7   1.0  blood_Press  0.998712
    # 8   0.0  blood_Press -0.528543
    # 9   1.0  blood_Press  0.792976
    # 10  1.0      golucse -1.086684
    # 11  1.0      golucse -0.585981
    # 12  1.0      golucse  2.005212
    # 13  0.0      golucse -1.123484
    # 14  1.0      golucse  0.021526
    # 15  1.0  Cholesterol -1.981315
    # 16  1.0  Cholesterol  0.934929
    # 17  1.0  Cholesterol  0.019169
    # 18  0.0  Cholesterol -1.299904
    # 19  1.0  Cholesterol -0.777959
    

    然后使用catplot方法并将col参数作为feature列传递

    sns.catplot(data=m, x='y', y='value', col='feature', kind='bar', col_wrap=2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 2019-02-15
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多