我想画一个包含几个次要情节的图形.这些次要情节中的一些我想成为表格.然而,我一直面临的问题是,我不能让桌子彼此对齐.我希望每个表格都对齐到每个小情节的"顶部".

我已经try 使用以下代码:

## Reprex 
library(ggplot2)
library(gridExtra)
library(cowplot)
library(ggpubr)

#Data

dataA <- data.frame("A" = rep("A", 3),"B" = rep("B", 3),"C" = rep("C", 3))
dataB <- data.frame("A" = rep("A", 4),"B" = rep("B", 4),"C" = rep("C", 4))
dataC <- data.frame("A" = rep("A", 5),"B" = rep("B", 5),"C" = rep("C", 5))
dataD <- data.frame("A" = rep("A", 3),"B" = rep("B", 3),"C" = rep("C", 3))

#Convert to Grob


fig_subplotA <- arrangeGrob(tableGrob(dataA, rows = NULL),
                     tableGrob(dataB, rows = NULL), ncol = 2)

fig_subplotB <- arrangeGrob(tableGrob(dataC, rows = NULL), 
                     tableGrob(dataD, rows = NULL), ncol = 2)


# Make final plot 

g <- list(fig_subplotA, fig_subplotB)

p.final <- arrangeGrob(grobs=g, ncol = 2)

p <- as_ggplot(p.final)+
        draw_plot_label(label = c("a", "b"), x = c(0, 0.5))
p

#Export 

ggsave(filename = "FigureExample.png", p, width = 4, height = 3)

输出如下所示:

Output

我想要一些类似的东西:

Goal

非常感谢您的任何意见!

推荐答案

就我所知,tableGrob没有垂直对齐方法,因此这需要根据Grob Heights计算正确的视区位置,这有点冗长,最好用一个函数来包装:

justify <- function(x, just = 1) {
  height <- as.numeric(grid::convertHeight(sum(x$heights), 'npc'))
  x$vp <- grid::viewport(y = just + height * (0.5 - just))
  x
}

这允许:

A <- tableGrob(dataA, rows = NULL)
B <- tableGrob(dataB, rows = NULL) 
subplotA <- arrangeGrob(justify(A), justify(B), ncol = 2)

C <- tableGrob(dataC, rows = NULL)
D <- tableGrob(dataD, rows = NULL) 
subplotB <- arrangeGrob(justify(C), justify(D), ncol = 2)

arrangeGrob(grobs = list(subplotA, subplotB), ncol = 2) |>
  as_ggplot() +
  draw_plot_label(label = c("a", "b"), x = c(0, 0.5))

enter image description here

R相关问答推荐

管道末端运行功能

R Markdown中的交叉引用表

向gggplot 2中的数据和轴标签添加大写和星号

如何求解arg必须为NULL或deSolve包的ode函数中的字符向量错误

如何将dygraph调用到R Markdown作为一个shiny 的react 对象的参数?

有效识别长载体中的高/低命中

绘制采样开始和采样结束之间的事件

以NA为通配符的R中的FULL_JOIN以匹配其他数据中的任何值.Frame

从非重叠(非滚动)周期中的最新数据向后开窗并在周期内计数

如何将使用rhandsontable呈现的表值格式化为百分比,同时保留并显示完整的小数精度?

在列表中排列R数据框中的列顺序

扩展R中包含列表的数据框

将具有坐标列表列的三角形转换为多个多边形

如果条件匹配,则使用Mariate粘贴列名

如何在R中创建条形图,使条形图在y轴上围绕0.5而不是0构建条形图?

如何在条形图中的x和填充变量中包含多个响应变量?

使用函数从R中的列中删除标高

如何在刻面和翻转堆叠条形图中对齐geom_text()

如何在矩阵图中按标准对数据进行分组以绘制矩阵

使用dplyr删除具有条件的行