如何在R Studio中绘制具有13个节点的二叉树

时间:2013-12-21 02:12:05

标签: r plot

我是R的新人,我的情节图像戒指,明星。它们有特殊功能,但我不知道如何绘制具有13个节点的二叉树? 我使用了graph.extended.chordal.ring()函数,但它没有帮助。 R studio是否有任何好的教程,我如何绘制二叉树?

library(igraph)
G <-  graph.extended.chordal.ring(13, matrix(c(2,4,6), nr=1))
L <- layout.fruchterman.reingold(G)

2 个答案:

答案 0 :(得分:10)

您可以使用graph.tree功能,例如:

library(igraph)
G <- graph.tree(n=13,children=2)

# let's print it using a tree-specific layout 
# (N.B. you must specify the root node)
co <- layout.reingold.tilford(G, params=list(root=1)) 
plot(G, layout=co)

enter image description here


编辑(根据评论)

library(igraph)
G <- graph.tree(n=13,children=2)

#add names to vertex (just assign a upper-case letter to each)
V(G)$name <- LETTERS[1:length(V(G))]

# plot (1)
lay <- layout.reingold.tilford(G, params=list(root='A')) 
plot(G, layout=lay, vertex.size=25)

# add a vertex 'O', then a new edge 'G' --> 'O'
G <- G + vertices('O')
G <- G + edge('G', 'O')

# plot again (2)
lay <- layout.reingold.tilford(G, params=list(root='A')) 
plot(G, layout=lay, vertex.size=25)

enter image description here

答案 1 :(得分:0)

我喜欢@ digEmAll的解决方案,但这是另一个使用我的实验包btree。这很好,因为它将二进制树表示为data.table对象(基本上是data.frames)。

library(data.table)
library(ggplot2)
library(btree)

# Make a perfect btree with depth 3 -> 15 total nodes
btree <- make_perfect_btree(depth=3)
btree
    NodeId ParentNodeId LeftChildNodeId RightChildNodeId NodePath Depth
 1:      1           NA               2                3              0
 2:      2            1               4                5        L     1
 3:      3            1               6                7        R     1
 4:      4            2               8                9       LL     2
 5:      5            2              10               11       LR     2
 6:      6            3              12               13       RL     2
 7:      7            3              14               15       RR     2
 8:      8            4              NA               NA      LLL     3
 9:      9            4              NA               NA      LLR     3
10:     10            5              NA               NA      LRL     3
11:     11            5              NA               NA      LRR     3
12:     12            6              NA               NA      RLL     3
13:     13            6              NA               NA      RLR     3
14:     14            7              NA               NA      RRL     3
15:     15            7              NA               NA      RRR     3

# Remove nodes 14 & 15 to get a tree with 13 nodes. (We're simply removing rows from a data.frame)
btree <- btree[!NodeId %in% c(14, 15)]

# Plot the tree
plot_btree(btree, labelCol = "NodeId")

enter image description here