在 R 中使用 grid.arrange 放置行和列标题 [英] Put row and column titles using grid.arrange in R

查看:65
本文介绍了在 R 中使用 grid.arrange 放置行和列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ggplots 的数据:

The data for the ggplots:

set.seed(0)

library(ggplot2)
library(gridExtra)

c <- list()

for (k in 1:9) c[[k]] <- ggplot(data.frame(x=1:10,y=rnorm(10)),aes(x=x,y=y))+geom_line()

grid.arrange (c[[1]],c[[2]],c[[3]],c[[4]],c[[5]]
,c[[6]],c[[7]],c[[8]],c[[9]],ncol=3, nrow=3, widths = c(4,4,4) ,heights = c(4,4,4))

我想要每一行和每一列的标题.

I want titles for each row and each column.

输出的形状将是这样的:

The shape of the output would be something like this:

          CTitle 1 CTitle 2 CTitle 3
RTitle1   plot1     plot2   plot3
RTitle2   plot4     plot5   plot6
RTitle3   plot7     plot8   plot9

推荐答案

您可以对每一列/行使用嵌套的arrangeGrob 调用,设置 top 和 left 参数.像这样:

You can use nested arrangeGrob calls for each column/row, setting the top and left argument. Something like this:

grid.arrange (arrangeGrob(c[[1]], top="CTitle1", left="RTitle1"),arrangeGrob(c[[2]],top="CTitle2"),arrangeGro‌​b(c[[3]],top="CTittl‌​e3"),arrangeGrob(c[[‌​4]], left="RTitle2"),c[[5]],c[[6]],arrangeGrob(c[[7]],left="RTitl‌​e3"),c[[8]],c[[9]],n‌​col=3, nrow=3, widths = c(4,4,4) ,heights = c(4,4,4))

感谢@eipi10,以下是简化流程的代码

Below is a code to streamline the process thanks to @eipi10

# Create list of plots
set.seed(0)
pl = lapply(1:9, function(i) {
  p = ggplot(data.frame(x=1:10,y=rnorm(10)),aes(x, y)) + 
              geom_line()
})

# Create row and column titles
col.titles = paste("C_Title", 1:3)
row.titles = paste("R_Title", 4:6)

# Add row titles
pl[1:3] = lapply(1:3, function(i) arrangeGrob(pl[[i]], left=row.titles[i]))

# Add column titles and lay out plots
grid.arrange(grobs=lapply(c(1,4,7), function(i) {
  arrangeGrob(grobs=pl[i:(i+2)], top=col.titles[i/3 + 1], ncol=1)
}), ncol=3)

这篇关于在 R 中使用 grid.arrange 放置行和列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆