Search code examples
rggplot2facet

ggplot2 move facet layout


I would like to manually (or automatically) alter the panel layout of a faceted graph of a ggplot2 graphic in R. I have seen solutions to annotations and reordering of Facets, but not this specific question. Here is a reproducible example:

library(ggplot2)
plot <- ggplot(diamonds, aes(carat, price)) + facet_wrap(~cut) + geom_point()

If I look at the plot now, you see that the blank facet is allocated in the bottom right corner of the plot grid.

enter image description here All I want to do is make the blank plot location be in the top left corner instead, but still plot all the other plots (just move the blank plot location).

I've tried looking at ggplot_build() as such:

plot_build <- ggplot_build(plot)
plot_build$panel$layout

but I can't figure out how to actually move the blank plot location to the correct row and column. Does anyone have any ideas?


Solution

  • You could move panels in the gtable,

    library(grid)
    library(ggplot2)
    
    p <- ggplot(diamonds, aes(carat, price)) + 
          facet_wrap(~cut) + geom_point()
    
    g <- ggplotGrob(p)
    
    gl <- g$layout
    idcol <- gl$r == (ncol(g)-2)
    g$layout[idcol & gl$b < 5, c("t", "b")] <- gl[idcol & gl$b < 5, c("t", "b")] + 4
    grid.newpage()
    grid.draw(g)
    

    enter image description here