我想获得类似于下图的图表,但我使用的代码创建了不同的图表。使用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))
这是上面代码输出的图表,但它不是我想要的:
我想要一个类似于下图所示的图表:
答案 0 :(得分:1)
我认为我明白你想要什么,但我会重申这个问题 这样你就可以确认我是否理解。我想那是什么 你想做的是:
查找树中的所有叶子,即没有后代的节点。 每片叶子都有一个父母。使用名称重命名父级 leaf,然后从图中删除叶子。以下代码实现了它。
## 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))
<强>结果强>