【问题标题】:For ggplot2 geom_boxplot, is there a way to remove the box and whiskers when only 2 samples?对于 ggplot2 geom_boxplot,只有 2 个样本时,有没有办法去除盒子和胡须?
【发布时间】:2019-01-14 21:14:08
【问题描述】:

当特定组中只有几个样本时,我遇到了 geom_boxplot 和 ggplot2 的问题。当一个组中有少量样本时,来自 ggplot2 的 geom_boxplot 命令仍会生成盒子和胡须,创建一个即使不合适时也会给出四分位数的视图。

我希望有人知道一种方法来强制 ggplot2 不为具有少量样本的组绘制框和胡须。

这是一个展示问题的玩具示例。

###Example
library(ggplot2)

#Set DF for plot 
Num <- c(150, 196, 182, 224, 111, 129, 80, 183, 130, 171, 169, 165)
Group <- c("Three", "Three", "One", "Two", "One", "Two", "One", "Two", "One", "Two", "One", "Two")
DF <- data.frame(Num, Group)

#Make figure
p1 <- ggplot(DF, aes(Group, Num))
p1 + geom_boxplot(aes(fill=Group)) + scale_color_manual(values = c("#CC0000", "#0000E5", "#008000")) + theme_minimal() + scale_shape_manual(values = c(16,17,15)) +
geom_point(size = 2.5) + scale_x_discrete(limits=c("One", "Two", "Three")).

目前输出如下图,但“三”组下只有两个样本。有没有办法强制特定组仅在组中的样本少于 N 个时显示点?

对于这个数字,我希望第一组和第二组看起来像他们一样,但希望第三组只有两个点,没有别的。任何帮助是极大的赞赏。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    最简单的解决方案当然是通过预先计算点数,只给geom_boxplot你想要绘制的数据行:

    DF$n = with(DF, ave(Num, Group, FUN = length))
    ## if you like dplyr
    # DF = group_by(DF, Group) %>% mutate(n = n())
    
    ggplot(DF, aes(Group, Num)) +
      geom_boxplot(data = subset(DF, n > 2), aes(fill = Group)) +
      scale_color_manual(values = c("#CC0000", "#0000E5", "#008000")) +
      theme_minimal() + 
      scale_shape_manual(values = c(16, 17, 15)) +
      geom_point(size = 2.5) + 
      scale_x_discrete(limits = c("One", "Two", "Three"))
    

    【讨论】:

    • 附注:group_by(DF, Group) %&gt;% mutate(n = n()) 也可以写成add_count(DF, Group)
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2018-03-14
    • 2020-08-28
    • 2021-05-28
    相关资源
    最近更新 更多