【问题标题】:plotting boxplot with sns用 sns 绘制箱线图
【发布时间】:2019-10-27 03:22:07
【问题描述】:

我想以箱线图的形式描述我在数据集中找到的变量的值。数据集如下:

https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)

到目前为止,我的代码如下:

import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing

df=pd.read_csv(file,names=['id', 'clump_thickness','unif_cell_size',
                                                         'unif_cell_shape', 'marg_adhesion', 'single_epith_cell_size',
                                                         'bare_nuclei', 'bland_chromatin', 'normal_nucleoli','mitoses','Class'])

#boxplot
    plt.figure(figsize=(15,10))
    names=list(df.columns)
    names=names[:-1]

    min_max_scaler=preprocessing.MinMaxScaler()


    X = df.drop(["Class"],axis=1)
    columnsN=list(X.columns) 
    x_scaled=min_max_scaler.fit_transform(X) #normalization
    X[columnsN]=x_scaled 
    y = df['Class']

    sns.set_context('notebook', font_scale=1.5)
    sns.boxplot(x=X['unif_cell_size'],y=y,data=df.iloc[:, :-1],orient="h")

我的箱线图返回下图:

但我想如下图所示显示我的信息:

我知道这是来自不同的数据集,但我可以看到他们同时显示了每个特征及其值的诊断。我试图以不同的方式来做,但我不能做那个图表。

我尝试了以下方法:

data_st = pd.concat([y,X],axis=1)
    data_st = pd.melt(data_st,id_vars=columnsN,
                    var_name="X",
                    value_name='value')

    sns.boxplot(x='value', y="X", data=data_st,hue=y,palette='Set1')
    plt.legend(loc='best')

但仍然没有结果。有什么帮助吗?

谢谢

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    pandas.DataFrame.melt重塑数据:

    • 大多数良性(2 类)箱线图都在 0(缩放)或 1(未缩放),因为它们应该是
      • print(df_scaled_melted.groupby(['Class', 'Attributes', 'Values'])['Values'].count().unstack())melt 之后,了解计数
    • MinMaxScaler 已被使用,但在这种情况下是不必要的,因为所有数据值都非常接近。如果您在不缩放的情况下绘制数据,则绘图看起来相同,除了 y 轴范围将是 1 - 10。
      • 这实际上应该只在数据大相径庭的情况下使用,在这种情况下,某个属性会对某些 ML 算法产生太大影响。
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from pathlib import Path
    import numpy as np
    from sklearn.preprocessing import MinMaxScaler
    
    # path to file
    p = Path(r'c:\some_path_to_file\breast-cancer-wisconsin.data')
    
    # create dataframe
    df = pd.read_csv(p, names=['id', 'clump_thickness','unif_cell_size',
                               'unif_cell_shape', 'marg_adhesion', 'single_epith_cell_size',
                               'bare_nuclei', 'bland_chromatin', 'normal_nucleoli','mitoses','Class'])
    
    # replace ? with np.NaN
    df.replace('?', np.NaN, inplace=True)
    
    # scale the data
    min_max_scaler = MinMaxScaler()
    df_scaled = pd.DataFrame(min_max_scaler.fit_transform(df.iloc[:, 1:-1]))
    df_scaled.columns = df.columns[1:-1]
    df_scaled['Class'] = df['Class']
    
    # melt the dataframe
    df_scaled_melted = df_scaled.iloc[:, 1:].melt(id_vars='Class', var_name='Attributes', value_name='Values')
    
    # plot the data
    plt.figure(figsize=(12, 8))
    g = sns.boxplot(x='Attributes', y='Values', hue='Class', data=df_scaled_melted)
    for item in g.get_xticklabels():
        item.set_rotation(90)
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.show()
    

    不缩放:

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from pathlib import Path
    import numpy as np
    
    p = Path.cwd() / r'data\breast_cancer\breast-cancer-wisconsin.data'
    
    df = pd.read_csv(p, names=['id', 'clump_thickness','unif_cell_size',
                               'unif_cell_shape', 'marg_adhesion', 'single_epith_cell_size',
                               'bare_nuclei', 'bland_chromatin', 'normal_nucleoli','mitoses','Class'])
    
    df.replace('?', np.NaN, inplace=True)
    df.dropna(inplace=True)
    df = df.astype('int')
    
    df_melted = df.iloc[:, 1:].melt(id_vars='Class', var_name='Attributes', value_name='Values')
    
    plt.figure(figsize=(12, 8))
    g = sns.boxplot(x='Attributes', y='Values', hue='Class', data=df_melted)
    for item in g.get_xticklabels():
        item.set_rotation(90)
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2017-10-24
      • 1970-01-01
      相关资源
      最近更新 更多