ggplot2: facet_wrap strip color based on variable in data set

前端 未结 4 1849
余生分开走
余生分开走 2020-11-28 03:05

Is there a way to fill the strips of facets created with facet_wrap based on a variable supplied with the data frame?

Example data:

MYdata <- data.f

4条回答
  •  余生分开走
    2020-11-28 03:51

    I would love to know how to do that, it is a great idea. One idea is to generate each chart independently with a different color as you do and then use something like multiplot or viewports to show then side by side - it will require a bit more work.

    if you want to extract the legend, which you will need for this approach - here is some code from Hadley that I found a while back

    g_legend<-function(a.gplot){
      tmp <- ggplot_gtable(ggplot_build(a.gplot))
      leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
      legend <- tmp$grobs[[leg]]
      return(legend)}
    

    see how it is extracted it from chart p, and then I took it out of the plot legend <- g_legend(p) lwidth <- sum(legend$width) #if you want to define the viewport based on this p <- p + theme(legend.position="none")

    then you eventually draw it

    grid.newpage()
    vp <- viewport(width = 1, height = 1)
    #print(p, vp = vp)
    
    submain <- viewport(width = 0.9, height = 0.9, x = 0.5, y = 1,just=c("center","top"))
    print(p, vp = submain)
    sublegend <- viewport(width = 0.5, height = 0.2, x = 0.5, y = 0.0,just=c("center","bottom"))
    print(arrangeGrob(legend), vp = sublegend)
    

    Good luck

提交回复
热议问题