首页 > 解决方案 > 如何结合使用 igraph 生成的图形和通过 cowplot::plot_grid 使用 ggplot2 制作的绘图

问题描述

最初,我无法完全绘制它,这意味着我找不到捕获绘图对象并将其提供给cowplot::plot_grid. 现在,我找到了一种解决方法,可以将图形图的图像保存为 png 并使用cowplot::draw_image. 有没有更简单的方法来做到这一点?此外,很难设置 png 的参数以具有良好的分辨率和大小并避免边缘修剪。我还需要对绘图进行一些调整,例如,应该可以使用具有精确连接权重值的自环和定向箭头。

在下文中,我获得了两个选项及其各自的结果。

library(ggplot2); library(cowplot); library(igraph)
graph_1 <- sample_gnm(10, 25, directed = T, loops = T)
gg_test <- ggplot(data.frame("a" = seq(1, 5, length.out = 10), "b" = runif(10)), aes(x=a, y=b)) + geom_point() + theme_classic()

选项 1 - 直接

# option 1 - empty graph
cowplot::plot_grid(plot(graph_1), gg_test)

选择1

选项 2 - 归档

# option 2 - working but horrible code and difficult setting of the resolution/size (r-base not the best)
png("to_delete_for_import.png", res = 150, height = 800, width = 1100)
plot(graph_1, edge.label = LETTERS[1:10], vertex.color = RColorBrewer::brewer.pal(10, "Spectral"))
dev.off()
graph_1_cwpl <- ggdraw() + draw_image("to_delete_for_import.png")
file.remove("to_delete_for_import.png")
cowplot::plot_grid(graph_1_cwpl, gg_test)

选择2

标签: rggplot2igraphcowplot

解决方案


我最近遇到了同样的问题,发现以下解决方案很有帮助。第一种方法类似于用户@January 已经评论过的:

library(ggplotify) 
E(graph_1)$label <- ""
plot_grid(base2grob(~plot(graph_1)),
          gg_test)

在此处输入图像描述

这是使用的第二种方法ggraph

library(ggraph)
ggtest2 <- ggraph(graph_1) +
          geom_node_point() +
          geom_edge_link() +
          theme_classic()

plot_grid(ggtest2, gg_test)

在此处输入图像描述


推荐阅读