删除 ggplot2 中 geom_boxplot 中的边框 [英] Removing the borders in geom_boxplot in ggplot2

查看:29
本文介绍了删除 ggplot2 中 geom_boxplot 中的边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来应该相对简单,但我找不到可以让我这样做的论据,我已经在 Google 和 Stack 中搜索了答案.

This should seem relatively straightforward but I can't find an argument which would allow me to do this and I've searched Google and Stack for an answer.

示例代码:

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)

这会输出第一张图,我想要第二张图.

This outputs the first graph, I would want something like the second.

我尝试包含 colour=cond 但这摆脱了中位数.

I tried including colour=cond but that gets rid of the median.

推荐答案

使用与 Marco Sandri 的答案相同的数据集来考虑两种可能的 hack.

Two possible hacks for consideration, using the same dataset as Marco Sandri's answer.

黑客 1.如果您真的不需要它来进行绘图,只需静态 ggplot 图像:

Hack 1. If you don't really need it to work in plotly, just static ggplot image:

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)

这覆盖了原始箱线图,其版本基本上是外箱的轮廓,隐藏了中位数(fatten = NULL),填充颜色(fill = NA), 晶须 (coef = 0) &离群值(outlier.alpha = 0).

This overlays the original boxplot with a version that's essentially an outline of the outer box, hiding the median (fatten = NULL), fill colour (fill = NA), whiskers (coef = 0) & outliers (outlier.alpha = 0).

但是,它似乎不适用于 plotly.我已经用 ggplot2 的开发版本(由 plotly 推荐)对其进行了测试,但无济于事.请参阅下面的输出:

However, it doesn't appear to work well with plotly. I've tested it with the dev version of ggplot2 (as recommended by plotly) to no avail. See output below:

黑客 2.如果您需要它在情节上工作:

Hack 2. If you need it to work in plotly:

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)

(ggplot输出同上)

(ggplot output is same as above)

plotly 似乎不理解 coef = 0 &output.alpha = 0 命令,所以这个 hack 创建了 y 变量的修改版本,这样 P30 以下的所有内容都设置为 P25,而上面的所有内容都设置为 P75.这将创建一个没有异常值、没有胡须的箱线图,并且中值与 P75 的箱线上限位于一起.

plotly doesn't seem to understand the coef = 0 & output.alpha = 0 commands, so this hack creates a modified version of the y variable, such that everything below P30 is set to P25, and everything above is set to P75. This creates a boxplot with no outliers, no whiskers, and the median sits together with the upper box limit at P75.

虽然比较麻烦,但是在情节上可以用:

It's more cumbersome, but it works in plotly:

这篇关于删除 ggplot2 中 geom_boxplot 中的边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆