繁体   English   中英

partykit:在终端节点箱图上方显示终端节点百分位数值

[英]partykit: Displaying terminal node percentile values above terminal node boxplots

我正在尝试使用partykit绘制使用rpart生成的回归树。 假设使用的公式是y ~ x1 + x2 + x3 + ... + xn 我想要实现的是在终端节点中带有箱线图的树,顶部有一个标签,列出分配给每个节点的观测值的y值分布的第10,第50和第90百分位数,即在表示的箱线图上方每个终端节点,我想显示一个标签,如“10th percentile = $ 200,mean = $ 247,90thcentntile = $ 292”。

下面的代码生成所需的树:

library("rpart")
fit <- rpart(Price ~ Mileage + Type + Country, cu.summary)
library("partykit")
tree.2 <- as.party(fit)

以下代码生成终端图,但终端节点上没有所需的标签:

plot(tree.2, type = "simple", terminal_panel = node_boxplot(tree.2,
  col = "black", fill = "lightgray", width = 0.5, yscale = NULL,
  ylines = 3, cex = 0.5, id = TRUE))

如果我可以显示节点的平均y值,那么应该很容易用百分位数来增加标签,所以我的第一步是在每个终端节点上方显示其平均y值。

我知道我可以使用以下代码检索节点(此处为节点#12)中的平均y值:

colMeans(tree.2[12]$fitted[2])

所以我尝试创建一个公式并使用mainlab面板生成函数的mainlab参数来生成包含这个含义的标签:

labf <- function(node) colMeans(node$fitted[2])
plot(tree.2, type = "simple", terminal_panel = node_boxplot(tree.2,
  col = "black", fill = "lightgray", width = 0.5, yscale = NULL,
  ylines = 3, cex = 0.5, id = TRUE, mainlab = tf))

不幸的是,这会生成错误消息:

Error in mainlab(names(obj)[nid], sum(wn)) : unused argument (sum(wn)).

但似乎这是在正确的轨道,因为如果我使用:

plot(tree.2, type = "simple", terminal_panel = node_boxplot(tree.2,
  col = "black", fill = "lightgray", width = 0.5, yscale = NULL,
  ylines = 3, cex = 0.5, id = TRUE, mainlab = colMeans(tree.2$fitted[2])))

然后我在显示的根节点得到正确的平均y值。 我将非常感谢帮助修复上述错误,以便显示每个单独终端节点的平均y值。 从那里开始,它应该很容易添加到其他百分位并很好地格式化。

原则上,你走在正确的轨道上。 但是如果mainlab应该是一个函数,它不是node的函数,而是idnobs的函数,参见?node_boxplot 您还可以使用整个树的fitted数据,更轻松地为所有终端节点计算均值表(或某些分位数):

tab <- tapply(tree.2$fitted[["(response)"]],
  factor(tree.2$fitted[["(fitted)"]], levels = 1:length(tree.2)),
  FUN = mean)

然后你可以通过舍入/格式化为绘图做准备:

tab <- format(round(tab, digits = 3))
tab
##           1           2           3           4           5           6 
## "       NA" "       NA" "       NA" " 7629.048" "       NA" "12241.552" 
##           7           8           9          10          11          12 
## "14846.895" "22317.727" "       NA" "       NA" "17607.444" "21499.714" 
##          13 
## "27646.000" 

要将其添加到显示中,请为mainlab编写自己的辅助函数:

mlab <- function(id, nobs) paste("Mean =", tab[id])
plot(tree.2, tp_args = list(mainlab = mlab))

在此输入图像描述

暂无
暂无

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

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