这应该看起来相对简单,但我找不到可以让我这样做的论据,我已经在 Google 和 Stack 上搜索了答案。
示例代码:
library(ggplot2)
library(plotly)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))
p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot()
p <- ggplotly(p)
Run Code Online (Sandbox Code Playgroud)
这会输出第一个图,我想要第二个图。

我尝试包括colour=cond但摆脱了中位数。
使用与 Marco Sandri 的答案相同的数据集,需要考虑两种可能的 hacks。
黑客 1。如果你真的不需要它在 plotly 中工作,只需静态 ggplot 图像:
ggplot(dat, aes(x=cond, y=rating, fill=cond)) +
geom_boxplot() +
geom_boxplot(aes(color = cond),
fatten = NULL, fill = NA, coef = 0, outlier.alpha = 0,
show.legend = F)
Run Code Online (Sandbox Code Playgroud)
这用一个基本上是外框轮廓的版本覆盖了原始箱线图,隐藏了中值 ( fatten = NULL)、填充颜色 ( fill = NA)、胡须 ( coef = 0) 和异常值 ( outlier.alpha = 0)。
但是,它似乎不适用于 plotly。我已经用 ggplot2 的开发版本(由 plotly 推荐)对其进行了测试,但无济于事。请参阅下面的输出:
黑客 2。如果您需要它以情节方式工作:
ggplot(dat %>%
group_by(cond) %>%
mutate(rating.IQR = case_when(rating <= quantile(rating, 0.3) ~ quantile(rating, 0.25),
TRUE ~ quantile(rating, 0.75))),
aes(x=cond, y=rating, fill=cond)) +
geom_boxplot() +
geom_boxplot(aes(color = cond, y = rating.IQR),
fatten = NULL, fill = NA)
Run Code Online (Sandbox Code Playgroud)
(ggplot 输出与上面相同)
plotly 似乎不理解coef = 0&output.alpha = 0命令,所以这个 hack 创建了 y 变量的修改版本,这样 P30 以下的所有内容都设置为 P25,上面的所有内容都设置为 P75。这将创建一个没有异常值、没有胡须的箱线图,并且中位数与 P75 的箱线上限位于一起。
它更麻烦,但它的工作原理是: