簡體   English   中英

如何在ggplot2中按組為facet_grid着色?

[英]How to color facet_grid by group in 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)

我想要的是根據性別對sid進行着色。 理想的數字是: 在此處輸入圖片說明

數據

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))

方法1

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()

在此處輸入圖片說明

警告:正如其他人指出的那樣,有很多方法可以使您的情節風格化,但是這些方法很混亂。 上述解決方案既簡單又干凈,但是顯然只能填充包含數據的構面。

您可以將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)

情節

不幸的是,這是需要解決的事情。 雖然這不是超級困難,但是您需要手動設置顏色。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM