Search code examples
rgraphggally

R GGally color edges by vertex membership


I am trying to create a list to color the edges of a graph depending on the grouping of the vertices they connect to. If an edge connects two members of the same group, the edge has their color. If the edge is between members of different groups, the edges should be grey. Here is my code:

mnet = rgraph(10, mode = "graph", tprob = 0.5)
rownames(mnet)<-letters[1:10]
colnames(mnet)<-letters[1:10]
net = network(mnet, directed = FALSE, ignore.eval = FALSE, names.eval = "strength")
phono<-data.frame(letters=letters[1:10],phono=c("vowel", "consonant","consonant","consonant","vowel","consonant","consonant","consonant","vowel", "consonant"))
table(phono)
net %v% "phono" <- as.character(phono$phono)
nnet<-matrix(0, 10, 10)
for (i in 1:10){
  for (j in 1:10){
    nnet[i,j] = ifelse(phono$phono[phono$letters %in% rownames(mnet)[i]]==phono$phono[phono$letters %in% colnames(mnet)[j]],
                       as.character(phono$phono[phono$letters %in% rownames(mnet)[i]]),
                       "grey50")
  }
}
ggnet2(net, color = "phono", palette = "Set2", label = "phono", edge.color = unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])

I am unhappy with that double loop in the middle of my R code. Is there a better way to do what I am trying to do? This is piggybacking off my most previous question which more tried to understand why "outer" wasn't working.

Also, the code doesn't work in general, but let's do one problem at a time. even though length(unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])==length(net %e% "strength")

Thanks.


Solution

  • Is this what you are looking for?

    enter image description here

    Code:

    # build graph
    net <- sna::rgraph(10, mode = "graph", tprob = 0.5)
    net <- network::network(net, directed = FALSE)
    
    # vowels and consonants
    phono <- c("v", "c", "c", "c", "v", "c", "c", "c", "v", "c")
    names(phono) <- letters[1:10]
    
    # extract edgelist, identify same-letter-type ties
    edges <- as.edgelist(net)
    k <- ifelse(phono[ edges[, 1] ] == phono[ edges[, 2] ], phono[ edges[, 1] ], NA)
    
    # color ties using `Set2` colors
    k[ is.na(k) ] <- "x"
    k <- c("c" = "#66C2A5", "v" = "#FC8D62", "x" = "grey50")[ k ]
    
    set.edge.attribute(net, "tie.type", k)
    GGally::ggnet2(
      net,
      color = phono[ network.vertex.names(net) ],
      palette = "Set2",
      label = phono[ network.vertex.names(net) ],
      edge.color = "tie.type",
      edge.size = 1
    )