如何在 R 中排列图表

How arrange diagram in R

我想得到类似于下图的图表,但我使用的代码创建了不同的图表。使用 rbind 我在图表中添加了一些层次结构。在数据框 col0 中有一个包含动物名称的字符串。在 col1 中,字符串被拆分为单个动物,并且 col2 正在为动物添加拉丁名称。 col1 数据总是在变化,并且在 col2 数据常量中(该列中总是有猫科动物或犬科动物的名字)。

library(igraph)
# I create my dataframe with animals
df <- data.frame(col0 = c("Cat Dog Wolf", "Cat Dog Wolf", "Cat Dog Wolf"),
col1 = c( "Cat", "Dog", "Wolf"),
col2 = c( "Feline", "Canis", "Canis2"))
# Add extra lines for hierarchy 
# These lines work with current graph for a new one these should be replace or deleted
df <-rbind(df, data.frame(col0 = "Cat Dog Wolf", col1 = "Feline", col2 ="Animal"))
df <-rbind(df, data.frame(col0 = "Cat Dog Wolf", col1 = "Canis", col2 = "Animal"))
df <-rbind(df, data.frame(col0 = "Cat Dog Wolf", col1 = "Canis2", col2 = "Canis"))

##########
df <-df[c('col2', 'col1')]
names(df) <-c('from', 'to')
abc <-union(df$to, df$from)
###########

g <-graph.data.frame(df, directed = TRUE, vertices = abc)
plot(g, vertex.size = 20, vertex.label.dist = 0.5, vertex.color = c("blue", 
"red", "green", "white", "orange"  ),
edge.arrow.size = 0.5, layout = layout.reingold.tilford(g))

这是上面代码输出的图,但不是我想要的:

我想要一张与下图类似的图表:

我想我明白你想要什么,但我会重述这个问题 以便您确认我是否理解。我认为那是什么 你想做的是:

找到树中的所有叶子,即没有后代的节点。 每片叶子将有一个parent。将 parent 重命名为 叶子,然后从图中删除叶子。以下代码实现了这一点。

## 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))

结果