How arrange diagram in R

前端 未结 1 1790
醉酒成梦
醉酒成梦 2021-01-16 01:41

I want to get diagram similar to picture below, but code I use creates different diagram. With rbind I added some hierarchy to a diagram. In data frame co

相关标签:
1条回答
  • 2021-01-16 02:13

    I think that I understand what you want, but I will restate the problem so that you can confirm whether or not I understood. I think that what you want to do is this:

    Find all of the leaves in the tree, i.e. the nodes with no descendants. Each leaf will have one parent. Rename the parent with the name of the leaf, then delete the leaf from the graph. The following code implements that.

    ## Assume that we have created the graph g using your code
    g2 = g           # Keep original graph intact
    SourceNodes = sapply(strsplit(attr(E(g2), "vnames"), "\\|"), "[", 1)
    DestNodes = sapply(strsplit(attr(E(g2), "vnames"), "\\|"), "[", 2)
    
    ## Leaf nodes are nodes that are destinations, but not sources
    ## Also need the node numbers for later deletion
    (LeafNodes = DestNodes[which(!(DestNodes%in% SourceNodes ))])
    [1] "Cat"  "Dog"  "Wolf"
    (LeafNumbers = match(LeafNodes, attr(V(g), "name")))
    [1] 1 2 3
    
    ## Find the parents of the leaves
    (UpOne = SourceNodes[match(LeafNodes, DestNodes)])
    [1] "Feline" "Canis"  "Canis2"
    
    ## Rename the UpOne nodes (parents of leaves)
    vertex_attr(g2)$name[match(UpOne, vertex_attr(g2)$name)] = LeafNodes
    
    ## Now delete the leaf nodes and plot
    g2 = delete_vertices(g2, LeafNumbers)
    plot(g2, vertex.size = 20, vertex.label.dist = 0.5, 
        vertex.color = c("red", "green", "white", "orange"  ),
        edge.arrow.size = 0.5, layout = layout.reingold.tilford(g2))
    

    Result

    0 讨论(0)
提交回复
热议问题