Facet/separate 使用公式但未绘制离群值时 R 中的箱线图? (ggplot2 或 r 基础知识)

Facet/separate boxplots in R when formula is used and outliers are not drawn? (ggplot2 or r basics)

我有一个名为 samples_type:

的数据框
Status   variable        value
PAT       SPP1        1,994629e+00
PAT       SPP1        1,179033e+00
PAT       SPP1        2,901539e+00
PAT       SPP1        1,140857e+00
PAT       SPP1        1,467056e+00
PAT       SPP1        2,579037e+00

"Status" 列可以取两个值:PAT 或 CON。 "variable" 列可以取很多值:SPP1、CCL24、ENG56 ...

我想为 Status:variable 的每个组合绘制值的箱线图。

目前我有两个代码:

boxplot(value ~ Status:variable, data=samples_type,
col=c("red", "limegreen"), las=2, outline=F)

和:

p0 <- ggplot(data = samples_J0_type, aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Status)) +
facet_wrap( ~ variable, scales="free")

第一个代码为我提供了一个图表中的所有箱线图,没有异常值。我想将它们分开,因为 par(mfrow=c(...,...)) 会这样做。 我该怎么做?

在第二个代码中,我使用了 ggplot2。我设法将箱线图分开 BUT 如您所见,我没有设法删除离群值,而且由于离群值,我的箱线图太小了。 如何删除离群值? 我在 Whosebug 上查看了如何使用 ggplot2 删除离群值,我找到了仅针对一个箱线图的答案,但没有找到多个箱线图的答案。我不知道该怎么做...

编辑:每个代码的箱线图

一般

有点难以提供帮助,因为您没有提供最小的数据集,所以我不得不回到现有数据。

mt <- mtcars %>% select(cyl, mpg, am)
## add some outliers
mt <- rbind(mt, data.frame(cyl = c(4, 6, 8), mpg = rep(100, 3), am = 0))

基础 R

您可以根据变量之一拆分数据,相应地设置 mfrow 并使用 apply 函数分别生成每个图:

## split your data according to one variable
dl <- split(mt, mt$am)

## set the mfrow
par(mfrow = 1:2)
## something more educated would be something like this
## needs to be adapted for border cases
## par(mfrow = c(ceiling(sqrt(length(dl))), ceiling(sqrt(length(dl)))))

## loop through all data sets
lapply(dl, function(d) boxplot(mpg ~ cyl, data = d, outline = FALSE))

但是,boxplot(. outliers = TRUE) 并没有真正去除异常值,而是延长了胡须。

ggplot

对于你的第二个问题,你可以先通过

隐藏你的异常值
geom_boxplot(aes(fill = Status), outlier.shape = NA)

然后根据您的数据通过 ylim 调整 y 范围。

。从技术上讲,您不需要使用 outlier.shape = NA 因为如果您使用 ylim 超出范围的点无论如何都会被丢弃,但这会使代码更加冗长以显示您想要做什么。

带有内置数据集的示例

library(tidyverse)

## plot w/ outliers shown
ggplot(mt, aes(x = factor(cyl), y = mpg)) + 
   geom_boxplot() + 
   facet_wrap(~am)

## plot with outliers removed
ggplot(mt, aes(x = factor(cyl), y = mpg)) + 
   geom_boxplot(outlier.shape = NA) + 
   facet_wrap(~am) + 
   ylim(c(0, 50))

警告

在您的更新中,您添加了绘图,我看到您有自由比例尺,这将使这种方法变得无用,因为您无法在每个面板上指定 ylim 基础。

感谢@thothal,我post 最终代码有效:

dl = split(samples_type, samples_type$variable)
par(mfrow = c(ceiling(sqrt(length(dl))),ceiling(sqrt(length(dl)))))
iwalk(dl, ~ boxplot(value ~ Status , data = .x,
      outline = FALSE,col=c("red", "limegreen"), main=.y))

"iwalk" 来自包 "purrr".

记住,数据框的头部samples_type:

Status   variable        value
PAT       SPP1        1,994629e+00
PAT       SPP1        1,179033e+00
PAT       SPP1        2,901539e+00
PAT       SPP1        1,140857e+00
PAT       SPP1        1,467056e+00
PAT       SPP1        2,579037e+00

"Status" 列可以取两个值:PAT 或 CON。 "variable" 列可以取很多值:SPP1、CCL24、ENG56 ...