2

I have a plot with a long label containing an expression and I want to split it on two lines.
Adding a "\n" inside the expression the result is not as expected.

ylabel <- expression("A very long label with text and \n 
expression"*(alpha+beta) [ij]*"  A very long label with text and expression")
curve(x^3 - 3*x, -2, 2, xlab=xlabel)

Any help would be appreciated. Thanks

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58

3 Answers3

7

Here is another solution, relying on atop as did @AndresT in his edit. Note that we cannot use control character like \n in an expression, which explains why using something like expression(paste("...\n", alpha[i], "....")) would not produce the desired output.

xlabel <- expression(atop("A very long label with text and expression", 
                          paste((alpha+beta)[ij], "   A very long label ...")))
curve(x^3 - 3*x, -2, 2, sub=xlabel, xlab="")

Note that I used sub instead of xlab to avoid collision with x tick marks.

enter image description here

chl
  • 27,771
  • 5
  • 51
  • 71
4
plot(1:10, ann = FALSE)
 mtext(side = 2, text = "Y Axis", line = 3)
 mtext(side = 2, text = "and something extra", line = 2)

enter image description here

For ggplot2:

set.seed(124)
data1 = data.frame(x=1:10,y=rnorm(10,1))

colnames(data1) = c("X", "Y") 
theme = theme_set(theme_bw()) 

# atop is the function to use in order to get two lines  

 xlab = expression(atop(paste("x Axis"),
            "More text"))
 ylab = expression(atop(paste("y Axis"),
                "Two lines"))




  ggplot(data1, aes(x = X, y = Y))+
            geom_point(shape = 1, color ="black") +
                 xlab(xlab) +  
                 ylab(ylab)


#And adjust the margins with opts.
aatrujillob
  • 4,738
  • 3
  • 19
  • 32
0

example line in ggplot2:

ylab(expression(atop(paste(italic("Saxifraga tridactylites")), 
"individuals per plot")))+
jan
  • 1