ggplot2 move facet layout

末鹿安然 提交于 2020-03-01 03:08:29

问题


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.

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?


回答1:


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)



来源:https://stackoverflow.com/questions/36990532/ggplot2-move-facet-layout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!