类似的问题已经被问过很多次了,例如这里和这里。但是,到目前为止我看到的所有其他答案并没有真正解决我的问题。
我试图在同一个窗口中绘制多个不同大小的图。我正在处理tidygraph
对象并ggraph
用于创建绘图。我尝试使用gridExtra
and cowplots
,但是,我似乎无法让它们按我的意愿工作。
例如,首先我创建一些数据,将它们转换为tidygraph
对象并将它们放在一个列表中,如下所示:
library(tidygraph)
library(ggraph)
library(cowplot)
library(gridExtra)
# create some data
edges <- data.frame(from = c(1,1), to = c(2,3))
edges1 <- data.frame(from = c(1, 2, 2, 1, 5, 5), to = c(2, 3, 4, 5, 6, 7))
edges2 <- data.frame(from = c(1,2,2,1), to = c(2,3,4,5))
tg <- tbl_graph(edges = edges)
tg_1 <- tbl_graph(edges = edges1)
tg_2 <- tbl_graph(edges = edges2)
myList <- list(tg, tg_1, tg_2)
然后我创建一个绘图函数ggraph
并创建一个绘图列表,如下所示:
# create plotting function
plotFun <- function(List, n) {
plot <- ggraph(List, "partition") +
geom_node_tile(aes(fill = "red"), size = 0.25) +
scale_y_reverse() +
theme_void() +
theme(legend.position = "none")
}
# create list of all plots
allPlots <- lapply(myList, plotFun, n = length(myList))
因此,在我的示例中,我有 3 个不同的图......我试图在同一个窗口中绘制所有 3 个图,但每个图的大小不同。我想要的输出如下图所示...
我试图做的是有一个情节“全尺寸”,第二个情节,第一个情节的1/2,第三个情节的第一个情节的1/4。这看起来像:
注意:图像是在 Photoshop 中制作的,所以我上面提到的比例在图像中并不准确。
我在尝试的解决方案中的想法是使用gridExtra
or cowplot
...
尝试的解决方案
# ATTEMPED COWPLOT SOLUTION
plot_grid(plotlist = allPlots, align = "hv", ncol = 2, rel_heights = c(1, 1/2, 1/4), rel_widths = c(1, 1/2, 1/4))
# ATTEMPED GRIDEXTRA SOLUTION
grid.arrange(
grobs = allPlots,
widths = c(1, 0.5, 1/4),
heights = c(1, 0.5, 1/4),
layout_matrix = rbind(c(1, 2, 3))
)