【问题标题】:Add both margins to facet_grid but not the combination将两个边距添加到 facet_grid 但不是组合
【发布时间】:2019-05-07 01:26:42
【问题描述】:

我想同时显示右边距和下边距,但不是两者的组合。 facet_grid 可以做到吗?

library(ggplot2)

ggplot(mtcars, aes(x = hp, group = vs)) + 
  geom_density() + 
  facet_grid(am ~ vs, switch = "y", margins = TRUE) 

我试图通过手动向 margin 参数提供因素来修复它,但这无济于事。此外,R 文档对我没有帮助。

目前的结果

期望的结果

【问题讨论】:

    标签: r ggplot2 facet-grid


    【解决方案1】:

    这样的事情对我来说是一个错误,因为我看不到gt 中的条目与最终形式的关系:

    library(ggplot2)
    
    p<-
    ggplot(mtcars, aes(x = hp, group = vs)) + 
        geom_density() + 
        facet_grid(am ~ vs, switch = "y", margins = TRUE)
    
    gt = ggplotGrob(p)
    
    keep <- !grepl("[3br]-3$",gt$layout$name)
    
    gt$layout <- gt$layout[keep,]
    gt$grobs  <- gt$grobs[keep]
    
    plot(gt)
    

    【讨论】:

      【解决方案2】:

      ggplot2 使用固定习语来命名关键情节元素,因此我们可以使用该确定性条件来查找元素:

      library(ggplot2)
      
      ggplot(mtcars, aes(x = hp, group = vs)) + 
        geom_density() + 
        facet_grid(am ~ vs, switch = "y", margins = TRUE) -> gg
      

      将绘图构建为gtable 对象:

      gt <- ggplot_gtable(ggplot_build(gg))
      

      获取表格单元格名称:

      cells <- gt$layout$name
      

      找出哪一个是底角面板和轴:

      apply(
        apply(
          do.call(rbind, strsplit(grep("panel", cells, value=TRUE), "-"))[,2:3],
          2, as.integer), 
        2, max
      ) -> max_col_row
      
      bottom_right_panel <- paste0(c("panel", max_col_row), collapse="-")
      bottom_axis <- sprintf("axis-b-%s", max_col_row[2])
      

      找出哪些不是底角面板:

      paste0(
        grep(sprintf("^%s|%s$", bottom_corner, bottom_axis), cells, value=TRUE, invert = TRUE),
        collapse = "|"
      ) -> not_bottom_corner_panel
      

      只画那些:

      grid::grid.draw(
        gtable::gtable_filter(gt, sprintf("^(%s)$", not_bottom_corner_panel))
      )
      

      【讨论】:

      • 您的解决方案仍然保留 x 轴标签 + 不想要的“右下角”的刻度。梅贝我错了。
      • 谢谢。固定的。它仍然是确定性的 :-) 这也有助于使示例代码不再是扭曲的括号迷宫。
      • 我更新了我的试错句,使其更有意义。
      • “猜一猜”的答案会得到勾选框。是的 SO 正在下降。
      猜你喜欢
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多