代码之家  ›  专栏  ›  技术社区  ›  d-cubed Tyler Rinker

3列CSV,到邻接矩阵,到网络图,到Arcplot

  •  4
  • d-cubed Tyler Rinker  · 技术社区  · 9 年前

    我正在尝试将一个有3列的CSV转换为一个arcplot。这些列- A , B , C 总是按顺序进行 A. -> B -> C 然而,我没有找到一种方法来实现这一点,因为大多数方法似乎都使用了两列边缘图。因此,我一直在遵循指示 here 转换为邻接矩阵。

    我将在下面重新创建问题,但不会生成虚假数据,因为一个问题是CSV可能无法正确读取。

    基本上,CSV包含行,其中每列由 , 但可能包含多个由分隔的值 ; 例如:

    ENV;MO,echoic;tact,social 
    ENV;MO,mand,physical
    OVB,intraverbal,social
    ENV;OVB,tact,social
    OVB,intraverbal;tact,social
    OVB;ENV;MO,intraverbal;mand,social
    OVB;ENV;MO,intraverbal;mand,physical;social
    ENV;MO,mand,social;physical
    

    为了在移动到arcplots之前完成一些网络绘图,我尝试了以下操作:

    options(stringsAsFactors = F)
    lst <- read.csv("abc.csv", header=FALSE)
    
    #this is pretty much straight from the link above
    d <- do.call(rbind, lst)
    edges <- rbind(d[ ,1:2], d[ ,2:3])
    g <- graph.data.frame(edges, directed=TRUE)
    adj <- as.matrix(get.adjacency(g)) 
    g2 <- new("graphAM", adjMat=adj, edgemode="directed")
    plot(g2, attrs = list(graph = list(rankdir="LR"), node = list(fillcolor = "lightblue")))
    

    结果完全不是我所希望的。而不是列中的元素 A. 指向 B 指向 C 相反,它只是A中指向自身的一个元素;一个来自 B 指向另一个人指向另一个,例如。, intraverbal -> mand -> 言语内的 ; tact ,一个来自 C 指向自身和来自的另一个值 C .

    附录:鉴于 A. -> B -> C 格式,一行,如

    卵白;环境;MO,言语内;曼德,社会

    表示

    A(OVB&ENV&MO)->B(言语交流)->C(社会)

    虽然这可能超出了问题的范围,但最终目标将是类似于此处所示的弧形图 PDF guide to arcplots in R

    2 回复  |  直到 7 年前
        1
  •  4
  •   nicola    9 年前

    不确定这是不是你想要的。但是,您可以尝试:

    require(igraph)
    df[]<-lapply(df,strsplit,";")
    el<-as.matrix(do.call(rbind,apply(df,1,expand.grid)))
    g<-graph_from_edgelist(rbind(el[,-3],el[,-1]))
    plot(g)
    

    enter image description here

    数据

    df<-structure(list(V1 = c("ENV;MO", "ENV;MO", "OVB", "ENV;OVB", "OVB", 
    "OVB;ENV;MO", "OVB;ENV;MO", "ENV;MO"), V2 = c("echoic;tact", 
    "mand", "intraverbal", "tact", "intraverbal;tact", "intraverbal;mand", 
    "intraverbal;mand", "mand"), V3 = c("social", "physical", "social", 
    "social", "social", "social", "physical;social", "social;physical"
    )), .Names = c("V1", "V2", "V3"), row.names = c(NA, -8L), class = "data.frame")
    
        2
  •  3
  •   digEmAll    9 年前

    您可以使用此代码(实际上它甚至不需要igraph…):

    # of course you need to install arcdiagram first
    # as described in the pdf
    library(arcdiagram) 
    
    DF <- read.table(text=
    "ENV;MO,echoic;tact,social 
    ENV;MO,mand,physical
    OVB,intraverbal,social
    ENV;OVB,tact,social
    OVB,intraverbal;tact,social
    OVB;ENV;MO,intraverbal;mand,social
    OVB;ENV;MO,intraverbal;mand,physical;social
    ENV;MO,mand,social;physical",sep=',')
    
    # replace ";" with "&\n"
    DF[] <- lapply(DF,function(x)gsub(';',' &\n',x))
    
    # create adjacency matrix
    m <- rbind(as.matrix(DF[,1:2]),as.matrix(DF[,2:3]))
    
    # plot...
    arcplot(m ,col.arcs='DodgerBlue',lwd.arcs=2,col.labels='black',las=2)
    

    enter image description here