Search code examples
rrpartrattle

using greek letters with subscripts for labels in rpart.plot or fancyRpartPlot?


I have the following MWE:

library(rpart.plot)
library(rpart)

set.seed(1234)
df <- data.frame(nu = c(rnorm(mean = 1, n = 100), rnorm(mean = 2, n = 50)), rho = c(rnorm(n = 50),rnorm(sd=2,n=100)), cl = c(rep("TRUE",100), rep("FALSE",50)))
names(df)[-3] <- c(expression(nu),expression(rho))

The above did not work, so I used the unicode fonts:

names(df)[-3] <- c("\u03BD","\u03C1")

So I use the following from the rpart package and then plot using rpart.

tree <- rpart(cl~., data = df)
rpart.plot(tree, type = 4, extra = 0, branch.lty = 3, box.palette = "RdYlGn")

I get:

rpart.plot without subscripts that works

However, my next objective is to add subscripts to nu and rho.

I tried:

names(df)[-3] <- c(expression("\u03BD"[1]) , expression("\u03C1"[2]))

tree <- rpart(cl~., data = df)
rpart.plot(tree, type = 4, extra = 0, branch.lty = 3, box.palette = "RdYlGn")

But

rpart.plot(tree, type = 4, extra = 0, branch.lty = 3, box.palette = "RdYlGn")

gives: rpart.plot with subscripts

The same issue arises with rattle's ``fancyRplot`:

 fancyRpartPlot(tree, caption = NULL)

that yields:

fancyRpartPLot with subscript

Is there a way to include subscripts in rpart.plot or fancyRpartPlot?


Solution

  • rpart.plot() doesn't seem to support the expression() notation. However, you can use the Unicode ₁ (subscript 1) and ₂ (subscript 2) characters, \u2081 and \u2082.

    names(df) <- c("\u03BD\u2081", "\u03C1\u2082", "cl")
    tree <- rpart(cl~., data = df)
    rpart.plot(tree, type = 4, extra = 0, branch.lty = 3, box.palette = "RdYlGn")
    

    enter image description here