Search code examples
rboxplotplotmath

Displaying values from a character vector as italic labels in boxplot in R


I want to use a character vector for boxplot names, how can I get these to be displayed as italic?

# get some data
x <- rnorm(1000)

# I want to get this:
labels <- c(expression(italic("One"), italic("Two")))
labels

boxplot(split(x, cut(x,breaks = c(-Inf, 0, Inf))), names = labels)

But using a character vector, such as

sNames <- c("One", "Two")

I've tried bquote(), expression() ...

labels <- bquote(expression(italic(.(sNames))))
labels # but this is length 1, not 2

... and with sapply()

labels <- sapply(sNames, function(x) bquote(expression(italic(.(x)))))
labels

boxplot(split(x, cut(x,breaks = c(-Inf, 0, Inf))), names = labels)

but this doesn't seem to be interpreted as an expression.

Thanks for any help.


Solution

  • Create the following function and use it as shown:

    make.italic <- function(x) as.expression(lapply(x, function(y) bquote(italic(.(y)))))
    
    boxplot(split(x, cut(x,breaks = c(-Inf, 0, Inf))), names = make.italic(sNames))
    

    which gives:

    screenshot