代码之家  ›  专栏  ›  技术社区  ›  Alexey Shiklomanov

ggplot'facet\u grid'标签切断

  •  9
  • Alexey Shiklomanov  · 技术社区  · 7 年前

    在里面 ggplot ,使用时 facet_grid(..., space = "free_y") 一组中的点数很小,刻面标题就被切断了。

    例如

    library(tidyverse)
    
    d <- tibble(
      x = factor(1:40),
      y = rnorm(40),
      g = c(rep("GROUP 1", 39), "GROUP 2")
    )
    
    ggplot(d) +
      aes(x = x, y = y) +
      geom_col() +
      facet_grid(g ~ ., scales = "free_y", space = "free_y") +
      coord_flip() +
      theme(
        strip.text.y = element_text(angle = 0, size = rel(4))
      )
    

    ggplot with facet strip text cut-off

    有没有办法得到 GROUP 2 文本是否不在镶嵌面网格边距处截断?我知道我可以拉伸情节,但这并不是一个令人满意的解决方案——毕竟,面之间存在着所有的空白空间!有没有一种方法可以让标签直接渗入其中?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Z.Lin    7 年前

    如果将打印转换为grob,则可以关闭剪裁:

    pg <- ggplotGrob(pp)
    
    for(i in which(grepl("strip-r", pg$layout$name))){
      pg$grobs[[i]]$layout$clip <- "off"
    }
    
    grid::grid.draw(pg)
    

    plot

    上面关闭了右侧所有镶嵌条标签的剪裁,这对于使用不同的数据集进行打印非常灵活。

    或者,如果您确切知道要关闭哪些功能,也可以检查grob&手动指定的值 i :

    > pg
    TableGrob (12 x 8) "layout": 18 grobs
        z         cells       name                                   grob
    1   0 ( 1-12, 1- 8) background        rect[plot.background..rect.908]
    2   1 ( 6- 6, 4- 4)  panel-1-1               gTree[panel-1.gTree.839]
    3   1 ( 8- 8, 4- 4)  panel-1-2               gTree[panel-2.gTree.852]
    4   3 ( 5- 5, 4- 4)   axis-t-1                         zeroGrob[NULL]
    5   3 ( 9- 9, 4- 4)   axis-b-1    absoluteGrob[GRID.absoluteGrob.865]
    6   3 ( 6- 6, 3- 3)   axis-l-1    absoluteGrob[GRID.absoluteGrob.872]
    7   3 ( 8- 8, 3- 3)   axis-l-2    absoluteGrob[GRID.absoluteGrob.879]
    8   3 ( 6- 6, 6- 6)   axis-r-1                         zeroGrob[NULL]
    9   3 ( 8- 8, 6- 6)   axis-r-2                         zeroGrob[NULL]
    10  2 ( 6- 6, 5- 5)  strip-r-1                          gtable[strip]
    11  2 ( 8- 8, 5- 5)  strip-r-2                          gtable[strip]
    12  4 ( 4- 4, 4- 4)     xlab-t                         zeroGrob[NULL]
    13  5 (10-10, 4- 4)     xlab-b titleGrob[axis.title.x..titleGrob.858]
    14  6 ( 6- 8, 2- 2)     ylab-l titleGrob[axis.title.y..titleGrob.855]
    15  7 ( 6- 8, 7- 7)     ylab-r                         zeroGrob[NULL]
    16  8 ( 3- 3, 4- 4)   subtitle  zeroGrob[plot.subtitle..zeroGrob.905]
    17  9 ( 2- 2, 4- 4)      title     zeroGrob[plot.title..zeroGrob.904]
    18 10 (11-11, 4- 4)    caption   zeroGrob[plot.caption..zeroGrob.906]
    
    # note that in this case, we actually only need to turn off clipping for
    # strip-r-2, the 11th grob.
    
    pg$grobs[[11]]$layout$clip <- "off"