Force facet_wrap to fill bottom row (and leave any “gaps” in the top row)

后端 未结 1 2072
梦如初夏
梦如初夏 2020-12-19 09:19

I\'d like to force facet_wrap to fill from the top-left, but in such a way as to always fully fill the bottom row. (That is, from the top-left plus whatever horizontal offs

相关标签:
1条回答
  • 2020-12-19 09:35

    Would this fix suffice?

    library(ggplot2)
    n <- 1000
    df <- data.frame(x = runif(n), y=rnorm(n), label = sample(letters[1:7], 
                     size = n, replace = TRUE), stringsAsFactors=TRUE)
    # following @Didzis' suggestion (with some minor changes)
    df$label.new <- factor(df$label, levels=sort(c(""," ",levels(df$label))))
    p <- ggplot(df, aes(x=x, y=y)) + geom_point() + 
             facet_wrap(~ label.new, ncol=3,drop=FALSE)
    

    enter image description here


    EDIT (from @baptiste):

    Starting from the last solution, it's easier to remove the grobs from the gtable,

    g = ggplotGrob(p)
    ## remove empty panels
    g$grobs[names(g$grobs) %in% c("panel1", "panel2", "strip_t.1", "strip_t.2")] = NULL
    ## remove them from the layout
    g$layout = g$layout[!(g$layout$name %in% c("panel-1", "panel-2", 
                                                    "strip_t-1", "strip_t-2")),]
    ## move axis closer to panel
    g$layout[g$layout$name == "axis_l-1", c("l", "r")] = c(9,9)
    grid.newpage()
    grid.draw(g)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题