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

问题描述 投票:-1回答:1

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

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))

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

可能有人有建议吗?我很感激。谢谢。

r ggplot2 boxplot
1个回答
2
投票

我不知道这是不是你想要的,但也许你可以从下面的代码中激励自己。

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

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

enter image description here

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))
}

enter image description here

编辑。

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

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)))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.