10

I'm plotting a graph with igraph and I would like the edges to have different colors depending on the strength of the connections they represent. I could set the colors but I cannot relate them to the values of the connections' strength.

My current code is the following:

library(igraph)
library(raster)
library(ggplot2)
library(statnet)
library(qgraph)
connectivityMatrix <- as.matrix(read.table(file=myFile,sep='')))
coordinates <- as.matrix(read.table(file=coordinatesFile))
connectivityMatrix<-connectivityMatrix[1:833,1:833]
CM<-connectivityMatrix[subsetX,subsetY]
COORD<-coordinates[subset,]

net <- as.network(CM, matrix.type = "adjacency", directed = TRUE)

minX<-min(coordinates[,1])
maxX<-max(coordinates[,1])
minY<-min(coordinates[,2])
maxY<-max(coordinates[,2])


p<-plot(net, coord=COORD,xlim=c(minX,maxX),ylim=c(minY,maxY),edge.col=c('red','yellow','cyan','blue'),object.scale=0.005, vertex.col='dimgrey',edge.lwd=1) 

In the code above is there a way to relate the colors specified using edge.col to the range of values they represent in the CM? This way, the edges corresponding to the value 0-x1 in the connectivity matrix would be plotted in red, x1-x2 in 'yellow',.... and x3-x4 in blue. x1, x2, x3 being the range limits and x4 being the maximum of the CM.

Does anyone have an idea on how to do it? Would it be possible to add a legend including the edges' color and the ranges of values they represent?

1 Answer 1

9

You can use colorRamp as a scaling function. see the code below for example.

library(igraph)
#Create a random weighted graph
g = erdos.renyi.game(10,0.5)
E(g)$weight = runif(ecount(g))

#Color scaling function
c_scale <- colorRamp(c('red','yellow','cyan','blue'))

#Applying the color scale to edge weights.
#rgb method is to convert colors to a character vector.
E(g)$color = apply(c_scale(E(g)$weight), 1, function(x) rgb(x[1]/255,x[2]/255,x[3]/255) )

#plot using igraph
plot.igraph(g)
1
  • Thanks that's the kind of function I had been looking for. In the mean time, I created a matrix with the colors specified according to the value of the CM and passed it as an argument of the edge.col parameter. This allowed me to create a nice legend and to relate ranges of values in the CM with colors. Thank you anyway. Feb 16, 2015 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.