R 箱形图,所有数据点从低到高排序

R box plot with all data points ordered from low to high

在 R 中,我想创建一个也显示所有数据点的箱线图。您可以在许多帖子和网站上找到此信息,但它们似乎都以“抖动”或“随机”方式显示数据点。这是在 R 中使用带有 ggplot2 的 ToothGrowth 数据集的示例代码。

library(datasets)
data(ToothGrowth)
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
library(ggplot2)
ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot(notch = TRUE) +
  geom_jitter(position=position_jitter(0.2))

但是,我希望数据点从左下角的最低点到右上角的最高点排序。请参阅此 link 中的示例: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3966983/figure/F1/(可免费访问)。具体来说,我参考图 1a,顶部(“纯度”)。

可能有人有建议吗?我将不胜感激。谢谢。

我不知道这是不是你想要的,但也许你可以从下面的代码中得到启发。

set.seed(1234)
n <- 20
x <- rnorm(n)

boxplot(x)
points(seq(0.75, 1.25, length.out = n), sort(x))

df1 <- sapply(1:4, function(i) rnorm(n, mean = i))
df1 <- as.data.frame(df1)
df1 <- reshape2::melt(df1)

boxplot(value ~ variable, df1)
sp <- split(df1, df1$variable)
for(i in 1:4){
  points(seq(i - 0.25, i + 0.25, length.out = n), sort(sp[[i]]$value))
}

编辑。

ggplot2 解决方案使用类似的技巧来定义点的 x 轴坐标。唯一 "strange" 是依赖 R 的内部因子表示作为从 1 开始的连续整数。请注意,这必须被视为 hack,但作为可靠的,我不相信它会永远改变。

library(ggplot2)
library(tidyverse)

df1 %>%
  group_by(variable) %>%
  arrange(value) %>%
  mutate(xcoord = seq(-0.25, 0.25, length.out = n())) %>%
  ggplot(aes(x = variable, y = value, group = variable)) +
  geom_boxplot() +
  geom_point(aes(x = xcoord + as.integer(variable)))