Plot edges based on weight using R igraph

不打扰是莪最后的温柔 提交于 2019-12-11 11:56:26

问题


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


回答1:


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)



回答2:


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"))


来源:https://stackoverflow.com/questions/25269705/plot-edges-based-on-weight-using-r-igraph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!