基本上,我想为grid.arrange()图添加标题和副标题。
我有plot_list
,它是15个ggplots的列表,
tg <- textGrob('Title', gp = gpar(fontsize = 13, fontface = 'bold'))
sg <- textGrob('Subtitle', gp = gpar(fontsize = 10))
但是这不起作用。我没有任何错误,但是tg
和sg
没有出现在绘图中。
grid.arrange(tg, sg, grobs = plot_list, ncol = 3)
说实话,我不是gridExtra
和grid
的专家,所以任何建议都将不胜感激
跟随changing multiple line title in multiplot ggplot2 using grid.arrange,我可以通过创建两个网格来完成您要的操作,首先创建仅两个绘图,然后创建第二个带有标题,副标题和第一个网格的网格。使用合成的plot_list
:
df <- data.frame(v1 = rnorm(1000))
plot_list <- list()
for (i in 1:15) {
df[,ncol(df)+1] <- rnorm(1000)
names(df)[ncol(df)] <- paste0("V_",as.character(i))
local({
i <- i
plot_list[[i]] <<- ggplot(df) + geom_point(aes_string(x = "v1", y = paste0("V_",as.character(i))))
})
}
tg <- textGrob('Title', gp = gpar(fontsize = 13, fontface = 'bold'))
sg <- textGrob('Subtitle', gp = gpar(fontsize = 10))
margin <- unit(0.5, "line")
grided <- gridExtra::grid.arrange(grobs = plot_list, ncol = 3)
gridExtra::grid.arrange(tg, sg, grided,
heights = unit.c(grobHeight(tg) + 1.2*margin,
grobHeight(sg) + margin,
unit(1,"null")))
希望这会有所帮助!
您需要将tg,sg和您的图合并到一个列表中。我将指定一个布局矩阵,它给您更多控制权,并使用grid.arrange:
进行绘制首先,我们有tg,sg,我用mtcars制作了一个plot_list为3。
library(ggplot2)
library(gridExtra)
library(grid)
tg <- textGrob('Title', gp = gpar(fontsize = 13, fontface = 'bold'))
sg <- textGrob('Subtitle', gp = gpar(fontsize = 10))
plot_list <- lapply(c("drat","wt","qsec"),function(i){
ggplot(mtcars,aes_string("mpg",i))+geom_point()
})
我们将您的地块合并到一个列表中:
g = c(list(tg),list(sg),plot_list)
所以现在tg是第一个元素,sg是第二个元素,您的绘图是3-5。我们指定布局:
N = length(plot_list)
laym = rbind(rep(1,N),rep(2,N),(3:(N+2)))
laym
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 4 5
此矩阵将具有第一个(tg),1占据第一行,sg占据第二行,而您的绘图占据第三行。如果您有其他类型的安排或列表,则可以相应地进行更改。
现在绘制,并使用heights = ...指定相对高度
grid.arrange(grobs=g,layout_matrix=laym,heights=c(1,1,10))
top
参数可以采用任何粗略形式,但需要知道其高度才能得到正确的空间,
library(grid)
library(gridExtra)
lg <- replicate(12, ggplot2::ggplot(), simplify = FALSE)
tg <- textGrob('Title', gp = gpar(fontsize = 50, fontface = 'bold'))
sg <- textGrob('Subtitle', gp = gpar(fontsize = 10))
lt <- list(tg, sg)
heights <- do.call(unit.c, lapply(lt, function(.g) 1.5*grobHeight(.g)))
titles <- gtable::gtable_matrix('title',
grobs = matrix(lt, ncol=1),
widths = unit(1,'npc'),
heights = heights)
grobHeight.gtable <- function(g) sum(g$heights)
grid.arrange(grobs = lg, top = titles)