How to have a new line in a `bquote` expression used with `text`?

浪子不回头ぞ 提交于 2019-11-30 03:10:19

问题


I want to have a new line in my bquote envrionment, how can I do this?

my code:

test<-c(1,2,3,4,4.5,3.5,5.6)
test2<-0.033111111
plot(test,c(1:length(test)))

segments(4,0,4,23,col="red",lwd=2)
text(5, 4.5, labels = bquote(Qua[0.99] == .(round(test2,4))),col="red", cex = 1.4)

And I want to have a new line after the equal sign, so this should give:

VaR_0.99 =

0.03311

and not

    VaR_0.99 = 0.03311

I tried it with lines, but it did not work:

    test<-c(1,2,3,4,4.5,3.5,5.6)
    test2<-0.033111111
    lines<-list(bquote(Qua[0.99] == ),bquote(.(round(test2,4))))
    plot(test,c(1:length(test)))

    segments(4,0,4,23,col="red",lwd=2)
    text(5, 4.5, labels =lines ,col="red", cex = 1.4)

回答1:


One of the errors was noted above. R expressions get parsed so they need to be syntactically valid. Since "==" is a two-argument function it cannot be the final item in an expression. The phantom function serves as a placeholder that is non-printing. Could also have been an empty character value (""). Since there was no "outside" value that needed to be evaluated, I just used expression() rather than bquote() for the first argument in the expression list.

The other one was more a semantic error than a syntactic one. You need to give an explicit y location for the second bquote expression. Pretty much all of the important arguments of text are vector-capable but there doesn't appear to be implicit up-(or down-)indexing for the y values:

test <- c(1, 2, 3, 4, 4.5, 3.5, 5.6)
test2 <- 0.033111111
lines <- c( expression(Qua[0.99] == phantom(0)) ,
           bquote(.(round(test2,4)))
          )
plot(test,c(1:length(test)))

segments(4,0,4,23,col="red",lwd=2)
text(5, c(4.5, 4), labels =lines ,col="red", cex = 1.4)

I have used the atop suggestion myself in the past, even suggesting it on Rhelp, but I think the approach above generalizes better to three or more expressions and allows more control over positioning. atop also silently reduces font sizes, so if you went the nested atop route for a three expression task, it might need to be atop( atop(..., ...), atop(..., phantom() ) to keep the sizes uniform.




回答2:


For instance, using atop:

test<-c(1,2,3,4,4.5,3.5,5.6)
test2<-0.033111111
plot(test,c(1:length(test)))

segments(4,0,4,23,col="red",lwd=2)
text(5, 4.5, 
     labels = bquote(atop(Qua[0.99] == phantom(), .(round(test2,4)))),
     col="red", cex = 1.4)



来源:https://stackoverflow.com/questions/15663535/how-to-have-a-new-line-in-a-bquote-expression-used-with-text

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