0

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?

user3115933
  • 4,303
  • 15
  • 54
  • 94
  • As far as I know you cannot use `text` to add/change labels based on a `party` object. The `plot() + text()` syntax is used when plotting `rpart::rpart` dendrograms, perhaps you are confusing two R packages? – Maurits Evers Aug 27 '18 at 06:18
  • See https://www.rdocumentation.org/packages/graphics/versions/3.5.1/topics/text. The function `text` accepts a numeric vector as its first argument i.e. `double`. Your `tree` is probably an S4 object, hence the error. Check the **party** documentation for how to fix this or provide a reproducible example. – BroVic Aug 27 '18 at 06:26

1 Answers1

2

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

Community
  • 1
  • 1
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68