在seaborn箱线图上绘制子地块的观测数量(python)

2024-06-17 14:58:16 发布

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

我已经为我定义了一个函数,用于使用箱线图分析我的列

    fig, ax = plt.subplots((len(list_of_columns)),1,figsize= datafigsize) 
    fig.suptitle(suptitle,fontsize=30)
    ax = ax.ravel() # Ravel turns a matrix into a vector, which is easier to iterate
    plt.tight_layout(h_pad = 3,pad=10);
    
    for i, column in enumerate(list_of_columns): 
        nobs = dataframe[column].value_counts().values
        nobs = [str(y) for y in nobs.tolist()]
        nobs = ["n: " + j for j in nobs]   
        pos = range(len(nobs))
        medians = dataframe.groupby([column])['saleprice'].median().values
        for tick,label in zip(pos,ax[i].get_xticklabels()):                                   
            ax[i].text(pos[tick], medians[tick] + 0.03, nobs[tick],
                    horizontalalignment='center', size='small', color='k', weight='semibold')
            sns.boxplot(data = dataframe, 
                        x= dataframe[column], 
                        y='saleprice',
                        ax=ax[i]) 
            ax[i].set_title(list_of_titles[i],fontdict={'fontsize': 15})
            ax[i].xaxis.set_visible(True);

子地块运行良好。 我的观察数字也被绘制出来

然而,观测数量只能绘制在6个类别上。以下是一个例子:

仅显示6个类别的n=#。 仅显示6个类别的n=#。


Tags: columnsofinposdataframeforlenfig
1条回答
网友
1楼 · 发布于 2024-06-17 14:58:16

最有可能的情况是,您的环境中存在导致问题的其他对象。您还将sns.boxplot放置在错误的for循环中

如果我使用示例数据集进行设置:

import pandas as pd
import seaborn as sns
import numpy as np
import string
import matplotlib.pyplot as plt

Vars = [i for i in string.ascii_letters]
np.random.seed(111)
dataframe = pd.DataFrame({'saleprice':np.random.uniform(0,100,100),
                          'var1':np.random.choice(Vars[0:5],100),
                          'var2':np.random.choice(Vars[5:12],100),
                         'var3':np.random.choice(Vars[12:21],100)})

list_of_columns = ['var1','var2','var3']

您可以在下面看到,我稍微修改了脚本,计算了data.frame中的中值和观察数。还要确保打印顺序和计数顺序相同(我在下面使用groupby数据框的索引作为参考):

for i, column in enumerate(list_of_columns): 
    stats_df = dataframe.groupby(column)['saleprice'].agg(median=np.median,n=len)
    stats_df = stats_df.sort_values('median')
    sns.boxplot(data = dataframe, x= column,y='saleprice',ax=ax[i],order=stats_df.index)
    ax[i].set_title(list_of_columns[i],fontdict={'fontsize': 15})
    
    for xpos in range(len(stats_df)):
        label = "n= "+str(stats_df['n'][xpos])
        ypos = stats_df['median'][xpos] + 0.03
        ax[i].text(xpos,ypos,label,horizontalalignment='center', size='small')

enter image description here

相关问题 更多 >