如何在ggplot2中按组对facet_grid着色?

Dav*_*d Z 2 r ggplot2

这是一个例子:

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)
Run Code Online (Sandbox Code Playgroud)

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

Rom*_*man 5

数据

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))
Run Code Online (Sandbox Code Playgroud)

方法一

ggplot(df, aes(bmi, blp, color = gender))+
    geom_point(size=2)+
    facet_grid(sid~groups)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:评论中澄清后的方法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)
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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