如何更改单个facet_wrap面板的格式?

时间:2011-07-19 16:32:11

标签: r ggplot2

是否可以改变单个分面图的格式?例如,使用下面的示例代码,可以更改cyl = 8图表的标题或背景颜色吗?

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

3 个答案:

答案 0 :(得分:17)

您可以修改ggplot2 grobs,例如:

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

更新:这应该适用于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)

答案 1 :(得分:10)

我知道这是一个老问题所以原来的海报可能早已不复存在但我仍然认为值得回答作为未来搜索者的资源。 rcs接受的答案确实有效,但我发现它相当不稳定和黑客。最后,我决定采用更温和但更稳定的方法。使用此方法,您只能更改背景,但这足以满足我的目的,也可能适用于其他人,我的方法是使用geom_rect来重新着色背景,如下所示:

highlights <- data.frame(cyl=c(8))

ggplot() + 
  geom_rect(data=highlights,aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf), fill='red', alpha=0.2) +
  geom_bar(data = mtcars, aes(x=gear), position="dodge", fill = 'black') +
  facet_wrap(~cyl)

Example plot

答案 2 :(得分:3)

这可能会帮助您更接近您想要的东西:

mtcars2 = subset(mtcars, cyl != 8)
   subs = subset(mtcars, cyl == 8)

require(ggplot2)
ggplot(mtcars2, aes(x=gear)) + 
    geom_bar(aes(y=gear, fill = 'black'), stat="identity", position="dodge") +
    geom_bar(data = subs, aes(x = gear), fill = 'blue', binwidth = 1) +
    facet_wrap(~cyl)