用sns绘制箱线图

2024-04-25 05:53:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想以箱线图的形式描述在数据集中发现的变量的值。数据集如下所示:

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")

我的箱线图返回下图:

enter image description here

但我想用下图显示我的信息:

enter image description here

我知道这是一个不同的数据集,但我可以看到,他们已经显示了诊断,在同一时间,为每个特征及其值。我试过用不同的方法来做,但我做不到。你知道吗

我尝试了以下方法:

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')

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

谢谢


Tags: 数据importdfdatasizenamesascell
1条回答
网友
1楼 · 发布于 2024-04-25 05:53:28

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()

enter image description here

无缩放:

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()

enter image description here

相关问题 更多 >