22

I want to add some subscripts and superscripts to my graph labels. I've try expression, but it doesn't work as I wish with new lines (\n). I've try to fix it using paste, but it doesn't work. Below are some of my tries:

par(mfcol=c(1,3))
plot(1,1,main=expression("first line \n second line x"^2))
plot(1,1,main=expression(paste("first line \n second line", "x"^2)))
plot(1,1,main=paste("first line \n second line", expression("x"^2)))

It produces:

enter image description here

In first two pictures the second line is not well centered, in the third one the superscript fails. How to get both centered line and subscripts/superscripts?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Marta Cz-C
  • 759
  • 1
  • 8
  • 18
  • 1
    Additionally: http://stackoverflow.com/questions/15297814/include-text-control-characters-in-plotmath-expressions?lq=1 and http://stackoverflow.com/questions/13198170/combining-expression-with-n on the same subject. – plannapus Dec 12 '13 at 17:21
  • 1
    Upvote: The image immediatly shows you, you've found the right question :) – BurninLeo Aug 14 '14 at 13:19

2 Answers2

28

You can introduce a line break inside an expression:

bquote(atop("first line",
            "second line" ~ x ^ 2))

(I’m using bquote rather than expression here – both work in this case.)

Execute demo(plotmath) for more information and look at the documentation for atop.

boxplot apparently has some trouble interpreting expressions in its title. A simple fix is to plot the title separately:

boxplot(data, main = '')
title(bquote(atop("first line", "second line" ~ x ^ 2)))
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    That's weird: this solution works well with `plot`, but doesn't work with `boxplot`. I've got a message that there was no function called 'atop'. – Marta Cz-C Dec 12 '13 at 20:24
  • @MartaCz-C Curious, you are right. However, the fix is pretty simple – see updated answer. – Konrad Rudolph Dec 12 '13 at 20:27
12

A fast solution is to add some spaces before the word "first".

Since plotmath does not support newlines, you can use mtext to create your lines one by one like this:

plot(1,1)
exp <- 2
Lines <- list(bquote("first line"),bquote("second line x"^2))
mtext(do.call(expression, Lines),side=3,line=1:0)

enter image description here

agstudy
  • 119,832
  • 17
  • 199
  • 261