简体   繁体   中英

Plot edges based on weight using R igraph

I'm trying to plot a network with igraph in R where the edges are sorted by weight. I have assigned colors, but I want weak edges on the back and strong edges in front. Is there a way of doing this? thanks

Here's a possible solution. It really depends on what you're working with, so with a code sample I could improve this.

Basically, edges are plotted in the order they appear. So we need to sort edges based on their weight attribute. This doesn't seem possible to do within the same graph, so it may just be necessary to create a new graph with the same attributes but with the edges sorted.

g <- graph( c(1,2, 1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5), n=5 )
E(g)$weight <- runif(10)

# Generates a the same graph but with edges sorted by weight.
h <- graph.empty() + vertices(V(g))
h <- h + edges(as.vector(t(get.edgelist(g)[order(E(g)$weight),])))
E(h)$weight <- E(g)$weight[order(E(g)$weight)]

E(h)$color <- "red"
E(h)[weight>0.3]$color <- "yellow"
E(h)[weight>0.7]$color <- "green"
plot(h,edge.width=2+3*E(h)$weight)

Updated version that worked for me:

df_edges <- as_data_frame(old_graph, what = "edges")
df_edges <- df_edges[order(df_edges$weight),]
new_graph <- graph_from_data_frame(d = df_edges, vertices = as_data_frame(old_graph, what = "vertices"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM