【问题标题】:How to combine a graph generated with igraph and a plot made with ggplot2 by means of cowplot::plot_grid如何结合使用 igraph 生成的图形和通过 cowplot::plot_grid 使用 ggplot2 制作的绘图
【发布时间】:2019-11-25 05:24:08
【问题描述】:

最初,我无法完全绘制它,这意味着我找不到捕获绘图对象并将其提供给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)

选项 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)

【问题讨论】:

  • 这不是很有效,但也许你可以找到一种方法让它变得更好:在你制作图表之后用户x &lt;- recordPlot(),然后plot_grid(x, gg_test)。但是,恐怕结果并不令人印象深刻。你试过ggnet2吗?
  • recordPlot() 有效,但它需要 gridGraphics 包,并且(在我的情况下)在边缘添加 NA 标签。质量方面还是不错的!我不知道ggnet2我害怕。我会检查一下;)
  • 是的,NA 加上混乱的节点和箭头样式,不确定您是否可以轻松处理。
  • 如果 gridGraphics 弄乱了你的绘图,请在 github 上提出问题。目标是忠实地捕捉所有基本图形,但仍有一些极端情况需要修复。
  • NAs 的问题最近在 gridGraphics 中得到修复:github.com/pmur002/gridgraphics/issues/14

标签: r ggplot2 igraph cowplot


【解决方案1】:

我最近遇到了同样的问题,发现以下解决方案很有帮助。第一种方法类似于用户@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)

【讨论】:

  • 这不是我要找的,因为它仍然需要手动使标签静音,我希望有另一种方法,同时考虑到网络绘图的工具数量。此外,我不知道在更复杂的图形的情况下 grob 会如何表现。第二个也是一样,但如果我能把它的美感提高到我需要的程度,我会看看。
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 2017-09-27
  • 2016-03-20
  • 2020-08-02
  • 1970-01-01
  • 2018-08-02
相关资源
最近更新 更多