Santi XGR
Santi XGR

Reputation: 307

how to use multiple fonts in r plot axis-labels?

I'm customizing the x axis labels of a plot. Each label contains several values and several characters, one of which ('x') should be italicized. This code works fine although the content of labels appears only in regular font:

df <- data.frame(sp=c('a', 'b', 'c', 'd', 'e'), n=c(1, 2, 3, 4, 5))
labels <- c()
for(i in 1:nrow(df)){
labels[i] = paste(df$sp[i], '\n(x = ', df$n[i], ')', sep = '')
}
plot(df$n, df$sp, xaxt = 'n')
axis( 1, at = seq( 1, nrow(df) ), labels = labels)

How can I italize character x? This call to substitute for example doesn't work:

substitute(paste(df$sp[i], italic('\n(x = '), df$n[i], ')', sep = ''), list(df$sp=df$sp, df$n=df$n) )

Upvotes: 0

Views: 215

Answers (1)

Richard Telford
Richard Telford

Reputation: 9923

One solution would be to call axis once for each label, and using atop() rather than \n

plot(df$sp, df$n, xaxt = 'n')
axis(1, at = 1:nrow(df), labels = rep("", nrow(df)))
labels <-sapply(1:nrow(df), function(i){
  axis( 1, at = i, line = 2, lty = 0, 
   labels = bquote(atop(.(as.character(df$sp[i])),.("(")~italic(x)~"="~.(i)~")")))
})

Upvotes: 1

Related Questions