按级别绘制 data.tree 着色和标签

问题描述 投票:0回答:2

我有以下 data.tree 结构。

d <- structure(list(SUBZONE = c("A1", "A2", "A3", "A4", "A8", "B10",  "B11", "B2", "B3", "B4"), 
                    ZONE = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"), 
                    ID = c(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L, 10L, 11L)), 
               .Names = c("SUBZONE", "ZONE", "ID"), 
               row.names = c(NA, 10L), 
               class = "data.frame")

d$pathString <- paste("all", d$ZONE,d$SUBZONE, sep = "/")
alltree <-as.Node(d)
plot(alltree)

根据图表和

alltree$Get(function(x) c(level = x$level))
,这棵树有三个不同的级别:

enter image description here

在格式化此图时我想实现两件事:

  1. 按级别给盒子上色,
  2. 逐个标签。

enter image description here

即使我尝试过,我也不知道如何访问这些级别。在本例中,我有“命名”节点,但并非我拥有的所有树都是如此,因此我想通过其级别号来访问它们。

r plot data.tree
2个回答
1
投票

您可以使用

Traverse
:

获取关卡中所有节点的集合
level1 <- Traverse(alltree, filterFun = function(x) x$level == 1)
level2 <- Traverse(alltree, filterFun = function(x) x$level == 2)
level3 <- Traverse(alltree, filterFun = function(x) x$level == 3)

这允许您根据需要为节点着色,如下所示:

Do(level1, SetNodeStyle, style = "filled", fillcolor = "#fff200", 
   fontcolor = "black", inherit = FALSE)
Do(level2, SetNodeStyle, style = "filled", fillcolor = "#feadc9", 
   fontcolor = "black", inherit = FALSE)
Do(level3, SetNodeStyle, style = "filled", fillcolor = "#b5e51a", 
   fontcolor = "black", inherit = FALSE)

这给出了这个结果:

plot(alltree)

enter image description here

就绘制级别而言,我无法在包本身中找到任何本地方法来执行此操作,但如果您导出为

DiagrammeR
格式,这是可能的。


0
投票

根据https://cran.r-project.org/web/packages/data.tree/vignettes/applications.html,特别是Jenny Lind(决策树,绘图)的应用,我利用了if控制过滤要修改的级别。看起来自然与这个问题有关。

d <- structure(
  list(
    SUBZONE = c("A1", "A2", "A3", "A4", "A8", "B10", "B11", "B2", "B3", "B4"),
    ZONE = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
    ID = c(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L, 10L, 11L)
  ),
  .Names = c("SUBZONE", "ZONE", "ID"),
  row.names = c(NA, 10L),
  class = "data.frame"
)

d$pathString <- paste("all", d$ZONE,d$SUBZONE, sep = "/")
alltree <-as.Node(d)
plot(alltree)
#
alltree$Get(function(x) c(level = x$level))

SetNodeStyle(
  alltree,
  style = "filled",
  fillcolor = function(node) {
    if (node$level == 1)
      "#fff200"
    else if (node$level == 2)
      c("#feadc9")
    else if (node$level == 3) {
      c("#b5e51a")
    }
  },
  fontcolor = "black",
  inherit = FALSE,
  label = function(node) {
    if (node$level == 2) {
      sapply(node$name, function(x) {
        paste0(x, "+++foo")
      })
    }
  }
)
plot(alltree) 
ToDiagrammeRGraph(alltree) |> DiagrammeR::export_graph(file_name="alltree_foo.png", file_type = "png")

我修改后的alltree

© www.soinside.com 2019 - 2024. All rights reserved.