Combining `expression()` with `\n`
Asked Answered
K

2

7

I have a ggplot where I have used expression(phantom(x) >=80) in the label text to get a proper greater-than-or-equal symbol.

However I also need to have (N=...) immediately underneath:

require(ggplot2)
.d <- data.frame(a = letters[1:6], y = 1:6)

labs <- c("0-9\n(N=10)","10-29\n(N=10)","30-49\n(N=10)", +
   "50-64\n(N=10)","65-79\n(N=10)", expression(phantom(x) >=80))

ggplot(.d, aes(x=a,y=y)) + geom_point() + 
   scale_x_discrete(labels = labs)

enter image description here

How can I combine the expression() with the escape \n ?

Kaseykasha answered 2/11, 2012 at 15:21 Comment(0)
S
14

As @otsaw said in his answer to your earlier question, plotmath (and therefore expression) doesn't allow linebreaks.
However, as a hack, you can use atop to let ≥80 appears on top of (N=10). But as you will soon see it doesn't match with the other labels:

labs <- c("0-9\n(N=10)","10-29\n(N=10)","30-49\n(N=10)", 
          "50-64\n(N=10)","65-79\n(N=10)", 
          expression(atop(phantom(x) >=80, (N==10))))

enter image description here

So, as a further hack, you can pass the other labels as expressions:

labs <- c(expression(atop(0-9,(N==10))),expression(atop(10-29,(N==10))),
          expression(atop(30-49,(N==10))), expression(atop(50-64,(N==10))),
          expression(atop(65-79,(N==10))), expression(atop(phantom(x) >=80, (N==10))))

enter image description here

But of course you have @otsaw solution (using Unicode) that is considerably less wordy:

labs <- c("0-9\n(N=10)","10-29\n(N=10)","30-49\n(N=10)", 
          "50-64\n(N=10)","65-79\n(N=10)", 
          "\u2265 80\n(N=10)")

enter image description here

Star answered 2/11, 2012 at 15:57 Comment(1)
+1 for unicode characters, didn't even know that was possible.Wilke
B
1

Another approach would be to use the recently archived tikzDevice. This creates the plots as tikz which are latex friendly format.

This will allow you to pass any latex expression as a character string to your labels.

It has the added benefit that you can compile the documents with the same preamble as your whole document so that the fonts etc are consistent.

All this can be automated using knitr using opts_chunk$set(dev = 'tikz')

Bacchus answered 5/11, 2012 at 0:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.