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

标签 r ggplot2 facet

我正在尝试重新排序 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)

enter image description here

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

我的问题是:

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

谢谢。

最佳答案

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

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)

enter image description here

关于R ggplot2facet_wrap重新排序子图并为每个ID标签设置不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859487/

相关文章:

r - 使用 ggplot 绘制气泡图的每组平均值

r - 如何更改方面标签?

R找不到函数 "%dopar%"

r - 无法运行任何 ggsubplot 示例

r - XPath在R中的br标签之后提取文本

r - 从 ggplot 中提取一个点并绘制它

java - 如何指定多个 Spring Data Solr Facet 字段?

lucene - Lucene 3.5中分组和构面之间有什么区别

r - 使用 na.action=na.pass 聚合给出了意想不到的答案

r - 在 R 中使用 Stargazer 将 csv 直接导出到 Excel