r - 如何完美对齐数量不等的图 (ggplot2,gridExtra)

标签 r ggplot2 gridextra

我想完美地对齐这些图:

unaligned plots

这是R代码:

library(tidyverse)
library(gridExtra)
groupes <- tribble(~type, ~group, ~prof, ~var,
                   1,1,1,12,
                   1,1,2,-24,
                   1,2,1,-11,
                   1,2,2,7,
                   2,1,1,10,
                   2,1,2,5,
                   2,2,1,-25,
                   2,2,2,2,
                   2,3,1,10,
                   2,3,2,3,
                   3,1,1,10,
                   3,1,2,-5,
                   3,2,1,25,
                   3,2,2,2,
                   3,3,1,-10,
                   3,3,2,3,
                   3,4,1,25,
                   3,4,2,-18)


hlay <- rbind(c(1,2,3),
              c(1,2,3),
              c(NA,2,3),
              c(NA,NA,3))

p1 <-  groupes %>% filter(type==1) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
  coord_cartesian(ylim=c(-25,25)) +
  labs(title="type 1",x="",y="")
p2 <-  groupes %>% filter(type==2) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
  coord_cartesian(ylim=c(-25,25)) +
  labs(title="type 2",x="",y="")
p3 <-  groupes %>% filter(type==3) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
  coord_cartesian(ylim=c(-25,25)) +
  labs(title="type 3",x="",y="")
grid.arrange(p1,p2,p3, layout_matrix=hlay)

我可能会通过添加 heights=c(1.3,1,1,1) 成功地产生更好的对齐。进入 grid.arrange但这不是一个完美的解决方案。另一种解决方案是不考虑标签占用的空间,但我不知道该怎么做。

最佳答案

如果您可以设置绝对面板大小(并相应地调整设备大小),则可能更易于管理。

justify <- function(x, hjust="center", vjust="center"){
  w <- sum(x$widths)
  h <- sum(x$heights)
  xj <- switch(hjust,
               center = 0.5,
               left = 0.5*w,
               right=unit(1,"npc") - 0.5*w)
  yj <- switch(vjust,
               center = 0.5,
               bottom = 0.5*h,
               top=unit(1,"npc") - 0.5*h)
  x$vp <- viewport(x=xj, y=yj)
  return(x)
}

library(grid)
gl <- lapply(list(p1,p2,p3),egg::set_panel_size, height=unit(1,"in"))
gl <- lapply(gl, justify, vjust="top")
gridExtra::grid.arrange(grobs=gl, nrow=1)

enter image description here

关于r - 如何完美对齐数量不等的图 (ggplot2,gridExtra),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206866/

相关文章:

r - R 中所有列的 1 天滞后、3 天平均滞后和 7 天平均滞后

r - ggplot2 中每个主题具有不同颜色的意大利面条图

r - geom_map "map_id"函数如何工作?

r - 基于 R 中的多个范围获取数据框中的行

r - 在 R 中使用多核计算 SVD

r - 编写具有不同数量输入文件的 R 函数

r - ggplot双反转y轴和geom_hline截距计算

R: gridExtra - 如何将摘要绘制为表格?

r - 如何在 gtable 内部使用解析并保留尾随零