ggplot使用互动和分组

时间:2018-10-25 22:35:47

标签: r ggplot2 boxplot

我需要在情节中使用交互和分组,但显示效果不正确。我想让图看起来像图1,x轴上的单个值可能在y轴上有多个方框图。例如,在图2中,您可以看到“ item25”在x轴上出现了两次,如图1所示。图2的示例代码如下所示。非常感谢您的帮助。

enter image description here  图1

enter image description here  图2

library("ggplot2")
library("plyr")
df<-data.frame(I = c(25, 25, 25, 25, 25, 25,25,85, 85, 85,85,85,85,85,125,125,125,125, 125, 125), U = c(1,1,1,2,2,2,2, 1,1,1,1,2,2,2,1,1,1,2,2,2),
           V =c(1.03, 1.06, 1.1,1.08,1.87,1.56,1.75,1.82, 1.85, 1.90,2.03, 2.06, 2.1,2.08,2.87,2.56,2.75,2.82, 2.85, 2.90), type=c(2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)) 

df1<-data.frame(I = c(26, 26,26,26,26,86,86,86,86,86, 86, 86, 86, 126,126,126,126,126, 126,126),U = c(1,1,1,2,2,1,1,1,1,1,2,2,2,1,1,1,1,2,2,2), 
            V =c(1.13, 1.24,1.3,1.17, 1.66,1.76,1.89, 1.90, 1.95,1.97,2.13, 2.24,2.3,2.17, 2.66,2.76,2.89, 2.90, 2.95,2.97), type=c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5)) 

main <- rbind(df,df1) 
main$type <- as.factor(main$type)
main$I <- as.factor(main$I)
main$U <- as.factor(main$U)

main <- transform(main, type = revalue(type,c("2"="type2", "5"="type5")))
main <- transform(main, U = revalue(U,c("1"="M", "2"="F")))
main <- transform(main, I = revalue(I,c("25"="item25", "85"="item85", "125"="item125", "26"="item26", "86"="item86", "126"="item126")))

grp_keys <- unique(as.matrix(main[, c("U", "I")]))
grp_inds <- 1:nrow(grp_keys)

main$grps <- apply(main, 1, function(x) {
  grp_inds[colSums(as.character(x[c("U", "I")]) == t(grp_keys)) == length(c("U", "I"))]
})

main$I_type <- interaction(main$I,main$grps) 
main$I_type <- droplevels(main$I_type)


ggplot(aes(y = V, x = I_type), data = main) + 
  geom_boxplot(outlier.colour = NA, aes(color = type), size = 0.4, 
           position = 'identity', width = 0.3) + 
  scale_x_discrete(labels = sub("\\..*$", "", levels(main$I_type))) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

1 个答案:

答案 0 :(得分:2)

这是一种使用I作为x轴并按grps分组的方法,以便为每个组分别获得箱形图。

ggplot(aes(y = V, x = I, group = grps), data = main) + 
  geom_boxplot(outlier.colour = NA, aes(color = type), size = 0.4, 
               position = 'identity', width = 0.3) + 
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

enter image description here