Expression and new line in plot labels [duplicate]
Asked Answered
G

2

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?

Galloway answered 12/12, 2013 at 16:50 Comment(2)
Additionally: #15298314 and #13198670 on the same subject.Clemmy
Upvote: The image immediatly shows you, you've found the right question :)Bypass
C
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)))
Concentration answered 12/12, 2013 at 17:13 Comment(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'.Galloway
@MartaCz-C Curious, you are right. However, the fix is pretty simple – see updated answer.Concentration
D
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

Descendant answered 12/12, 2013 at 17:16 Comment(1)
I think I've seen this somewhere before...! (it is still a great answer)Gallbladder

© 2022 - 2024 — McMap. All rights reserved.