Creating a graph with variable edge width in Rgraphviz

March 26, 2015
By

(This article was first published on log Fold Change » r, and kindly contributed to R-bloggers)

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.

To leave a comment for the author, please follow the link and comment on their blog: log Fold Change » r.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)