Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rpart plot text shorter

Tags:

r

rpart

I am using the prp function from the rpart.plot package to plot a tree. For categorical data like states, it gives a really long list of variables and makes it less readable. Is there any way to wrap text to two or more lines if exceeds some length?

like image 313
Yoki Avatar asked Oct 21 '22 11:10

Yoki


1 Answers

Here's an example that wraps long split labels over multiple lines. The maximum length of each line is 25 characters. Change the 25 to suit your purposes. (This example is derived from Section 6.1 in the rpart.plot vignette.)

tree <- rpart(Price/1000 ~ Mileage + Type + Country, cu.summary)

split.fun <- function(x, labs, digits, varlen, faclen)
{
    # replace commas with spaces (needed for strwrap)
    labs <- gsub(",", " ", labs)
    for(i in 1:length(labs)) {
        # split labs[i] into multiple lines
        labs[i] <- paste(strwrap(labs[i], width=25), collapse="\n")
    }
    labs
}

prp(tree, split.fun=split.fun)
like image 109
Stephen Milborrow Avatar answered Nov 03 '22 21:11

Stephen Milborrow