ggplot2 - 最小/最大的Boxplot Whiskers

时间:2014-11-13 23:03:00

标签: r ggplot2

在ggplot2中,我希望将胡须扩展到数据集的最小值和最大值,而不是显示异常值。我找到了隐藏异常值的方法,但是我无法将胡须延伸到每组的最小值和最大值。

a <- data.frame(group = "a", value = rnorm(10))
b <- data.frame(group = "b", value = rnorm(100))
c <- data.frame(group = "c", value = rnorm(1000))

data <- rbind(a, b, c)

ggplot(data, aes(x=group, y=value)) + 
  stat_boxplot(geom ='errorbar') +
  geom_boxplot() #geom_boxplot(outlier.shape = NA)

问:设置ggplot2箱图的正确方法是什么,以便胡须延伸到最小值和最大值?


1 个答案:

答案 0 :(得分:2)

根据LJW的评论,我认为这就是你想要的:

a <- data.frame(group = "a", value = rnorm(10))
b <- data.frame(group = "b", value = rnorm(100))
c <- data.frame(group = "c", value = rnorm(1000))

data <- rbind(a, b, c)

o <- function(x) {
  subset(x, x == max(x) | x == min(x))
}

f <- function(x) {
  r <- quantile(x, probs = c(0.00, 0.25, 0.5, 0.75, 1))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

ggplot(data, aes(x=group, y=value)) + 
  stat_summary(fun.data=f, geom="boxplot") + 
  stat_summary(fun.y = o, geom="point") +
  stat_boxplot(geom='errorbar',coef=10) #just give an arbitrarily big number here

<强>更新 您可以在stat_boxplot函数中添加带有coef参数的胡须:

enter image description here