Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale edge colors in igraph?

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?

like image 242
user3584444 Avatar asked Feb 06 '15 12:02

user3584444


1 Answers

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)
like image 186
ahmohamed Avatar answered Sep 23 '22 17:09

ahmohamed