Search code examples
rdecision-treeparty

What is causing this error message when using the party package for a decision tree plot?


I am plotting a decision tree using the party package. When running the plot(tree) function, it plots the decision tree. However, I want to change the font size of the node labels and I am using the following codes:

tree<-ctree(Attrition~MaritalStatus+Age_group,data=traindf1)
plot(tree)
text(tree, cex = 0.5)

When running the last line of code, I get the following error message:

Error in as.double(y) : 
   cannot coerce type 'S4' to vector of type 'double'

I had a look at this post but it seems to relate to another package: Error in as.double(y) : cannot coerce type 'S4' to vector of type 'double'

How can I fix this?


Solution

  • Note that you should probably use partykit instead of party, as the former offers greater flexibility in tuning graphical aspects of the trees. Also be aware that party and partykit should not be used together as ctree objects are different in partykit and party.

    Neither partykit::ctree nor party::ctree have a text method for adding/changing text labels. Perhaps you came across the plot + text syntax when you read about rpart, which is an entirely different R package for recursive partitioning/classification with decision trees.

    Here is a side-by-side example of both methods

    partykit::ctree

    library(partykit)
    fit <- ctree(Ozone ~ ., data = airquality[complete.cases(airquality), ])
    

    enter image description here

    You can change the font size through the gp function parameter, e.g.

    plot(fit, gp = gpar(fontsize = 4))
    

    enter image description here

    rpart::rpart

    library(rpart)
    fit <- rpart(Ozone ~ ., data = airquality[complete.cases(airquality), ])
    plot(fit)
    text(fit)
    

    Here you can change the font size through the cex parameter in text.

    enter image description here