如何在R树形图中为满足3次成功先于2次失败的节点着色
为硬币抛掷树状图中符合条件的节点着色
问题背景
我有一枚两面的硬币(S=成功,F=失败),编写了以下R代码生成5次抛硬币的所有组合:
outcomes <- c("S", "F") combinations <- expand.grid(rep(list(outcomes), 5)) colnames(combinations) <- paste("Flip", 1:5)
输出的前几行组合如下:
> head(combinations) Flip 1 Flip 2 Flip 3 Flip 4 Flip 5 S S S S S F S S S S F S S S S F F S S S S S F S S
接着用data.tree包生成了展示所有分支的树状图:
library(data.tree) generate_tree <- function(node, depth) { if (depth == 0) { return(node) } else { for (outcome in c("S", "F")) { child <- node$AddChild(name = outcome) generate_tree(child, depth - 1) } return(node) } } root <- Node$new("Start") root <- generate_tree(root, 5) print(root, "level") plot(root)

我需要为出现3次成功时失败次数不足2次的分支节点染成绿色。已经能在表格中判断符合条件的组合:
outcomes <- c("S", "F") combinations <- expand.grid(rep(list(outcomes), 5)) colnames(combinations) <- paste("Flip", 1:5) check_successes_before_failures <- function(row) { successes <- sum(row == "S") failures <- sum(row == "F") return(successes >= 3 && failures < 2) } combinations$Three_Successes_Before_Two_Failures <- apply(combinations, 1, check_successes_before_failures) head(combinations)
输出结果:
Flip 1 Flip 2 Flip 3 Flip 4 Flip 5 Three_Successes_Before_Two_Failures S S S S S TRUE F S S S S TRUE S F S S S TRUE F F S S S FALSE S S F S S TRUE F S F S S FALSE
但不知道如何在树状图中为符合条件的节点着色?
解决方案
可以通过给data.tree的节点添加自定义属性,再根据属性设置绘图颜色来实现,完整代码如下:
library(data.tree) # 修改树生成函数,跟踪路径上的S/F数量并标记目标节点 generate_tree <- function(node, depth, current_S = 0, current_F = 0) { if (depth == 0) { # 标记叶子节点是否符合条件 node$isTarget <- (current_S >= 3 && current_F < 2) return(node) } else { for (outcome in c("S", "F")) { new_S <- current_S + (outcome == "S") new_F <- current_F + (outcome == "F") child <- node$AddChild(name = outcome) # 递归生成子节点,传递当前计数 generate_tree(child, depth - 1, new_S, new_F) # 标记当前节点是否符合条件 child$isTarget <- (new_S >= 3 && new_F < 2) } return(node) } } # 生成带属性的树 root <- Node$new("Start") root <- generate_tree(root, 5) # 设置节点颜色:符合条件的节点为绿色,其余为默认白色 SetGraphStyle(root, node.col = function(node) { if (node$isTarget) return("green") else return("white") }) # 绘制树状图(若需横向展示,可添加参数direction = "lr") plot(root, direction = "lr")
代码说明
generate_tree函数新增current_S和current_F参数,用于跟踪每个节点路径上的成功和失败次数- 每个节点都会被添加
isTarget属性,标记该节点是否满足成功次数≥3且失败次数<2的条件 - 使用
SetGraphStyle自定义节点颜色,根据isTarget的值动态设置绿色或默认色 - 绘图时添加
direction = "lr"参数可以将树状图改为横向(从左到右)展示,更易阅读
内容的提问来源于stack exchange,提问作者stats_noob
相关产品推荐
相关产品推荐

