igraph creating a weighted adjacency matrix

Scott Ritchie picture Scott Ritchie · Jan 23, 2014 · Viewed 30.9k times · Source

I'm trying to use the igraph package to draw a (sparse) weighted graph. I currently have an adjacency matrix, but cannot get the graph.adjacency function to recognise the edge weights.

Consider the following random symmetric matrix:

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)

To plot, first I must get this adjacency matrix into the proper igraph format. This should be relatively simple with graph.adjacency. According to my reading of the documentation for graph.adjacency, I should do the following:

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

However, it doesn't recognise the edge weights:

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

How do I get igraph to recognise the edge weights?

Answer

Gabor Csardi picture Gabor Csardi · Jan 23, 2014

The weights are there, weight (e/n) means that there is an edge attribute called weight, and it is numeric. See ?print.igraph. But they are not plotted by default, you need to add them as edge.label.

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

graph plot screenshot

For plotting, make sure you read ?igraph.plotting.