2

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

user3934361
  • 21
  • 1
  • 2
  • 2
    You're more likely to get help if you post your date (or a link to it), or at least a representative sample, and show the code you've created so far to solve the problem. See [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – jlhoward Aug 12 '14 at 19:50
  • Sorry, this was my first time posting here, and my graph is so large that I didn't think about that. – user3934361 Aug 14 '14 at 16:00

2 Answers2

3

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)
Will Beason
  • 3,417
  • 2
  • 28
  • 46
1

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"))
kory
  • 472
  • 4
  • 9
  • I'm trying to do the same with arrows, it works, but it seems that arrows are always drawn above edges, so I have edges in the correct layering, arrows in the correct layering, but back arrows over front edges and arrows not coupled with their respective edges. – Halberdier Jul 22 '20 at 14:23