合并分组箱线图r的data.frames

合并分组箱线图r的data.frames,r,ggplot2,R,Ggplot2,我有两个数据帧z(一百万次观测)和b(500k次观测) 我想创建分组箱线图,使用时间作为因素,处理作为颜色。本质上,我需要将它们绑定在一起,然后区分它们,但不确定如何区分。我尝试的一种方法是: zz<-factor(rep("Z", nrow(z)) bb<-factor(rep("B",nrow(b)) dumB<-merge(z,zz) #this won't work because it says it's too big dumB<-merge(b,zz) to

我有两个数据帧z(一百万次观测)和b(500k次观测)

我想创建分组箱线图,使用时间作为因素,处理作为颜色。本质上,我需要将它们绑定在一起,然后区分它们,但不确定如何区分。我尝试的一种方法是:

zz<-factor(rep("Z", nrow(z))
bb<-factor(rep("B",nrow(b))
dumB<-merge(z,zz) #this won't work because it says it's too big
dumB<-merge(b,zz)
total<-rbind(dumB,dumZ)

zz我将按如下方式处理:

# create a list of your data.frames
l <- list(z,b)
# assign names to the dataframes in the list
names(l) <- c("z","b")

# bind the dataframes together with rbindlist from data.table
# the id parameter will create a variable with the names of the dataframes
# you could also use 'bind_rows(l, .id="id")' from 'dplyr' for this
library(data.table)
zb <- rbindlist(l, id="id")

# create the plot
ggplot(zb, aes(x=factor(time), y=Tracer, color=treatment)) +
  geom_boxplot() +
  facet_wrap(~id) +
  theme_bw()
ggplot(zb, aes(x=treatment, y=Tracer, color=interaction(id, time))) + 
  geom_boxplot(width = 0.7, position = position_dodge(width = 0.7)) + 
  theme_bw()

作为对您最后一条评论的回应:要在一个绘图中获得所有内容,您可以使用
交互
来区分不同的分组,如下所示:

# create a list of your data.frames
l <- list(z,b)
# assign names to the dataframes in the list
names(l) <- c("z","b")

# bind the dataframes together with rbindlist from data.table
# the id parameter will create a variable with the names of the dataframes
# you could also use 'bind_rows(l, .id="id")' from 'dplyr' for this
library(data.table)
zb <- rbindlist(l, id="id")

# create the plot
ggplot(zb, aes(x=factor(time), y=Tracer, color=treatment)) +
  geom_boxplot() +
  facet_wrap(~id) +
  theme_bw()
ggplot(zb, aes(x=treatment, y=Tracer, color=interaction(id, time))) + 
  geom_boxplot(width = 0.7, position = position_dodge(width = 0.7)) + 
  theme_bw()
其中:


关键是您不需要执行
合并
,这在大型表上计算成本很高。相反,为每个数据帧分配一个新的变量和值(下面代码中的源c(b,z)),然后
rbind
。然后它变得很简单,我的解决方案与@Jaap非常相似,只是有不同的方面

library(ggplot2)
#Create some mock data
t<-seq(1,55,by=2)
z<-data.frame(tracer=sample(t,size = 10,replace = T), time=c(0,15), treatment=c("S","X"))
b<-data.frame(tracer=sample(t,size = 10,replace = T), time=c(0,15), treatment=c("S","X"))
#Add a variable to each table to id itself
b$source<-"b"
z$source<-"z"
#concatenate the tables together
all<-rbind(b,z)

ggplot(all, aes(source, tracer, group=interaction(treatment,source), fill=treatment)) +
  geom_boxplot() + facet_grid(~time)
库(ggplot2)
#创建一些模拟数据

太好了,真的非常感谢你!看起来很棒!有可能按时间而不是z/b刻面吗?我刚刚意识到我实际上是在同一张图上寻找箱线图,类似于本页上的最后一个图:切割是时间,价格是示踪,颜色=处理。这是可能的,因为我的图形在刻面时看起来不可比较。:-)我真的很感激,谢谢你,它现在看起来很漂亮。我会用我认为合适的颜色和宽度让它看起来更显眼。我已经将互动切换到id,现在治疗:-)非常感谢您的支持help@HCAI是的,请参阅更新。您必须在
geom_boxplot
中同时使用
width
参数才能看到您最喜欢的内容。谢谢您,非常感谢。我选择Jaap的回应是因为我可以毫无困难地遵循代码,直接将其应用到我的代码中,而无需替换任何内容。还有一张我所追求的图片,因此它在视觉上重申了代码的有效性(至少从新手的角度来看)