igraph创建加权邻接矩阵

时间:2014-01-23 06:19:49

标签: r igraph

我正在尝试使用igraph包来绘制(稀疏)加权图。我目前有一个邻接矩阵,但无法获得graph.adjacency函数来识别边权重。

考虑以下随机对称矩阵:

m <- read.table(row.names=1, header=TRUE, text=
"           A          B          C          D           E         F
A 0.00000000  0.0000000  0.0000000  0.0000000  0.05119703 1.3431599
B 0.00000000  0.0000000 -0.6088082  0.4016954  0.00000000 0.6132168
C 0.00000000 -0.6088082  0.0000000  0.0000000 -0.63295415 0.0000000
D 0.00000000  0.4016954  0.0000000  0.0000000 -0.29831267 0.0000000
E 0.05119703  0.0000000 -0.6329541 -0.2983127  0.00000000 0.1562458
F 1.34315990  0.6132168  0.0000000  0.0000000  0.15624584 0.0000000")
m <- as.matrix(m)

要绘制图表,首先我必须将此邻接矩阵转换为正确的igraph格式。使用graph.adjacency时,这应该相对简单。根据我对graph.adjacency的文档的阅读,我应该做到以下几点:

library(igraph)
ig <- graph.adjacency(m, mode="undirected", weighted=TRUE)

但是,它无法识别边缘权重:

str(ig)
# IGRAPH UNW- 6 8 -- 
# + attr: name (v/c), weight (e/n)
# + edges (vertex names):
# [1] A--E A--F B--C B--D B--F C--E D--E E--F
plot(ig)

enter image description here

如何让igraph识别边缘权重?

4 个答案:

答案 0 :(得分:27)

权重在那里,weight (e/n)表示有一个名为weight的edge属性,它是数字。见?print.igraph。但默认情况下不会绘制它们,您需要将它们添加为edge.label。

plot(ig, edge.label=round(E(ig)$weight, 3))

graph plot screenshot

对于绘图,请务必阅读?igraph.plotting

答案 1 :(得分:9)

@ TWL的解决方案可以很容易地推广,以表示边缘的宽度作为权重的函数,包括负权重。诀窍是通过对最小权重的值求和(加上可选地表示最小权重宽度的偏移量)来转换所有权重。例如:

# reproducible example:
set.seed(12345)
a <- matrix(runif(5*5, min=-10, max=10), ncol=5)
diag(a) <- 0 # remove loops.
>a
           [,1]       [,2]      [,3]       [,4]       [,5]
[1,]  0.0000000 -6.6725643 -9.309291 -0.7501069 -0.9254385
[2,]  7.5154639  0.0000000 -6.952530 -2.2371204 -3.4649518
[3,]  5.2196466  0.1844867  0.000000 -1.9502972  9.3083065
[4,]  7.7224913  4.5541051 -9.977268  0.0000000  4.1496375
[5,] -0.8703808  9.7947388 -2.175933  9.0331751  0.0000000

# create igraph object.
g <- graph.adjacency(a, mode="undirected", weighted=TRUE)
plot(g)

# assign edge's width as a function of weights.
E(g)$width <- E(g)$weight + min(E(g)$weight) + 1 # offset=1
plot(g)

enter image description here

答案 2 :(得分:8)

尽管我喜欢igraph,但我发现qgraph包更容易绘制加权网络。

使用邻接矩阵,您也可以使用qgraph库中的qgraph()来绘制它。它会自动为负边缘着色为红色,正边缘为绿色。

install.packages('qgraph')
require(qgraph)
qgraph(m)
qgraph(m,edge.labels=TRUE)  #if you want the weights on the edges as well

qgraph建立在igraph上,但只是为你做了一切。

答案 3 :(得分:3)

您可以使用E(ig)$weight提取边权重,并将它们分配给绘图函数中的edge.width参数:

plot(ig, edge.width=E(ig)$weight)

请参阅?igraph.plotting [link]以供参考。

另请注意,在此示例中,权重将对应于边的宽度,因此它们应为>= 0

相关问题