带R中虚拟变量的重叠数据子集的箱线图

时间:2019-03-28 13:34:37

标签: r ggplot2

我想可视化与ggplot2中的箱线图的均值比较,但是除了具有分类变量的向量之外,我还有几个具有1或0的向量来指示它们是否属于该类别。存在一些重叠-即某些数据点将同时属于多个组。

我能够获得一个组中所有值的箱形图,但是无法将另一组的值添加到同一图中。通过将as.factor()应用于虚拟变量,我能够获得该组与非该组中那些的均值得分的箱形图。我看过有关刻面的帖子可能会有所帮助,但我发现的所有示例(Multiple boxplots placed side by side for different column values in ggplotHow do I make a boxplot with two categorical variables in R?)都与我尝试做的完全不同。

score <- c(1, 8, 3, 5, 10, 7, 4, 3, 8, 1)
group1 <- c(0, 0, 1, 0, 1, 1, 0, 1, 0, 1)
group2 <- c(1, 1, 0, 1, 0, 1, 1, 1, 0, 0)
group3 <- c(0, 1, 0, 0, 0, 0, 0, 0, 1, 1)
df <- data.frame(score, group1, group2, group3)
library(ggplot2)
ggplot(aes(y=score, x=as.factor(group1), fill=group1), data=df) +
  geom_boxplot() #mean for both values inside and outside group plotted
ggplot(aes(y=score, x=as.numeric(group1), fill=group1), data=df) +
  geom_boxplot() #mean for just those values where group1 == 1

我想以a)多个图作为我从第一行代码得到的结果,或者b)多个图作为从我第二行得到的结果来结束。前者包括一个组外所有值的箱线图,后者则没有。对于总体均值有一个箱线图也是很酷的,但我真的不确定什么可行。

1 个答案:

答案 0 :(得分:0)

我不太确定您是否只希望对哑元为1的人使用箱形图。无论如何,data.table::melt对您可能有用,这为您提供了一种易于绘制的长格式表格。

library(data.table)
dat.m <- melt(dat, measure.vars=2:4)

boxplot(score ~ value + variable, dat.m[dat.m$value == 1, ])

产量

enter image description here


数据

dat <- structure(list(score = c(1, 8, 3, 5, 10, 7, 4, 3, 8, 1), group1 = c(0, 
0, 1, 0, 1, 1, 0, 1, 0, 1), group2 = c(1, 1, 0, 1, 0, 1, 1, 1, 
0, 0), group3 = c(0, 1, 0, 0, 0, 0, 0, 0, 1, 1)), class = "data.frame", row.names = c(NA, 
-10L))