2013-03-21 111 views
5

我有一組簡單的方向關係(父 - >子),我想繪製。我的數據的結構使得有許多分立的子網絡。這裏有一些看起來像我的假數據。使用igraph在R中繪製多個離散網絡

require(igraph) 
parents<-c("A","A","C","C","F","F","H","I") 
children<-c("B","C","D","E","G","H","I","J") 
begats<-data.frame(parents=parents,children=children) 
graph_begats<-graph.data.frame(begats) 
plot(graph_begats) 

假數據中有兩個截然不同的子網絡,每個子網絡嚴格來說都是父母 - 子女的譜系。我需要在同一個窗口中繪製兩個譜系作爲樹形網絡(理想情況下是相同的頂點座標系)。我嘗試過使用layout.reingold.tilford(),但我最多隻能繪製其中一棵樹,所有其他頂點都繪製在根頂點頂部,就像這樣。

lo<-layout.reingold.tilford(graph_begats,root=1) 
plot(graph_begats,layout=lo) 

對任意數量的離散譜系進行此操作的任何想法?

+0

如果我能想出如何A)計算離散譜系的數量在數據集中,和B)分配給每個頂點到其譜系,我會的方式到75%解決我的問題。 – 2013-03-21 23:16:33

+1

使用'clusters()'或'decompose.graph()'分開網絡,然後分別計算每個網格的佈局,然後通過移動其中一個佈局矩陣來合併它們。 – 2013-03-22 01:09:44

+0

是的! 'decompose.graph()'是我需要的。仍然在矩陣轉換工作,但我到了那裏。 – 2013-03-22 14:15:13

回答

6

所以,正如我在上面的評論中提到的,一種解決方案是分別爲每個組件計算佈局。這很簡單,即使需要一些代碼才能正確執行。以下代碼適用於任意數量的組件。拓撲排序中的第一個頂點用作每個樹的根節點。

require(igraph) 

## Some data 
parents <- c("A", "A", "C", "C", "F", "F", "H", "I") 
children <- c("B", "C", "D", "E", "G", "H", "I", "J") 
begats <- data.frame(parents=parents, children=children) 
graph_begats <- graph.data.frame(begats) 

## Decompose the graph, individual layouts 
comp <- decompose.graph(graph_begats) 
roots <- sapply(lapply(comp, topological.sort), head, n=1) 
coords <- mapply(FUN=layout.reingold.tilford, comp, 
       root=roots, SIMPLIFY=FALSE) 

## Put the graphs side by side, roots on the top 
width <- sapply(coords, function(x) { r <- range(x[, 1]); r[2] - r[1] }) 
gap <- 0.5 
shift <- c(0, cumsum(width[-length(width)] + gap)) 
ncoords <- mapply(FUN=function(mat, shift) { 
    mat[,1] <- mat[,1] - min(mat[,1]) + shift 
    mat[,2] <- mat[,2] - max(mat[,2]) 
    mat 
}, coords, shift, SIMPLIFY=FALSE) 

## Put together the coordinates for the original graph, 
## based on the names of the vertices 
lay <- matrix(0, ncol=2, nrow=vcount(graph_begats)) 
for (i in seq_along(comp)) { 
    lay[match(V(comp[[i]])$name, V(graph_begats)$name),] <- ncoords[[i]] 
} 

## Plot everything 
par(mar=c(0,0,0,0)) 
plot(graph_begats, layout=lay) 

plot

+0

非常感謝,Gabor。這就是它! – 2013-03-23 13:12:17