Line break in expression()?

百般思念 提交于 2019-11-26 06:40:00

问题


I have the following histogram in R:

hist(alpha,cex.main=2,cex.axis=1.2,cex.lab=1.2,
main=expression(paste(\"Histogram of \",hat(mu), \", Bootstrap samples, Allianz\")))

The titlle is too long, so I want a line break. According to this thread I tried

hist(alpha,cex.main=2,cex.axis=1.2,cex.lab=1.2,
main=expression(paste(\"Histogram of \",hat(mu), \",cat(\"\\n\") Bootstrap samples, Allianz\")))

or

hist(alpha,cex.main=2,cex.axis=1.2,cex.lab=1.2,
main=expression(paste(\"Histogram of \",hat(mu), cat(\"\\n\"),\", Bootstrap samples, Allianz\")))

But both do not work, how can I get a line break in paste()?


回答1:


You can easily use line breaks in regular paste, but this is plotmath paste (actually a different function also with no 'sep' argument) and the (long) ?plotmath page specifically tells you it cannot be done. So what's the work-around? Using the plotmath function atop is one simple option:

expression(atop("Histogram of "*hat(mu), Bootstrap~samples*','~Allianz))

This will break at the comma and center the plotmath expressions. More complicated options are available.

This illustrates plotting to a graphics file. Ironically, the first effort gave me a display that did have your problem with the 'hat' (are those circumflexes?) being cut off and this shows how to increase the margins. The top margin is probably the third number so c(3,3,8,0) might suit you better:

 pdf("test.pdf") ;  par(mar=c(10,10,10,10))
 hist(1:10,cex.main=2,cex.axis=1.2,cex.lab=1.2,
 main=expression(atop("Histogram of "*hat(mu), 
                       Bootstrap~samples * ',' ~Allianz)))
 dev.off() # don't need to restore;  this 'par' only applies to pdf()



回答2:


You are going to need to use something else. I was directed to use mtext and bquote when I was stuck on a similar problem.

alpha = rnorm(1e3)
hist(alpha,cex.main=2,cex.axis=1.2,cex.lab=1.2,main=NULL )

title <- list( bquote( paste( "Histogram of " , hat(mu) ) ) ,
               bquote( paste( "Bootstrap samples, Allianz" ) ) )


mtext(do.call(expression, title ),side=3, line = c(1,-1) , cex = 2 )

In the above example, title (thanks to @hadley) can be simplified to

title <- as.list(expression(paste("Histogram of " , hat(mu)), "Bootstrap samples, Allianz"))



来源:https://stackoverflow.com/questions/18237134/line-break-in-expression

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