Add horizontal line to terminal barplots in party / partykit trees

送分小仙女□ 提交于 2019-12-07 02:45:26

The partykit distinguishes "panel" functions and "panel-generating" functions:

  • The former just expect the node of a tree as their sole argument and then draw this node (using grid graphics).

  • 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.

To signal that a function is a panel-generating function, it has to have class "grapcon_generator". Hence

class(node_barplot)
## [1] "grapcon_generator"

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().

Just for completeness: As Achim explained, the class attribute was not correct to indicate that the function has to be passed the whole tree, not just a node. Setting it to class(node_barplot2) <- "grapcon_generator" does the trick.

I slightly tweaked the node_barplot code and added two new arguments to the function: hline and h.gp. The first one specifies where the horizontal line is drawn (a value between 0 and 1). The line is the same across all terminal panels. The second one takes a gpar object used to style the drawn line. The function is named node_barplot2, you can find the gist here. The code that draws the line is at the end.

Example

library(devtools)
source_gist("0313362f0c84b21625bd")

plot(fit, terminal_panel = node_barplot2, 
     tp_args= list(hline = .8, 
                   h.gp = gpar(lwd=4, col="blue")))

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!