R ggplot,更改构面标签文本和背景颜色

时间:2017-01-13 09:56:46

标签: r ggplot2

如何将灰色小平面标签(A和B)更改为带有白色文字的红色背景?

A = data.table(x = 1:4, y = 1:4, z = c('A','A','B','B'))
ggplot(A) + geom_point(aes(x = x, y = y)) + facet_wrap(~z) + theme_bw()

enter image description here

2 个答案:

答案 0 :(得分:37)

你可以这样做:

ggplot(A) +
  geom_point(aes(x = x, y = y)) +
  facet_wrap(~z) +
  theme_bw()+
  theme(strip.background =element_rect(fill="red"))+
  theme(strip.text = element_text(colour = 'white'))

enter image description here

答案 1 :(得分:10)

对于希望更改各个方面标签的其他人,有一个解决方案here

g <- ggplot_gtable(ggplot_build(p))
stripr <- which(grepl('strip-r', g$layout$name))
fills <- c("red","green","blue","yellow")
k <- 1
for (i in stripr) {
  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::grid.draw(g)

enter image description here