3

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.

CCID
  • 1,368
  • 5
  • 19
  • 35

3 Answers3

5

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

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks. I needed to get the expression outside the sapply function. To use without a custom function, `labels <- as.expression(lapply(sNames, function(x) bquote(italic(.(x)))))` – CCID Apr 29 '15 at 14:16
3

Another simple solution is use par() to change the font of the axis.

df <- data.frame(x = rnorm(1000), labels = c(rep("One", 500), rep("Two", 500)))
par(font.axis = 3) # change font of the axis to italic
boxplot(x ~ labels, data = df, yaxt = "n")
par(font.axis = 1) # return to normal font (plain text)
axis(side = 2)
fvfaleiro
  • 183
  • 1
  • 6
1

I think I managed to obtain the desired results, but to be honest, I'm not really sure why it works, and therefore I'm not sure this solution is optimal:

x <- list(a=1:10, b=1:10)
foo <- Vectorize(function(u) eval(parse(text=sprintf("expression(italic(%s))", u))))
boxplot(x, names=foo(names(x)))

Resulting labels

Vincent Guillemot
  • 3,394
  • 14
  • 21