ggplot2 - 使用 geom_boxplot 生成带有自定义晶须的水平箱线图时出错

ggplot2 - Error while generating a horizontal boxplot with custom whiskers using geom_boxplot

出于教育目的,我正在尝试使用 ggplot2 生成水平箱线图和点图。但是,我想生成一个自定义箱线图,其中胡须位于 2.5% 和 97.5% 百分位数,而不是 geom_boxplot 使用的 1.5*IQR 定义。因此,我决定使用以下代码:

y <- rnorm(100)
df = data.frame(y)
df_boxplot <- data.frame(
  x_coord = 0.5,
  y0 = quantile(y, 0.025),
  y25 = quantile(y, 0.25),
  y50 = median(y),
  y75 = quantile(y, 0.75),
  y100 = quantile(y, 0.975)
)
# Vertical orientation with custom whiskers works
ggplot() +
  geom_boxplot(data = df_boxplot,
    aes(x = x_coord, ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
    stat = "identity"
  ) +
  geom_jitter(data = df, aes(y=y, x=0.5))
# Horizontal orientation with custom whiskers throws an error
ggplot() +
  geom_boxplot(data = df_boxplot,
               aes(y=x_coord, xmin = y0, xlower = y25, xmiddle = y50, xupper = y75, xmax = y100),
               stat = "identity"
  ) +
  geom_dotplot(data = df, aes(x=y))

# Using horizontal stat_summary with custom whiskers works
f <- function(x) {
  r <- quantile(x, probs = c(0.025, 0.25, 0.5, 0.75, 0.975))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}
ggplot() +
  stat_summary(data = df, aes(x=y, y=0.5), fun.data=f, geom="boxplot", position="dodge2", orientation = "y") +
  geom_dotplot(data = df, aes(x=y))

但是,当使用水平方向和胡须的自定义定义时,出现以下错误:

Error in `$<-.data.frame`(`tmp`, "xmin", value = numeric(0)) :

Replacement has 0 rows, data has 1

这个错误似乎是 geom_boxplot 特有的,因为它适用于 stat_summary。请问geom_boxplot报错的原因是什么,如何解决。情节应该看起来像这样:

您需要设置 orientation = 'y' 才能直接从 geom_boxplot 获取水平箱线图。您可能认为 geom_boxplot 会从提供的美学中猜出这一点,但事实并非如此。

ggplot() +
  geom_boxplot(data = df_boxplot,
               aes(y = x_coord, xmin = y0, xlower = y25, xmiddle = y50, 
                   xupper = y75, xmax = y100),
               stat = "identity", orientation = 'y'
  ) +
  geom_dotplot(data = df, aes(x=y))