【问题标题】:How can I add tick marks in a boxplot based on a boolean value in a DataFrame?如何根据 DataFrame 中的布尔值在箱线图中添加刻度线?
【发布时间】:2020-03-19 12:11:00
【问题描述】:

如何根据 'boolean_val' 的值向该箱线图添加点或刻度线?

import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame(np.random.rand(140, 1)*1000, columns=['int_value'])

df['boolean_value'] = np.random.random(df.shape)<0.5

sns.boxplot(x=df['int value'])
plt.show()

【问题讨论】:

    标签: python pandas numpy seaborn


    【解决方案1】:
    • boolean_value 设置为 x 轴,按单独的分类值绘制箱线图。
    import pandas as pd
    import numpy as np
    import seaborn as sns
    
    df = pd.DataFrame(np.random.rand(140, 1)*1000, columns=['int_value'])
    df['boolean_value'] = np.random.random(df.shape)<0.5
    
    sns.boxplot(y=df['int_value'], x=df['boolean_value'])
    plt.show()
    

    • 您在评论中要求添加数据点并不是箱线图的工作方式。但是,可以在顶部添加 swarmplot,以创建相同的效果。
    sns.boxplot(y=df['int_value'], x=df['boolean_value'])
    sns.swarmplot(y=df['int_value'], x=df['boolean_value'], color='black')
    plt.show()
    

    • 如果你想要一个只有True的情节
    sns.boxplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True])
    sns.swarmplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True], color='black')
    plt.show()
    

    • 如果您希望将整个分布作为单个箱线图,但只希望显示真实数据点。
    sns.boxplot(y=df['int_value'])
    sns.swarmplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True], color='black', label='only True')
    plt.xticks([0], [''])
    plt.xlabel('True/False Boxplot Distribution')
    plt.legend()
    plt.show()
    

    注意:

    • 对于样本数据,很难直观地辨别仅 True 数据的分布与 True/False 组合分布之间的差异。
    df.describe()
    
            int_value
    count  140.000000
    mean   524.828022
    std    302.097860
    min      1.566518
    25%    240.890088
    50%    567.986782
    75%    778.906109
    max    995.508649
    
    df.groupby('boolean_value').describe()
    
                  int_value                                                                                  
                      count        mean         std       min         25%         50%         75%         max
    boolean_value                                                                                            
    False              70.0  525.125956  291.117406  1.566518  247.411473  577.119686  770.783246  995.508649
    True               70.0  524.530087  314.800514  8.077607  233.074629  550.306306  828.866101  993.770101
    

    【讨论】:

    • 我试图有 1 个箱线图,其中只有真值显示为方框内的标记以查看分布。有没有办法将它添加到箱线图中?
    猜你喜欢
    • 2018-08-09
    • 2020-05-22
    • 2018-04-08
    • 2018-02-22
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多