Creating a graph with variable edge width in Rgraphviz

This was waaaaay more complicated than necessary. Figuring it out took me almost a whole day.

In essence, there is the graph package in R, which provides graph objects and methods, and there is the Rgraphviz package, which allows you to plot the graphs on the screen. They work well.

library(graph)
library(Rgraphviz)
nodes <- c( LETTERS[1:3] )
edgesL <- list( A=c("B", "C"), B=c("A", "C"), C=c("B", "A" ) )
graph <- new( "graphNEL", nodes= nodes, edgemode="undirected", edgeL=edgesL )
rag <- agopen( graph, "" )
plot(rag)

Here the output:

example0

So far, so good. If I wanted to color the edge from A to C red, here is what I could do:

eAttrs <- list( color=c( "A~C"="red" ) )
rag <- agopen( graph, "", edgeAttrs=eAttrs )
plot(rag)

example2

The attribute “color” works well. The man page for AgEdge gives us other attributes, specifically, “lwd” which specifies the width of the edge. However, it is not possible to set the edge widths using the above method. I found that the following code works for me:

setEdgeAttr <- function( graph, attribute, value, ID1, ID2 ) {

  idfunc <- function(x) paste0( sort(x), collapse="~" )
  all.ids <- sapply( AgEdge(graph), 
    function(e) idfunc( c( attr(e, "head"), attr( e, "tail" ))))

  sel.ids <- apply(cbind( ID1, ID2 ), 1, idfunc )

  if(!all(sel.ids %in% all.ids)) stop( "only existing edges, please" )
  sel <- match( sel.ids, all.ids )

  for(i in 1:length(sel)) {
    attr( attr( graph, "AgEdge" )[[ sel[i] ]], attribute ) <- value[i]
  }

  return(graph)
}

Example:

rag <- agopen( graph, "" )
rag <- setEdgeAttr( rag, "lwd", c(5, 20), c("B", "B"), c( "A", "C" ) )
plot(rag)

example4

What a colossal waste of my time. However, I need a visualization with graphs; and it needs to take a custom node drawing function as an argument, so there.