关于r:igraph创建加权邻接矩阵

igraph creating a weighted adjacency matrix

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

考虑以下随机对称矩阵:

1
2
3
4
5
6
7
8
9
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文档的阅读,我应该执行以下操作:

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

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

1
2
3
4
5
6
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识别边缘权重?


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

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

graph plot screenshot

对于绘图,请确保您阅读了?igraph.plotting


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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


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

使用邻接矩阵,您还可以仅使用qgraph库中的qgraph()对其进行绘制。它将自动为负边缘涂上红色阴影,为正边缘涂上绿色阴影。

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

qgraph建立在igraph之上,但是为您做的一切。


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

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

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

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