2011-03-19 228 views
24

我想绘制一个网络可视化,以类似于流程图。我相当接近用下面的代码,但我有几个问题:如何使用固定位置控制igraph绘图布局?

  1. 这是最好的布局()算法,或我可以手动分配>
  2. 我怎样才能使每个节点的位置确定这些节点在剧情中不重叠(就像他们在这里做的那样)?
  3. 我可以将一个节点分配为“锚点”还是起点?即,我可以让“C”成为最顶层还是最左边的节点?

非常感谢!

library("igraph") 
L3 <- LETTERS[1:8] 
d <- data.frame(start = sample(L3, 16, replace = T), end = sample(L3, 16, replace = T), 
       weight = c(20,40,20,30,50,60,20,30,20,40,20,30,50,60,20,30)) 


g <- graph.data.frame(d, directed = T) 

V(g)$name 
E(g)$weight 

ideg <- degree(g, mode = "in", loops = F) 

col=rainbow(12) # For edge colors 

plot.igraph(g, 
    vertex.label = V(g)$name, vertex.label.color = "gray20", 
    vertex.size = ideg*25 + 40, vertex.size2 = 30, 
    vertex.color = "gray90", vertex.frame.color = "gray20", 
    vertex.shape = "rectangle", 
    edge.arrow.size=0.5, edge.color=col, edge.width = E(g)$weight/10, 
    edge.curved = T, 
    layout = layout.reingold.tilford) 

回答

32

igraph中的布局定义在矩阵中,每个节点有2列和1行。第一列指示其x位置,第二列指示其y位置,并且比例不相关(它总是重新调整以适合-1到1的绘图区域。您可以在绘图之前通过调用图形上的布局函数来获得此布局:

l <-layout.reingold.tilford(g) 
l 
    [,1] [,2] 
[1,] 0 0 
[2,] -1 3 
[3,] 0 1 
[4,] 0 3 
[5,] 0 2 
[6,] 0 4 
[7,] 1 3 

这样你可以改变它在手动想要的任何方式,然后将其发送到剧情:

plot.igraph(g, 
    vertex.label = V(g)$name, vertex.label.color = "gray20", 
    vertex.size = ideg*25 + 40, vertex.size2 = 30, 
    vertex.color = "gray90", vertex.frame.color = "gray20", 
    vertex.shape = "rectangle", 
    edge.arrow.size=0.5, edge.color=col, edge.width = E(g)$weight/10, 
    edge.curved = T, 
    layout = l) 

这似乎也可以设置参数params控制布局abit。这是一个包含参数root的列表,显然它可以用来设置图形的根。该节点(reigramber igraph使用类似C的节点索引,第一个是0)。因此,设置在根“C”:

l <- layout.reingold.tilford(g,params=list(root=2)) 

编辑:另外的RGraphViz中有一些不错的树的布局,可能是值得一试。


编辑2:

这是从我的包,它采用的是同一种布局矩阵的图形,以确定节点的位置,你可能会发现有用的源代码的修改的摘录:

gridLayout <- function(x) 
{ 
    LmatX <- seq(-1,1,length=ncol(x)) 
    LmatY <- seq(1,-1,length=nrow(x)) 

    loc <- t(sapply(1:max(x),function(y)which(x==y,arr.ind=T))) 
    layout <- cbind(LmatX[loc[,2]],LmatY[loc[,1]]) 
    return(layout) 
} 

什么这个函数是变换矩阵指定在一个网格(类似于layout())布局的两列布局与x和y位置。定义一个零矩阵,并为每个节点的整数从1到节点总数(这是igraph ID + 1)。

例如,对于一个愚蠢的4节点图:

grid <- matrix(c(
    0,0,1,0,0, 
    2,0,3,0,4),nrow=2,byrow=TRUE) 

library("igraph") 

g <- graph.adjacency(matrix(1,4,4)) 

plot(g,layout=gridLayout(L)) 
+0

感谢您的提示!像这样把位置放在一起:l2 < - as.matrix(data.frame(c(0,6,12,12,12,24,24,24),c(0,.5,.5 ,0,-1,1,-1,。25))) – 2011-03-20 04:51:13

+3

2年后,这个答案对我有帮助:-) – 2013-06-30 14:26:00

+1

Sacha,当我应用你的代码时,我得到ncol(x)中的错误:找不到对象'L'。在plot(g,layout = gridLayout(L))这一行中,可能有一个我无法理解的问题。 – 2016-10-26 13:42:50

4

,如果你要分配的节点位置自己是增加与您的数据表标记为X和Y列一个不太复杂的方法比上面这些列中各个节点的x和y坐标。例如

library('igraph') 
nodes <- c('a','b','c','d') 
x <- c(0,1,2,3) 
y <- c(0,1,2,3) 
from <- c('a','b','c') 
to <- c('b','c','d') 
NodeList <- data.frame(nodes, x ,y) 
EdgeList <- data.frame(from, to) 
a<- graph_from_data_frame(vertices = NodeList, d= EdgeList, directed = FALSE) 
plot(a) 

enter image description here