Search code examples
rdata-visualizationigraphdata-manipulation

R: Assigning Colors to a Graph


I am working with the R programming language.

I have the following graph:

library(igraph)
library(dplyr)

#create file from which to sample from
x5 <- sample(1:100, 1000, replace=T)
#convert to data frame
x5 = as.data.frame(x5)

#create first file (take a random sample from the created file)
a = sample_n(x5, 900)
#create second file (take a random sample from the created file)
b = sample_n(x5, 900)

#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")

graph <- graph.data.frame(c, directed=F)
graph <- simplify(graph)

plot(graph)

enter image description here

For each of these nodes in this graph, I have a "value" corresponding to node:

length = length(unique(cbind(c(c$a, c$b))))
values = data.frame(node = unique(cbind(c(c$a, c$b))), value = rnorm(length, 200, 10 ))

Here is what I have tried so far (Is there an easy way to color network nodes by degree in igraph for R?):

uni_all <- seq(min(values$value), max(values$value))
colors <- data.frame(color = heat.colors(length(uni_all), rev = T), levels = uni_all)
V(graph)$color <- colors$color[match(V(graph), colors$levels)]

plot(graph)

But this is producing a colorless graph:

enter image description here

Can someone please show me what I am doing wrong and how I can fix this?

Thanks!


Solution

  • First, make sure the scores in 'values' are in the same order as the vertices in 'graph'. The names of the vertices are stored in V(graph)$name as a vector of strings.

    values<- values[match(V(graph)$name, values$node), 'value']
    

    I suggest using the colorRamp function, so you can define your own color palette.

    Col_Pal <- colorRamp(c('red','orange','yellow'))   
    

    The colorRamp function maps values within the interval [0,1] to colors. We will therefore need to normalize the values in 'values' to this range.

    values<- (values-min(values))/diff(range(values))
    

    Extract the colors for the nodes from the color palette based on the values specified in the vector 'values'.

    Col_Nodes<- rgb(Col_Pal(values), max=255) 
    

    Assign the colors to the vertices of 'graph', storing them as the attribute 'col'.

    V(graph)$col<- Col_Nodes
    

    Plot the graph.

    plot(graph, vertex.color = V(graph)$col)