Splitting axis labels with expressions

爷,独闯天下 提交于 2019-12-22 12:18:25

问题


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


回答1:


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.




回答2:


plot(1:10, ann = FALSE)
 mtext(side = 2, text = "Y Axis", line = 3)
 mtext(side = 2, text = "and something extra", line = 2)

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.



回答3:


example line in ggplot2:

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


来源:https://stackoverflow.com/questions/8985222/splitting-axis-labels-with-expressions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!