Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Network in R (control edge thickness plus non-overlapping edges)

Tags:

r

I need to draw a network with 5 nodes and 20 directed edges (an edge connecting each 2 nodes) using R, but I need two features to exist:

  1. To be able to control the thickness of each edge.
  2. The edges not to be overlapping (i.e.,the edge form A to B is not drawn over the edge from B to A)

I've spent hours looking for a solution, and tried many packages, but there's always a problem.

Can anybody suggest a solution please and provide a complete example as possible?

Many Thanks in advance.

like image 581
Pansy Avatar asked Sep 22 '11 20:09

Pansy


1 Answers

If it is ok for the lines to be curved then I know two ways. First I create an edgelist:

Edges <- data.frame(
    from = rep(1:5,each=5),
    to = rep(1:5,times=5),
    thickness = abs(rnorm(25)))

Edges <- subset(Edges,from!=to)

This contains the node of origin at the first column, node of destination at the second and weight at the third. You can use my pacake qgraph to plot a weighted graph using this. By default the edges are curved if there are multiple edges between two nodes:

library("qgraph")
qgraph(Edges,esize=5,gray=TRUE)

qgraph

However this package is not really intended for this purpose and you can't change the edge colors (yet, working on it:) ). You can only make all edges black with a small trick:

qgraph(Edges,esize=5,gray=TRUE,minimum=0,cut=.Machine$double.xmin)

For more control you can use the igraph package. First we make the graph:

library("igraph")
g <- graph.edgelist(as.matrix(Edges[,-3]))

Note the conversion to matrix and subtracting one because the first node is 0. Next we define the layout:

l <- layout.fruchterman.reingold(g)

Now we can change some of the edge parameters with the E()function:

# Define edge widths:
E(g)$width <- Edges$thickness * 5

# Define arrow widths:
E(g)$arrow.width <- Edges$thickness * 5

# Make edges curved:
E(g)$curved <- 0.2

And finally plot the graph:

plot(g,layout=l)

igraph

like image 111
Sacha Epskamp Avatar answered Sep 19 '22 18:09

Sacha Epskamp