Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 move facet layout

Tags:

r

ggplot2

facet

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?

like image 781
sjfox Avatar asked May 02 '16 19:05

sjfox


1 Answers

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

like image 66
baptiste Avatar answered Oct 31 '22 15:10

baptiste