Change whisker definition for only one level of a

2019-09-06 01:13发布

问题:

I'm trying to change the whisker definition to extend to the minimum and maximum (i.e., not to consider anything as an outlier), as in this question, but only for a single level of the factor that is mapped to the x-axis. The code in that answer will change the whisker definition for the entire plot.

What's the proper way, if any, to go about this?

回答1:

Extending the example linked in the question, you could do something like:

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

# sample data
d <- data.frame(x = gl(2,50), y = rnorm(100))

# do it
ggplot(d, aes(x, y)) + 
  stat_summary(data = subset(d, x == 1), fun.data = f, geom = "boxplot") +
  geom_boxplot(data = subset(d, x == 2))

In this case, factor x == 2 gets the "regular" geom_boxplot, but factor x == 1 is the "extended".


In your case, and being a little more abstract, you probably want to do something like this:

ggplot(d, aes(x, y)) + 
  stat_summary(data = subset(d, x == "special_factor"), fun.data = f, geom = "boxplot") +
  geom_boxplot(data = subset(d, x != "special_factor"))