R ggplot2 facet_wrap 重新排序子图并为每个 ID 标签设置不同的颜色

R ggplot2 facet_wrap reordering subfigure and set different colors for each ID label

我正在尝试重新排列 ggplot 中的子图顺序 facet_wrap 并为其子图文本标签指定特定颜色。

这是我的数据集:

  ID <- rep(c('ABC123','DEF456','GHI789','JKL012'),each = 10)
  Vref <- c((runif(10,1,2)),(runif(10,3,5)),(runif(10,6,9)),(runif(10,0,2)))
  Time <- rep(c(1:10),4)
  df <- data.frame(ID,Vref,Time)
  ggplot(df) + geom_point(aes(x=Time, y=Vref)) + facet_wrap(~ID, nrow = 2)

现在子图的顺序是ABC123 --> DEF456 --> GHI789 --> JKL012。 所有文本标签均为黑色。

我的问题是:

如何将顺序改为GHI789 --> ABC123 --> JKL012 --> DEF456? 如何指定红绿黄蓝的颜色?

谢谢。

我建议查看这些已回答的问题:

How to change the order of facet labels in ggplot (custom facet wrap labels)

facet label font size

排序可以通过一个因素来实现,facet strip的着色是通过一个主题来完成的,如下(颜色为橙色):

ggplot(df) + geom_point(aes(x=Time, y=Vref)) + facet_wrap(~ID, nrow = 2) +
theme(strip.text.x = element_text(size = 8, colour = "orange"))

对于单独为每个面条着色,我不知道有什么干净的方法可以做到这一点。我发现了一个类似的问题,它讨论了使用自定义图形对象(grobs)来修改条带的背景颜色。这是 link:

ggplot2: facet_wrap strip color based on variable in data set

为条带文本指定颜色的一种方法是使用 grid 包中的编辑功能。通常 grid.ls() 和其他编辑功能只能看到一个 grob,但是 grid.force() 使 ggplot 中的所有 grob 对网格的编辑功能可见。

library(grid)
library(ggplot2)

ID <- rep(c('ABC123','DEF456','GHI789','JKL012'),each = 10)
Vref <- c((runif(10,1,2)),(runif(10,3,5)),(runif(10,6,9)),(runif(10,0,2)))
Time <- rep(c(1:10),4)
df <- data.frame(ID,Vref,Time)

# Change order of strip texts
df$ID = factor(df$ID, levels = c("GHI789", "ABC123", "JKL012", "DEF456"))

p = ggplot(df) + geom_point(aes(x=Time, y=Vref)) + facet_wrap(~ID, nrow = 2) 

gp <- ggplotGrob(p)  # Get ggplot grob

# Get the names of the grobs
# grid.force makes all the grobs visible to grid's editing functions
names.grobs <- grid.ls(grid.force(gp))$name

# Inspect the list. The required grobs' names begin with GRID.text,
# but so do other text grobs - to do with the axes.
# Therefore, in the edit, use gPath to limit the editing to GRID.text in the strip,
# and not the GRID.text in the axes.

strip.text <- names.grobs[which(grepl("GRID.text", names.grobs))]

# Set up the colours
colour <- c("yellow", "blue", "red", "green")

# The edit
for(i in 1:4) gp = editGrob(grid.force(gp), 
                     gPath("GRID.titleGrob", strip.text[i]), 
                     grep = TRUE,    
                     gp = gpar(col = colour[i]))

# Draw it 
grid.newpage()
grid.draw(gp)