Add barplots to circles in inner nodes in partykit plotted trees

572 views Asked by At

The partykit package plots barplots at the terminal nodes of trees which gives a visual rendition of the posterior probabilities of the dependent variable classes.

I would like to add those barplots also in the inner nodes, below the standard circles/ellipses. This needs to use a function that is a mixture of node_inner() and node_barplot() to the inner_panel argument of the plot() method.

But those function have pretty complex internals and I'm not sure how to mix the two in order to have to inner plots stacked vertically.

Any ideas?

1

There are 1 answers

0
Achim Zeileis On BEST ANSWER

It's possible, it just doesn't look very appealing. If you want to show the name of the splitting variable and the p-value, it would be better to tweak the mainlab argument of node_barplot. In the answer to Ctree classification with weights - results displayed there is in illustration how to include weights in the title - in a similar fashion you could display splitting variable and p-value.

If you are determined to set up a new panel function that has two subpanels, you need a little bit of grid programming (the graphics system that the plot() method is based on). You need to set up a grid.layout and then go through the resulting viewports.

make_inner_and_barplot <- function(object, ...) {
  function(node) {  
    ## layout
    pushViewport(viewport(layout = grid.layout(nrow = 2, ncol = 1,
      heights = unit(c(0.2, 0.8), "npc"))))
    ## background color
    grid.rect(gp = gpar(fill = "white", col = 0))
    ## circle
    pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1))
    node_inner(object)(node)
    popViewport()
    ## circle
    pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2))
    node_barplot(object, id = FALSE, ...)(node)
    popViewport(2)
  }
}

With the resulting panel function you can then do:

ct <- ctree(factor(cyl) ~ ., data = mtcars, minsplit = 2)
plot(ct, inner_panel = make_inner_and_barplot(ct), tnex = 0.8)

inner and barplot