ggplot:用箱线图显示组和时间交互(2x2)

时间:2016-03-31 11:37:19

标签: r ggplot2 reshape boxplot

我见过ggplot2和reshapre库的几个例子。但我的最终结果仍然覆盖了我的箱形图。我还没有看到关于2x2 boxplot-design(组和时间交互)的任何简单示例。我只有一个数据框。

ggplot(aes(y = DV, x = "Group and Time", col = df$group), data = df) + 
  geom_boxplot(aes(y = df$y1, x=df$group, col="T1")) + 
  geom_boxplot(aes(y = df$y2, x=df$group, col="T2"))

enter image description here

T2(蓝色)的颜色覆盖T1颜色(红色)。我的最小例子看起来像这样:

set.seed(1234)
x<- sample(c("exp", "con"), 100, replace = TRUE)
yT1<-rnorm(100)
yT2<-rnorm(100)
df<- (as.data.frame(cbind(x,yT1,yT2)))
head(df)

    x                yT1                  yT2
1 exp  0.405002805433516     1.94871306497599
2 exp   0.97580332180945    0.933816332207727
3 con -0.348876736539909     1.91305942169705
4 con  0.158625439491262 -0.00523405793193957
5 exp  -1.76325506654115   -0.152260048921635
6 exp  0.338596047099905   -0.509631657179118

ggplot(aes(y = DV, x = "group and time", col = df$x), data = df) + 
  geom_boxplot(aes(y = df$yT1, x=df$x, col="T1")) + 
  geom_boxplot(aes(y = df$yT2, x=df$x, col="T2")) 

我知道我的最小例子缺少某种类转换(df是因子,但应该包含数字列)。我为此感到抱歉,但我现在不知道如何解决这个问题。我希望你明白这个主意。非常感谢你

1 个答案:

答案 0 :(得分:1)

我不确定你究竟是什么意思 - 我想,exp / con和T1 / T2之间的相互作用?

也许这个是您正在寻找的情节(请注意函数调用中的interaction aes):

library(ggplot2)
library(tidyr)

set.seed(1234)
x<- sample(c("exp", "con"), 100, replace = TRUE)
yT1<-rnorm(100)
yT2<-rnorm(100)
df1 <- as.data.frame(cbind(x,yT1,yT2))

df2 <- gather(df1, "grp", "val", yT1, yT2)
df2$val <- as.numeric(df2$val)

ggplot(df2, aes(x = grp, y = val, interaction = x, colour = grp)) + 
  geom_boxplot()

enter image description here

或作为替代方案,为每个组提供自己的颜色:

df2$newx <- sprintf("%s.%s", as.character(df2$x), df2$grp)

ggplot(df2, aes(x = newx, y = val, colour = newx)) + 
  geom_boxplot()

enter image description here