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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With