Reorder columns in boxplots ggplot2
我有这个箱线图,我想重新排列列。我想要 MCAR、MAR、MNAR 而不是 MAR、MCAR、MNAR。传说也是错误的,橙色是ymiss,蓝色是yobs,但我无法改变它。你能帮助我吗?谢谢!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | library(ggplot2) logistic <- function(x) exp(x) / (1 + exp(x)) set.seed(80122) n <- 300 dt <- MASS::mvrnorm(n = n, mu = c(0, 0), Sigma = matrix(c(1, 0.5, 0.5, 1), nrow = 2));dt r2.mcar <- 1 - rbinom(n, 1, 0.5);r2.mcar r2.mar <- 1 - rbinom(n, 1, logistic(dt[, 1]));r2.mar r2.mnar <- 1 - rbinom(n, 1, logistic(dt[, 2]));r2.mnar yobs1<-dt yobs1[r2.mcar==0,2]<-NA;yobs1 yobs2<-dt yobs2[r2.mar==0,2]<-NA;yobs2 yobs3<-dt yobs3[r2.mnar==0,2]<-NA;yobs3 dados<-matrix(cbind(yobs1[,1],yobs2[,1],yobs3[,1],yobs1[,2],yobs2[,2],yobs3[,2]),ncol=1) v<-c(rep("yobs",900),rep("ymiss",900)) m<-c(rep("MCAR",300),rep("MAR",300),rep("MNAR",300)) dados<-data.frame(v,m,dados) names(dados)<-c("y","mecanismo","valores") p <- ggplot(dados, aes(x =valores, y = mecanismo)) + geom_boxplot(aes(fill = y), position = position_dodge(0.9)) + scale_fill_manual(values = c("lightskyblue","lightsalmon")) p + facet_grid(~mecanismo) |
你的一个问题实际上是两个问题:
改变刻面的顺序。
将图例中的特定颜色分配给一个因素。在您的
这是代码和情节:
1 2 3 4 5 6 7 8 9 | # relevel factor for right order of facets dados$mecanismo <- factor(dados$mecanismo, levels=c('MCAR','MAR','MNAR')) p <- ggplot(dados, aes(x =valores, y = mecanismo)) + geom_boxplot(aes(fill = y), position = position_dodge(0.9)) + # set colors with named vector scale_fill_manual(values = c('yobs'="lightskyblue",'ymiss'="lightsalmon")) p + facet_grid(~mecanismo) |
编辑:更改图例键的顺序
经过一些评论,很明显 OP 不仅打算根据
1 2 3 4 5 6 7 8 9 10 | dados$mecanismo <- factor(dados$mecanismo, levels=c('MCAR','MAR','MNAR')) ggplot(dados, aes(x =valores, y = mecanismo)) + geom_boxplot(aes(fill = y), position = position_dodge(0.9)) + # set colors with named vector scale_fill_manual( values = c('yobs'="lightskyblue",'ymiss'="lightsalmon"), breaks = c('yobs', 'ymiss') ) |
添加此代码,它将起作用:
1 2 3 4 5 6 7 | #Reorder var dados$mecanismo <- factor(dados$mecanismo,levels = c("MCAR","MAR","MNAR"),ordered = T) p <- ggplot(dados, aes(x =valores, y = mecanismo)) + geom_boxplot(aes(fill = y), position = position_dodge(0.9)) + scale_fill_manual(values = c("lightsalmon","lightskyblue")) p + facet_grid(~mecanismo) |