rigraphggnetwork

Set edge colours based on edge relationships ggnet2, igraph r


I am plotting a graph with ggnet2. I would like to plot edges based on the value of edge relationship. Until now I was able only to represent edge value on the edge, below you can see an extract of my code:

ggnet2(max_spann_tree3 ,size =  nlav1,size.cut = 4, edge.size = 1, edge.color = "grey", edge.label = E(max_spann_tree2)$weight,edge.label.size = 2, color = "he1", color.legend = "industry", palette = "Set3")

Here the values that I used for the edge label in the my code:

edge.label=E(max_spann_tree2)$weight
> edge.label
  [1] 0.4047619 0.3703704 0.5483871 0.4727273 0.5510204 0.6078431 0.5490196 0.6451613 0.7254902 0.4489796
 [11] 0.6000000 0.4074074 0.5714286 0.6973684 0.8181818 0.8701299 0.6578947 0.4210526 0.5128205 0.4909091
 [21] 0.6037736 0.3793103 0.4166667 0.3750000 0.5000000 0.3000000 0.5660377 0.5263158 0.5000000 0.4634146

I would like to plot the same graph, but setting a colour scale based on the edge's relationships that are included in the range 0.2-0.9, without representing them in the edge's label. I tried with this: https://briatte.github.io/ggnet/#edge-size-and-color, without success. here my attempt:

>set.edge.attribute(max_spann_tree3 , "color", ifelse(max_spann_tree3 %e%"E(max_spann_tree2)$weight"> 0.5, "black"&& max_spann_tree3 %e%"E(max_spann_tree2)$weight"< 0.5, "red"))
> ggnet2(max_spann_tree3 ,size =  nlav1,size.cut = 4, edge.size = 1, edge.color = "color", edge.label.size = 2, color = "he1", color.legend = "industry", palette = "Set3")

> Error in if (!is_col(edge.color)) { : 
>       missing value where TRUE/FALSE needed

any suggestions?


Solution

  • If you want to color your graph edges by their weight, you can use the cut function along with its labels argument to assign a color attribute to your edges.

    library(igraph)
    library(GGally)
    
    #simulate a weighted network
    set.seed(1)
    tree_graph<-random.graph.game(20, p=.2)
    E(tree_graph)$weight<-sample(seq(0,1,0.01), ecount(tree_graph), replace=T)
    
    
    #add colors to edges according to what bin their weight falls in
    E(tree_graph)$color<-as.character(cut(E(tree_graph)$weight, 
                                                breaks=c(0, 0.3, 0.5, 0.7, 1), 
                                                labels=c("yellow", "orange", "red", "black")))
    
    #plot graph, verifying that colors match edge weights
    ggnet2(tree_graph, edge.color = "color", edge.label = "weight")