2014-07-25 22 views
0

这是从一个后续问题:Creating treechart from tabbed text in R订单中的R的igraph包不正确treechart条目

我使用下列的函数:

treechart = function(){ 
library(psych) 
fields <- max(count.fields(textConnection(readClipboard()), sep = "\t")) 
dat = read.table(text = readClipboard(), sep="\t",col.names = paste0("V", sequence(fields)), header=FALSE, fill=TRUE, strip.white=TRUE, stringsAsFactors=FALSE, na.strings="") 

library(zoo) 
library(igraph) 
# To prepare the data 
# carry forward the last value in columns if lower level (col to the right) 
# is non-missing 
dat[1] <- na.locf(dat[1], na.rm=FALSE) 
for(i in ncol(dat):2) { 
    dat[[i-1]] <- ifelse(!is.na(dat[[i]]), na.locf(dat[[i-1]], na.rm=F), dat[[i-1]]) 
}    

# get edges for graph 
edges <- rbind(na.omit(dat[1:2]), 
      do.call('rbind', 
        lapply(1:(ncol(dat)-2), function(i) 
        na.omit(setNames(dat[(1+i):(2+i)], 
        names(dat[1:2]))))) 
         ) 

# create graph 
g <- graph.data.frame(edges) 
# Plot graph 
E(g)$curved <- 0 
plot.igraph(g, vertex.size=0, edge.arrow.size=0 , layout=-layout.reingold.tilford(g)[,2:1]) 
} 

我使用下面的示例数据(由制表符分隔在电子表格文本编辑器或),我选择并控制-C复制:

AAA 
    BBB 
    CCC 
    DDD 
     III 
     JJJ 
      LLL 
    EEE 
     KKK 
    FFF 
    GGG 

上运行的命令“treechart()”然后我获得以下图: enter image description here

这里DDD和EEE比BBB,CCC高。同样,JJJ在III之前。我怎样才能纠正这个顺序的函数treechart()始终是正确的?谢谢你的帮助。

回答

1

这不是说布局不正确,而只是你要求layout.reingold.tilford布局,这就是你得到的。正如你所看到的,它喜欢将更复杂的分支移到一边。它不考虑顶点指定的顺序。我试着写会保持秩序,新的布局功能

layout.tree.order <- function(g, vseq=V(g)$name, root=vseq[1]) { 
    leaves <- vseq[sapply(V(g)[vseq], function(x) 
     length(unique(neighbors(g, x, mode="out"))))==0] 
    ypos <- rep(NA, vcount(g)) 
    ypos[match(leaves, V(g)$name)]<-rev(seq(0,1,length.out=length(leaves))) 

    calcypos<-function(g, vx) { 
     if (!is.na(ypos[vx])) { 
      p <- ypos[vx] 
     } else { 
      nb <- unique(neighbors(g, V(g)[vx])) 
      p <- mean(sapply(nb, function(x) calcypos(g,x))) 
     } 
     ypos[vx] <<- p 
     return(invisible(p)) 
    } 
    calcypos(g, which(V(g)$name == root)) 
    xpos <- c(shortest.paths(g, V(g)[which(vseq == root)], V(g), mode="out")) 

    cbind(xpos, ypos) 
} 

然后你只是想改变的情节线在treemap函数添加一个额外的行,改变布局

vseq <- apply(dat, 1, function(x) na.omit(rev(x))[1]) 
plot.igraph(g, vertex.size=0, edge.arrow.size=0, 
    layout=layout.tree.order(g, vseq)) 

所以vseq这是什么指定自上而下的顺序。在这里,我们按照它们出现在您的dat数据框中的顺序使用这些值。这会产生如下图:

enter image description here

+0

是的,它现在完美了! – rnso