partykit:当包含不等回归器的名称长度时,在终端节点中对齐文本

问题描述

我正在尝试将终端节点的美学编辑为:

  1. 增加框的大小,以便将全名列在其中。

  2. 如果可能,在存在不等回归变量名称长度的情况下对齐内部文本以生成终端节点的类似表格的视图。

下面我列出了我的尝试,使用 gp 选项 (fontsize = 10,Boxwidth = 10),但我怀疑我使用了错误的美学选项。

mysummary 函数this question 中受到高度启发。


library("partykit")

set.seed(1234L)
data("PimaIndiansDiabetes",package = "mlbench")
## a simple basic fitting function (of type 1) for a logistic regression
logit <- function(y,x,start = NULL,weights = NULL,offset = NULL,...) {
                  glm(y ~ 0 + x,family = binomial,start = start,...)}


## Long name regressors
PimaIndiansDiabetes$looooong_name_1 <- rnorm(nrow(PimaIndiansDiabetes))
PimaIndiansDiabetes$looooong_name_2 <- rnorm(nrow(PimaIndiansDiabetes))
## Short name regressor
PimaIndiansDiabetes$short_name <- rnorm(nrow(PimaIndiansDiabetes))


## set up a logistic regression tree
pid_tree <- mob(diabetes ~ glucose        + 
                          looooong_name_1 +
                          looooong_name_2 +
                          short_name      | 
                          pregnant + pressure + triceps + insulin +
                          mass + pedigree + age,data = PimaIndiansDiabetes,fit = logit)

## Summary function from: https://stackoverflow.com/questions/65495322/partykit-modify-terminal-node-to-include-standard-deviation-and-significance-of/65500344#65500344
mysummary <- function(info,digits = 2) {
  n <- info$nobs
  na <- format(names(coef(info$object)))
  cf <- format(coef(info$object),digits = digits)
  se <- format(sqrt(diag(vcov(info$object))),digits = digits)
  t <- format(coef(info$object)/sqrt(diag(vcov(info$object))),digits = digits)

  c(paste("n =",n),paste("Regressor","beta","[","t-ratio","]"),paste(na,cf,t,"]")
  )
}

#plot tree
plot(pid_tree,terminal_panel = node_terminal,tp_args = list(FUN = mysummary,fill = c("white")),gp = gpar(fontsize = 10,Boxwidth = 10,## aparently this option doesn't belonw here,margins = rep(0.01,4))) ## neither this does.


这是我得到的:

enter image description here

但我想得到如下内容

enter image description here

非常感谢。

解决方法

一个简单而基本的解决方案是使用等宽字体,如 Courier 或 Inconsolata:

plot(pid_tree,terminal_panel = node_terminal,tp_args = list(FUN = mysummary,fill = "white"),gp = gpar(fontfamily = "inconsolata"))

tree with inconsolata text

除了这个简单的基于文本的表格之外,您还可以生成更复杂的表格,例如,通过 ggplot2gtable,如下图所示:Seibold,Hothorn,Zeileis (2019 )。 “具有全局加性效应的广义线性模型树。” 数据分析和分类的进展13,703-725。 doi:10.1007/s11634-018-0342-1

palmtree with custom table

代码有点复杂,但可以在文章的复制材料中找到。具体来说,你需要这两个文件: