在`geom_boxplot`中仅更改一个因子级别的胡须定义

时间:2022-01-16 13:05:26

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.

我正在尝试将晶须定义更改为最小值和最大值(即,不要将任何事物视为异常值),如此问题中所示,但仅针对映射到x轴的因子的单个级别。该答案中的代码将改变整个图的胡须定义。

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

如果有的话,有什么方法可以解决这个问题?

1 个解决方案

#1


3  

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".

在这种情况下,因子x == 2获得“常规”geom_boxplot,但因子x == 1是“扩展”。


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"))

#1


3  

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".

在这种情况下,因子x == 2获得“常规”geom_boxplot,但因子x == 1是“扩展”。


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"))