将列表转换为igraph对象以进行绘图的最优雅方法

时间:2018-12-23 19:25:13

标签: r igraph

我是igraph的新手,它似乎是一个非常强大(因此也很复杂)的软件包。

我试图将以下列表转换为igraph对象。

graph <- list(s = c("a", "b"),
              a = c("s", "b", "c", "d"),
              b = c("s", "a", "c", "d"),
              c = c("a", "b", "d", "e", "f"),
              d = c("a", "b", "c", "e", "f"),
              e = c("c", "d", "f", "z"),
              f = c("c", "d", "e", "z"),
              z = c("e", "f"))

weights <- list(s = c(3, 5),
                a = c(3, 1, 10, 11),
                b = c(5, 3, 2, 3),
                c = c(10, 2, 3, 7, 12),
                d = c(15, 7, 2, 11, 2),
                e = c(7, 11, 3, 2),
                f = c(12, 2, 3, 2),
                z = c(2, 2))

解释如下:s是起始节点,它链接到节点ab。对于sa,边缘的权重为3;对于sb,边缘的权重为5。依此类推。

我尝试了igraph中的各种函数,但仅遇到各种错误。将上述内容转换为igraph对象以绘制图形的最优雅,最简单的方法是什么?

1 个答案:

答案 0 :(得分:5)

创建一个边列表,然后从中创建一个图形。分配权重并将其绘制。

set.seed(123)

e <- as.matrix(stack(graph))
g <- graph_from_edgelist(e)
E(g)$weight <- stack(weights)[[1]]

plot(g, edge.label = E(g)$weight)

screenshot