Search code examples
rigraphgraph-visualization

Define Edge labels based on matching vertex type in R


I have a graph net with two different types (1 and 2) of vertices, appearing n1 and n2 times, respectively:

net %v% "type" <- c(rep("1", n1), rep("2", n2))

We have some edges which were generated randomly with probabilities ps and pd, where ps is the edge probability with a same type (1-1 or 2-2) and pd with a different type (1-2).

I would like to plot this graph such that the edges between same types (i.e. 1-1 or 2-2) have a different color than edges between different types (1-2).

How do I do this? I tried playing around with the %e% operator of the network package, but I'm confused about how to grab the type of the end node of each edge. Thank you!


Solution

  • Do you want that?

    from <- sample(1:2, 10, replace = T)
    to <- sample(1:2, 10, replace = T)
    node <- cbind(from, to)
    library(igraph)
    net <- graph_from_edgelist(node, directed = F)
    edge_color <- function(from_to){
      from_node <- from_to[1]
      to_node <- from_to[2]
      ifelse(from_node == to_node, return("red"), return("blue"))
    }
    color<- apply(node, 1, edge_color)
    plot(net, edge.color=color)
    

    enter image description here