Search code examples
rigraph

How can I assign a color range to edges in igraph plot in R based on edge attributes?


I have a large social network plot that I am trying to color-code using the strength of the connections between individuals. In mock_table, the individuals are listed in column a and b, and the strength of each connection is given in column c.

I was successful in properly assigning these strength values to the edge.width function, however, when I attempt to apply this to the edge.color, the values do not properly align. The colors in the plot do represent sn_color, but they are not assigned to the proper edges. The thickest edges (strongest connection, largest c-value) should also have the darkest color and vice versa.

Below is a simplified version of my current code:

mock_table <- as.data.frame(cbind(a=c("PO", "BL", "MA", "AL", "BL"), b=c("MA", "BO", "ED", "MA", "MA"), c=as.numeric(c(8,41,10,23,50))))
mock_table$c <- as.numeric(as.character(mock_table$c))

sn_graph <- graph_from_data_frame(d=mock_table, vertices = c("PO", "BL", "MA", "AL", "BO", "ED"), directed = FALSE)
sn_proximity <- (mock_table$"c")

sn_colorrange <- colorRampPalette(c("yellow", "orange", "red", "darkred"))
sn_color <- sn_colorrange(length(sn_proximity))

plot(sn_graph,
     edge.width=(1/3)*(sn_proximity),
     edge.color=sn_color
     )

Would anyone be able to help me figure out how I can properly assign this color palette? Thanks so much!

Edited to include reproducible example code.


Solution

  • You need to tell the plot exactly which color to use. If you wanted to use a different color for each from the ramp, then you could do something like

    plot(sn_graph,
         edge.width=(1/3)*(sn_proximity),
         edge.color=sn_color[order(sn_proximity)]
    )
    

    Otherwise it may be more common to set a fixed number of bins and then use cut() to the color has more meaning

    n_bins <- 5
    sn_color <- sn_colorrange(n_bins)
    plot(sn_graph,
         edge.width=(1/3)*(sn_proximity),
         edge.color=sn_color[cut(sn_proximity, breaks=n_bins )]
    )