elliot
elliot

Reputation: 1944

Control the order in which nodes and edges are drawn in R igraph?

Is it possible to control the order in which nodes and edges are drawn in an igraph plot? Something similar to the way ggplot2 plots points in the order that they are arranged in the dataframe. I know that there is bound to be overlap in plotted nodes and edges, but I'd like to be able to control which are most visible (i.e. the ones plotted on the top). I have a graph with some overlap below.

library(igraph)
library(scales)
col_fun <- colorRampPalette(c('tomato', 'skyblue'))

g <- erdos.renyi.game(100, .025)

V(g)$label <- NA
V(g)$size <- scales::rescale(degree(g), c(5,15))

V(g)$color <- col_fun(vcount(g))

E(g)$color <- col_fun(ecount(g))

plot(g)

Plot with overlap

Upvotes: 2

Views: 933

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48201

Just like in ggplot2 we look at the row numbers in a data frame, in igraph we also look at vertex ID's. As an example, let

set.seed(1)
g <- erdos.renyi.game(100, .05)
V(g)$name <- 1:100
V(g)$size <- scales::rescale(degree(g), c(3, 20))
V(g)$color <- col_fun(vcount(g))
V(g)$color[92] <- "#FF0000"
V(g)$color[2] <- "#00FF00"
plot(g)

enter image description here

Here vertex 2 is small and green, while vertex 92 is big and red. Notice that vertices are named. Also one can see that vertices with higher numbers are on top of those with lower numbers (vertex names correspond also to their order). On the other hand,

set.seed(1)
g <- erdos.renyi.game(100, .05)
V(g)$name <- 1:100
idx <- 1:100
idx[c(92, 2)] <- c(2, 92)
g <- permute(g, idx)
V(g)$size <- scales::rescale(degree(g), c(3, 20))
V(g)$color <- col_fun(vcount(g))
V(g)$color[2] <- "#FF0000"
V(g)$color[92] <- "#00FF00"
plot(g)

enter image description here

Now vertex 92 is below others and vertex 2 is actually also pretty high. This happened due to permute that switched vertices 2 and 92:

idx <- 1:100
idx[c(92, 2)] <- c(2, 92)
g <- permute(g, idx)

That's not particularly convenient, but I'm not aware of any other way to reorder vertices.

Upvotes: 1

Related Questions