【问题标题】:Change box width from IQR to user defined in seaborn boxplot将盒子宽度从 IQR 更改为 seaborn boxplot 中定义的用户
【发布时间】:2021-05-09 20:59:25
【问题描述】:

我想用从最小到最大的盒子绘制 seaborn boxplot,而不是从第 2 到第 3 个四分位数,我可以在 matplotlib 或 seaborn 中控制它吗?我知道我可以控制胡须 - 盒子怎么样?

【问题讨论】:

    标签: matplotlib seaborn boxplot


    【解决方案1】:

    这是一种使用聚合数据框通过水平图模拟 seaborn 箱线图的方法。

    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    # set sns plot style
    sns.set()
    tips = sns.load_dataset('tips')
    fig, (ax1, ax2) = plt.subplots(nrows=2)
    
    sns.boxplot(x='total_bill', y='day', data=tips, ax=ax1)
    
    day_min_max = tips[['day', 'total_bill']].groupby('day').agg(['min', 'max', 'median'])
    day_min_max.columns = day_min_max.columns.droplevel(0)  # remove the old column name, only leaving 'min' and 'max'
    
    ax2.use_sticky_edges = False
    sns.barplot(y=day_min_max.index, x=day_min_max['median'] - day_min_max['min'], left=day_min_max['min'], ec='k', ax=ax2)
    sns.barplot(y=day_min_max.index, x=day_min_max['max'] - day_min_max['median'], left=day_min_max['median'], ec='k', ax=ax2)
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      【解决方案2】:

      描绘第一个和第三个四分位数是箱线图的定义特征,因此我认为不存在此选项。但是,如果您想使用最小值和最大值,则不会绘制任何晶须,因此您可以简单地使用条形图:

      import numpy as np
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      data = np.random.rand(10, 3)
      sns.barplot(x=np.arange(10), y=data.ptp(axis=1), bottom=data.min(axis=1))
      plt.show()
      

      【讨论】:

      • 不错的简洁解决方案。请注意,您需要sns.barplot(x=..., y=data.ptp(axis=1), bottom=data.min(axis=1)),因为y 是从bottom 开始的条形高度。使用y=data.max(axis=1),条形从min 变为min+max
      • @JohanC 谢谢,很好。可耻的是,这甚至不是我第一次犯这个特殊错误......不知何故,height 是一个亲戚height 不想进入我的大脑。现已编辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2012-04-26
      相关资源
      最近更新 更多