R: plotting decision tree labels leaves text cut off

rhae66 picture rhae66 · May 7, 2013 · Viewed 23.5k times · Source

(I'm still learning how to handle images in R; this is sort of a continuation of rpart package: Save Decision Tree to PNG )

I'm trying to save a decision tree plot from rpart in PNG form, instead of the provided postscript. My code looks like this:

png("tree.png", width=1000, height=800, antialias="cleartype")
plot(fit, uniform=TRUE, 
   main="Classification Tree")
text(fit, use.n=TRUE, all=TRUE, cex=.8)
dev.off()

but cuts off a little of the labels for the edge nodes on both sides. this isn't a problem in the original post image, which I've converted to png just to check. I've tried using both oma and mar settings in par, which were recommended as solutions for label/text problems, and both added white space around the image but don't show anymore of the labels. Is there any way to get the text to fit?

Answer

Stephen Milborrow picture Stephen Milborrow · Mar 13, 2014

The rpart.plot package plots rpart trees and automatically takes care of the margin and related issues. Use rpart.plot (instead of plot and text in the rpart package). For example:

library(rpart.plot)
data(ptitanic)
fit <- rpart(survived~., data=ptitanic)
png("tree.png", width=1000, height=800, antialias="cleartype")
rpart.plot(fit, main="Classification Tree")
dev.off()