虽然这个问题早已得到解答,但我已经封装了一个函数,可以根据以前的答案轻松设置单个图像的背景、边框和文本颜色。我发布它以便对其他人有所帮助。
library(dplyr)
library(ggplot2)
library(RColorBrewer)
这个函数:
modify_facet_appearance <- function(plot = NULL,
strip.background.x.fill = NULL,
strip.background.y.fill = NULL,
strip.background.x.col = NULL,
strip.background.y.col = NULL,
strip.text.x.col = NULL,
strip.text.y.col = NULL){
if(is.null(plot)){stop("A ggplot (gg class) needs to be provided!")}
g <- ggplot_gtable(ggplot_build(plot))
stripy <- which(grepl('strip-r|strip-l', g$layout$name))
stripx <- which(grepl('strip-t|strip-b', g$layout$name))
lx <- c(length(strip.background.x.fill), length(strip.background.x.col), length(strip.text.x.col))
if(!all(lx==length(stripx) | lx==0)){stop("The provided vectors with values need to have the same length and the number of facets in the plot!")}
ly <- c(length(strip.background.y.fill), length(strip.background.y.col), length(strip.text.y.col))
if(!all(ly==length(stripy) | ly==0)){stop("The provided vectors with values need to have the same length and the number of facets in the plot!")}
for (i in seq_along(stripy)){
j1 <- which(grepl('strip.background.y', g$grobs[[stripy[i]]]$grobs[[1]]$childrenOrder))
if(!is.null(strip.background.y.fill[i])){g$grobs[[stripy[i]]]$grobs[[1]]$children[[j1]]$gp$fill <- strip.background.y.fill[i]}
if(!is.null(strip.background.y.col[i])){g$grobs[[stripy[i]]]$grobs[[1]]$children[[j1]]$gp$col <- strip.background.y.col[i]}
j2 <- which(grepl('strip.text.y', g$grobs[[stripy[i]]]$grobs[[1]]$childrenOrder))
if(!is.null(strip.text.y.col[i])){g$grobs[[stripy[i]]]$grobs[[1]]$children[[j2]]$children[[1]]$gp$col <- strip.text.y.col[i]}
}
for (i in seq_along(stripx)){
j1 <- which(grepl('strip.background.x', g$grobs[[stripx[i]]]$grobs[[1]]$childrenOrder))
if(!is.null(strip.background.x.fill[i])){g$grobs[[stripx[i]]]$grobs[[1]]$children[[j1]]$gp$fill <- strip.background.x.fill[i]}
if(!is.null(strip.background.x.col[i])){g$grobs[[stripx[i]]]$grobs[[1]]$children[[j1]]$gp$col <- strip.background.x.col[i]}
j2 <- which(grepl('strip.text.x', g$grobs[[stripx[i]]]$grobs[[1]]$childrenOrder))
if(!is.null(strip.text.x.col[i])){g$grobs[[stripx[i]]]$grobs[[1]]$children[[j2]]$children[[1]]$gp$col <- strip.text.x.col[i]}
}
return(g)
}
示例:
该功能可以从gg对象中进行管道传输,有点类似于添加+主题()
的方式。
pal.y <- brewer.pal(length(unique(mpg$drv))*2, "Paired")
pal.x <- brewer.pal(length(unique(mpg$cyl))*2, "Paired")
p <- {ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(drv ~ cyl) +
ggtitle("How to change colour of font in facet strip?")} %>%
modify_facet_appearance(strip.background.x.fill = pal.x[seq(1, length(pal.x), 2)],
strip.background.x.col = pal.x[seq(2, length(pal.x), 2)],
strip.text.x.col = pal.x[seq(2, length(pal.x), 2)],
strip.background.y.fill = pal.y[seq(1, length(pal.y), 2)],
strip.background.y.col = pal.y[seq(2, length(pal.y), 2)],
strip.text.y.col = pal.y[seq(2, length(pal.y), 2)])
plot(p)
ggthemes::theme_few()
,我通常会尽力记住它。我希望 Hadley 不要听到这个,但我非常讨厌默认的ggplot2
主题,从心底里讨厌。 - utubun