问题描述
我正在使用partykit
中的ctree
函数.
I am using the ctree
function from partykit
.
library(rpart)
library(partykit)
fit <- ctree(Kyphosis ~ Age + Number + Start, data=kyphosis)
plot(fit, terminal_panel=node_barplot)
我想在每个条形图中添加一条额外的水平线,以指示整个数据集的平均响应,即此处为0.79.
I want to add an additional horizonal line to each barplot, indicating the average reponse across the dataset, i.e. at 0.79 here.
prop.table(table(kyphosis$Kyphosis))
absent present
0.7901235 0.2098765
方法:我开始修改传递给terminal_panel
参数的node_barplot
函数.但是源代码很长,几乎没有注释.因此,我尝试逐步进行操作,将功能分解为前两行代码(外加一个额外的打印命令).但是,如果我运行它,则对象y
是NULL
并引发错误.
Approach: I started to modify the node_barplot
function that is passed to the terminal_panel
argument. But the source code is very long and comes with almost no comments. So I tried to go step by step, stripping down the function to its first two lines of code (plus an extra print command). However, if I run it, the object y
is NULL
and an error is thrown.
node_barplot2 <- function(obj, ...)
{
y <- obj$fitted[["(response)"]] # first lime from node_barplot source
print(y)
stopifnot(is.factor(y) || isTRUE(all.equal(round(y), y)) || is.data.frame(y))
}
plot(fit, terminal_panel=node_barplot2)
> Error in round(y) : Non-numeric argument in mathematical function
作为其原始代码,我不太了解这里哪里出错了和如何绘制水平线.有什么想法吗?
As its the original code, I do not quite see where I go wrong here and how I could draw the horizontal line. Any ideas?
推荐答案
partykit
区分面板"功能和面板生成"功能:
The partykit
distinguishes "panel" functions and "panel-generating" functions:
-
前者只希望将树的
node
作为其唯一参数,然后绘制该节点(使用grid
图形).
The former just expect the
node
of a tree as their sole argument and then draw this node (usinggrid
graphics).
后者希望将一棵完整的树作为其第一个参数,以及用于自定义的其他参数.它们返回一个面板"函数(仅带有参数node
),其中某些信息(如x和y范围)存储在函数环境中.
The latter expect a full tree as their first argument plus further arguments for customization. They return a "panel" function (with only argument node
) where certain informations like the x and y ranges are stored in the function environment.
要发出一个函数是一个面板生成函数的信号,它必须具有类"grapcon_generator"
.因此
To signal that a function is a panel-generating function, it has to have class "grapcon_generator"
. Hence
class(node_barplot)
## [1] "grapcon_generator"
要向函数中添加某些图形元素,建议复制整个node_barplot
源代码(包括末尾的类分配),然后添加所需的元素,例如,可以使用的水平参考线grid.lines()
.
To add certain graphical elements to the function, I would recommend copying the whole node_barplot
source code (including the class assignment at the end) and then add the elements you need, e.g., a horizontal reference line you can draw with grid.lines()
.
这篇关于在聚会/partykit树中向终端条形图添加水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!