我正在尝试重新排序 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 ? 如何指定红、绿、黄、蓝颜色?
谢谢。
最佳答案
指定 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)
关于R ggplot2facet_wrap重新排序子图并为每个ID标签设置不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859487/