29

How can I combine text and math expressions in a plot's title. If I use paste the expression is converted to character. For example I want something like this as a title

$ARL_1$ curve for $S^2$

Thank you

plannapus
  • 18,529
  • 4
  • 72
  • 94
Brani
  • 6,454
  • 15
  • 46
  • 49

3 Answers3

34

You want to read ?plotmath to see how to do this sort of thing. Here is an example:

plot(1:10, main = expression(ARL[1] ~ "curve for" ~ S^2))

The [.] is subscript, whilst ^ gives superscript. The ~ spaces out the parts of the expression as if there were literal spaces.

Edit: normally I would have done:

plot(1:10, main = expression(ARL[1] ~ curve ~ for ~ S^2))

but that throws an error because for is being interpreted as the start of a for() loop call.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • Second will work if you use `expression(ARL[1] ~ curve ~ "for" ~ S^2)`. – Marek Nov 29 '10 at 10:32
  • @Marek: Oh, yes, agreed. But if you are going to do `"for"` you might as well do `"curve for"`, unless `~` and " " are different amounts of space...? – Gavin Simpson Nov 29 '10 at 11:56
  • Of course. It matters in more complicated cases when one needs to mixed more strings. I add it as completeness ;) On other hand you could also use back-ticks `\``. – Marek Nov 29 '10 at 12:28
33

You can also use bquote(paste(...)), which is a little more flexible than expression: you can include variable values (say, the value of x) in the labels with .(x). For example:

x<- 232323
plot(1:10, main = bquote(paste(ARL[1], " curve for ", S^2, "; x=",.(x))))
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
fabians
  • 3,383
  • 23
  • 23
  • 2
    Yes although I generally find that using the plotmath paste function confuses more than it helps. Try > x<- 232323 > plot(1:10, main = bquote(ARL[1]~"curve for"~S^2~";"~x==.(x))) – IRTFM Nov 29 '10 at 15:16
  • +1 Dwin - introducing `paste` is a pain in the but if you get your `,` or `""` in the wrong places... – Gavin Simpson Nov 29 '10 at 15:59
  • @GavinSimpson Yeah, your answer is nicer. But I thought it would be good to point out a more flexible solution in case somebody comes here looking for a more general solution. – fabians Nov 29 '10 at 16:24
  • +1 from me. That comment wasn't a criticism of the substantive point of your answer (`bquote()`), just a point about introducing paste in there if you can avoid it. `bquote()` is underused and very powerful! – Gavin Simpson Nov 29 '10 at 16:41
  • 1
    .. another 1+ from me. I thought bquote was an excellent suggestion and only added a very minor demurral to avoid paste when possible, because it often gets confused with that "other paste". People don't realize it's a different function with different sematics and with no sep argument. – IRTFM Nov 29 '10 at 22:16
4

You can also use latex2exp::TeX to convert TeX to expressions on the fly:

plot(cars, main = TeX("$ARL_1$ curve for $S^2$"))
loki
  • 9,816
  • 7
  • 56
  • 82