简体   繁体   English

tidygraph 中的 Label 个树枝

[英]Label tree branches in tidygraph

I have a rooted forest with 116 trees as a tidygraph object. I now want to add a new property to the nodes, ie label the nodes within the branches.我有一个有 116 棵树的有根森林作为tidygraph object。我现在想向节点添加一个新属性,即 label 分支内的节点。

For instance, for a graph例如,对于一个图

a <- tibble(from = c(1, 2, 3, 3, 4, 5, 7, 8, 8, 9, 10), 
            to = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
a_graph = as_tbl_graph(a)

I'd like to have a column in the node data with c("A", "A", "A", "B", "C", "B", "C", "C", "D", "E", "D", "E") , ie nodes 1-3 are labeled with A, nodes 4 and 6 with B, nodes 5, 7, 8 with C, nodes 9 and 11 with D, and nodes 10 and 12 with E.我想在节点数据中有一列c("A", "A", "A", "B", "C", "B", "C", "C", "D", "E", "D", "E") ,即节点1-3标记为A,节点4和6标记为B,节点5、7、8标记为C,节点9和11标记为D,节点10和 12 与 E.

So, is there a way to automatically label the nodes depending on the branch they're on even if the trees in my forest can have very different structures?那么,有没有一种方法可以根据节点所在的分支自动 label 节点,即使我森林中的树可能具有非常不同的结构?

This will label nodes in groups of 3 if there are less than 78 nodes.如果少于 78 个节点,这将以 3 个为一组的 label 个节点。 Trees having more nodes require multi character labels eg AA.具有更多节点的树需要多字符标签,例如 AA。

library(tidygraph)
#> 
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(tidyverse)

a <- tibble(
  from = c(1, 2, 3, 3, 4, 5, 7, 8, 8, 9, 10),
  to = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
)
a_graph <- as_tbl_graph(a)

a_graph |>
  activate(nodes) |>
  mutate(label = name |> map_chr(function(name) {
    res <- as.integer(name)
    res <- res / 4
    res <- LETTERS[res + 1]
    res
  }))
#> # A tbl_graph: 12 nodes and 11 edges
#> #
#> # A rooted tree
#> #
#> # Node Data: 12 × 2 (active)
#>   name  label
#>   <chr> <chr>
#> 1 1     A    
#> 2 2     A    
#> 3 3     A    
#> 4 4     B    
#> 5 5     B    
#> 6 7     B    
#> # … with 6 more rows
#> #
#> # Edge Data: 11 × 2
#>    from    to
#>   <int> <int>
#> 1     1     2
#> 2     2     3
#> 3     3     4
#> # … with 8 more rows

Created on 2022-06-21 by the reprex package (v2.0.0)reprex package (v2.0.0) 创建于 2022-06-21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM