Is it possible to switch the side of y-axis breaks and labels on a faceted plot?

前端 未结 3 1010
夕颜
夕颜 2021-01-01 18:59

By default, on a faceted ggplot (facet_grid), the y-axis facet labels are on the right and the y-axis breaks and labels are on the left.

Is it possible to switch the

3条回答
  •  爱一瞬间的悲伤
    2021-01-01 19:11

    I wrote this for my needs. If you use it with switch = "y", you're halfway done.

    You still need to modify it to switch the axis, which may take some more work because the axis and breaks form one column in a gtable, so you'll need to decompose it further.

    switch_facet_strip <- function(p, switch = c("x", "y")) {
    
      require(gtable)
      rbind_gtable <- gtable:::rbind_gtable
      cbind_gtable <- gtable:::cbind_gtable
    
      if ("y" %in% switch)
        p <- p + theme(strip.text.y = element_text(vjust = 0.5, angle = 90))
    
      g <- ggplotGrob(p)
    
    
      gdim <- as.numeric(g$layout[g$layout$name == "background", c("b", "r")])
      tpos <- g$layout[g$layout$name == "strip-top", "b"][1]
      rpos <- g$layout[g$layout$name == "strip-right", "r"][1]
      new_tpos <- g$layout[g$layout$name == "axis-b", "b"][1] + 1
      new_rpos <- g$layout[g$layout$name == "axis-l", "r"][1] - 1
    
      if ("x" %in% switch) {
        g <- rbind_gtable(
               rbind_gtable(
                   gtable_add_rows(
                     rbind_gtable(g[1:tpos-1, ] , g[(tpos+1):(new_tpos-1), ], "first"),
                     unit(5, units = "mm")),
                   g[tpos, ], "first"),
               g[new_tpos:gdim[1], ], "first")
      }
    
      if ("y" %in% switch) {
        g <- cbind_gtable(
               cbind_gtable(
                 gtable_add_cols(
                   cbind_gtable(g[, 1:new_rpos], g[, rpos], "first"),
                   unit(5, units = "mm")),
                 g[, (new_rpos+2):rpos-1], "first"),
               g[, (rpos+1):gdim[2]], "first")
      }
    
      grid.newpage()
      grid.draw(g)
    }
    

    Note: This hack allows me to switch both strips next to their respective axis label. It only makes sense if you are using a theme in which strip have no backgrounds. I think this is the right way to display facet labels because it allows to read the plot like a multiway table. Moreover, the facet labels are next to the axes breaks, which makes it much more obvious what the axes represent. Anyone else thinks this makes sense? I wish it were an option in ggplot.

    The right way to display facet grids

提交回复
热议问题