2

这是一个例子:

library(ggplot2)
set.seed(123)
df<-data.frame(sid=letters[1:8], 
               groups=rep(1:4, each=2), 
               blp=abs(rnorm(8, 120, 5)),
               bmi=abs(rnorm(8, 25, 5)),
               gender=rep(c("F", "M"), each=4))

ggplot(df, aes(bmi, blp))+
    geom_point(size=2)+
facet_grid(sid~groups)

我想要的是sid按他们的性别着色。理想的数字是: 在此处输入图像描述

4

3 回答 3

4

数据

library(ggplot2)
    set.seed(123)
    df<-data.frame(sid=letters[1:8], 
                   groups=rep(1:4, each=2), 
                   blp=abs(rnorm(8, 120, 5)),
                   bmi=abs(rnorm(8, 25, 5)),
                   gender=rep(c("F", "M"), each=4))

方法一

ggplot(df, aes(bmi, blp, color = gender))+
    geom_point(size=2)+
    facet_grid(sid~groups)

在此处输入图像描述

编辑:评论中澄清后的方法2

ggplot(df, aes(bmi, blp, color = gender))+
    geom_point(size=2)+
facet_grid(sid~groups)+
    geom_rect(data=subset(df, gender == "F"), 
              aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf), 
              fill="red", alpha=0.2)+
    geom_rect(data=subset(df, gender == "M"), 
              aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf), 
              fill="blue", alpha=0.2)

一个更简单的解决方案是+ geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf, fill = gender), alpha=0.2)代替两个geom_rect()s。

在此处输入图像描述

警告:正如其他人指出的那样,有一些方法可以制作你的情节风格,但这些方法非常混乱。上述解决方案简单明了,但显然只能填充包含数据的方面。

于 2018-10-05T14:46:52.550 回答
3

您可以将 ggplot 转换为 grob,并在那里进行更改:

# convert to grob
gp <- ggplotGrob(p) # where p is the original ggplot object

# assign the first 4 right-side facet strips with blue fill
for(i in 1:4){
  grob.i <- grep("strip-r", gp$layout$name)[i]
  gp$grobs[[grob.i]]$grobs[[1]]$children[[1]]$gp$fill <- "blue"
}
# assign the next 4 right-side facet strips with red fill
for(i in 5:8){
  grob.i <- grep("strip-r", gp$layout$name)[i]
  gp$grobs[[grob.i]]$grobs[[1]]$children[[1]]$gp$fill <- "red"
}

grid::grid.draw(gp)

阴谋

于 2018-10-05T15:17:11.547 回答
1

不幸的是,这是需要通过解决方法来完成的事情。虽然这不是很困难,但您需要手动设置颜色。

library(ggplot2)
library(grid)
set.seed(123)
df<-data.frame(sid=letters[1:8], 
               groups=rep(1:4, each=2), 
               blp=abs(rnorm(8, 120, 5)),
               bmi=abs(rnorm(8, 25, 5)),
               gender=rep(c("F", "M"), each=4))

p <- ggplot(df, aes(bmi, blp))+
  geom_point(size=2)+
  facet_grid(sid~groups)
g <- ggplot_gtable(ggplot_build(p))
strip_right <- which(grepl('strip-r', g$layout$name))
fills <- c("blue","blue","blue","blue","red","red","red","red")
k <- 1
for (i in strip_right) {
  j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
  g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- fills[k]
  k <- k+1
}
grid.draw(g)

于 2018-10-05T15:21:14.673 回答