Search code examples
rexpressionlabelcut

R expression in multi-labels


I've tried expression and bquote, but can't figure this one out...

I have a continuous variable, call it x. I cut it using cut(...) to create a factor with two levels. I want to label these levels <=10 and >10 but I'd like to use the expression or bquote functions (see plotmath function) to replace the <= with the nicer version:

For example:

x <- rnorm(100,10,5)
x.10 <- cut(x, breaks=c(-Inf,10,Inf), labels=*expression*)

What should I put as the argument to labels so that when I do a barplot of x.10 the labels appear under the bars?

barplot(table(x.10))

barplot(table(x.10))

I can get this to work:

labs <- expression(x <= ...)

plot(1, main=labs)

plot(1, main=labs)

but how to icorporate that into the barplot labels?


Solution

  • Don't try to do expressions as labels to factors. Apply the expression labels on the plot itself, with something like:

    set.seed(42) # always include a seed in questions with randomness
    x <- rnorm(100,10,5)
    x.10 <- cut(x, breaks=c(-Inf,10,Inf), labels = FALSE)
    
    labels <- c(expression(paste(x <= 10)), expression(paste(x > 10)))
    barplot(table(x.10), names.arg = labels)
    

    simple barplot