Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the format of an individual facet_wrap panel?

Tags:

r

ggplot2

Is it possible to alter the format of an individual facet plot? For example, using the sample code below, can one change the color of the title or background for the cyl=8 plot?

library(ggplot2)
ggplot(mtcars, aes(x=gear)) + 
  geom_bar(aes(y=gear), stat="identity", position="dodge") +
  facet_wrap(~cyl)
like image 675
user338714 Avatar asked Jul 19 '11 16:07

user338714


1 Answers

You can modify the ggplot2 grobs, for instance:

library("ggplot2")
d <- ggplot(mtcars, aes(x=gear)) + 
       geom_bar(aes(y=gear), stat="identity", position="dodge") +
       facet_wrap(~cyl)

grob <- ggplotGrob(d)
strip_bg <- grid.ls(getGrob(grob, "strip.background.rect",
                            grep=TRUE, global=TRUE))$name
panel_bg <- grid.ls(getGrob(grob, "panel.background.rect",
                            grep=TRUE, global=TRUE))$name
strip_text <- grid.ls(getGrob(grob, "strip.text.x",
                              grep=TRUE, global=TRUE))$name
grob <- geditGrob(grob, strip_bg[2], gp=gpar(fill="gray60"))
grob <- geditGrob(grob, panel_bg[2], gp=gpar(fill="darkolivegreen2"))
grob <- geditGrob(grob, strip_text[2], gp=gpar(col="white"))
grid.draw(grob)

geditGrob example

Update: This should work with ggplot2 0.9.3

grob <- ggplotGrob(d)

elem <- grob$grobs$panel2
panel_bg <- grid.ls(getGrob(elem, "panel.background.rect", grep=TRUE))$name
grob$grobs$panel2 <- editGrob(elem, panel_bg, gp=gpar(fill="darkolivegreen"), grep=TRUE)

elem <- grob$grobs$strip_t.1
strip_bg <- grid.ls(getGrob(elem, "strip.background.rect", grep=TRUE))$name
grob$grobs$strip_t.1 <- editGrob(elem, strip_bg, gp=gpar(fill="gray60"), grep=TRUE)

elem <- grob$grobs$strip_t.1
strip_text <- grid.ls(getGrob(elem, "strip.text.x.text", grep=TRUE))$name
grob$grobs$strip_t.1 <- editGrob(elem, strip_text, gp=gpar(col="white"), grep=TRUE)

grid.draw(grob)
like image 161
rcs Avatar answered Sep 19 '22 20:09

rcs