Advertisement
Guest User

Untitled

a guest
Aug 29th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.86 KB | None | 0 0
  1. library(Rgraphviz)
  2.  
  3. # Assumes that a graph is  a data frame with columns
  4. # subject, object, [label, width, hue, saturation, brightness]
  5.                  
  6. namedvector <- function(names, values) {names(values) = names; values}
  7.  
  8. render <- function(graph) {
  9.   nodes = union(graph$subject, graph$object)
  10.   edges = tapply(graph$object, graph$subject, function(x) list(edges=as.character(x)), simplify=F)
  11.   # add edges for object-only nodes (leafs)
  12.   for (leaf in setdiff(graph$object, graph$subject)) edges[[leaf]] = list(edges=NULL)  
  13.   # create graph
  14.   g <- new("graphNEL", nodes = nodes, edgeL = edges, edgemode="directed")
  15.   # add labels, width, color if given  
  16.   edgeids = paste(graph$subject, graph$object, sep="~")
  17.   edgeAttrs = if (is.null(graph$label)) list() else
  18.     list(label=namedvector(edgeids, as.character(graph$label)) )
  19.   if (!is.null(graph$col))
  20.     edgeRenderInfo(g) <- list(col=namedvector(edgeids, as.character(graph$col)))
  21.   if (!is.null(graph$width))
  22.     edgeRenderInfo(g) <-  list(lwd=namedvector(edgeids, graph$width))
  23.   if (!is.null(graph$label))
  24.     edgeRenderInfo(g) <- list(label=namedvector(edgeids, as.character(graph$label)))
  25.   # layour and render
  26.   g = layoutGraph(g, recipEdges="distinct", edgeAttrs=edgeAttrs)
  27.   renderGraph(g)
  28. }
  29.  
  30. # test code: create normal and reciprocal graph and some attributes
  31. graph = data.frame(subject=c("a", "c"), object=c("a", "a"))
  32. rgraph = data.frame(subject=c("a", "b"), object=c("b", "a"))
  33. label=c("0.7","-1.0")
  34. col=c("blue","red")
  35. width=c(2,4)
  36.  
  37. # plot graphs in rows with increasing #features complexity in columns
  38. layout(matrix(1:8, nrow=2, byrow=T))
  39. for (g in list(graph, rgraph)) {
  40.   render(g)
  41.   render(cbind(g, label=label))
  42.   render(cbind(g, label=label, width=width))
  43.   render(cbind(g, label=label, width=width, col=col))
  44. }
  45. # result at http://imageshack.us/photo/my-images/405/recip.png/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement