You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改partykit中ctree的终端节点以优化决策树可视化

解决partykit包ctree终端节点文本显示问题

一、自定义终端面板隐藏“n = xx”部分

partykit的绘图系统支持完全自定义终端节点内容,你可以基于默认面板函数修改,去掉样本量的显示:

1. 针对默认文本型终端节点

如果使用默认的文本终端面板,可自定义函数只保留响应变量的统计信息:

# 自定义终端面板函数,移除样本量行
custom_text_terminal <- function(obj, ...) {
  node_terminal(obj, 
                fun = function(node) {
                  stats <- node$info$statistics
                  if (is.null(stats)) return("")
                  # 根据响应变量类型调整显示内容
                  if (inherits(stats, "table")) {
                    # 分类变量:显示类别占比
                    paste0(names(stats), ": ", round(stats/sum(stats)*100, 1), "%", collapse = "\n")
                  } else if (is.numeric(stats)) {
                    # 连续变量:显示均值和标准差
                    paste0("均值: ", round(stats["mean"], 2), "\n标准差: ", round(stats["sd"], 2))
                  } else {
                    ""
                  }
                },
                id = FALSE, ...)
}

# 应用自定义面板绘图
plot(your_tree, terminal_panel = custom_text_terminal, gp = gpar(fontsize = 7))

2. 针对箱线图型终端节点

如果使用node_boxplot,可以关闭默认的样本量标题,自定义显示内容:

# 自定义箱线图终端面板,隐藏样本量
custom_boxplot_terminal <- function(obj, ...) {
  node_boxplot(obj, 
               main = function(node) "", # 移除默认的"n=xx"标题
               id = FALSE, ...)
}

plot(your_tree, terminal_panel = custom_boxplot_terminal, gp = gpar(fontsize = 7))

二、其他优化可视化的方法

除了修改终端文本,还可以从根源和布局上优化:

  • 剪枝缩小树规模:未剪枝的树节点过多是核心问题,用prune()函数剪枝:
# 基于AIC准则剪枝
pruned_tree <- prune(your_tree, method = "AIC")
plot(pruned_tree)
  • 使用紧凑布局:通过type参数选择更紧凑的布局,减少节点间距:
plot(your_tree, type = "compact", terminal_panel = custom_text_terminal, gp = gpar(fontsize = 7))
  • 调整节点尺寸:通过gp参数缩小节点的宽高,适配小字体:
plot(your_tree, terminal_panel = custom_text_terminal, 
     gp = gpar(fontsize = 7, box.width = 0.4, box.height = 0.25))

内容的提问来源于stack exchange,提问作者Linus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:18:54