如何在与“text”一起使用的“bquote”表达式中换行?

问题描述 投票:0回答:3

我想在我的

bquote
环境中添加一条新线,我该怎么做?

我的代码:

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)

我想在等号后有一个新行,所以这应该给出:

VaR_0.99 =

0.03311

and not

    VaR_0.99 = 0.03311

我用线条尝试过,但没有成功:

    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)
r data-visualization plotmath
3个回答
11
投票

例如,使用

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)

enter image description here


9
投票

上面我对提问者的评论中指出了其中一个错误。 R 表达式经过解析,因此它们需要在语法上有效。由于“==”是一个双参数函数,因此它不能是表达式中的最后一项。

phantom
函数用作非打印的占位符。也可能是空字符值 (
""
)。由于没有需要计算的“外部”值,因此我只使用
expression()
而不是
bquote()
作为表达式列表中的第一个参数。

(注意:R 中的表达式表现为列表,因此

c()
成功将语言项附加到单个元素表达式,并且不需要
list()
,事实上在这种情况下是有害的。还有另一个微妙之处
 bquote
不会返回“表达式”类结果,而是返回“调用”。如果需要真正的“表达式”(就像这里的情况一样),则可能需要用
as.expression
包裹它。我见过 R 专家使用
lapply( . , as.expression)
在类似情况下返回表达式列表。)

另一个错误更多的是语义错误,而不是语法错误。您需要为第二个

bquote
表达式提供明确的 y 位置。几乎所有重要的文本参数都支持向量,但 y 值似乎没有隐式的向上(或向下)索引:

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)

enter image description here

我自己过去曾使用过

atop
建议,甚至在 Rhelp 上建议过它,但我认为上面的方法可以更好地推广到三个或更多表达式,并且可以更好地控制定位。
atop
还会默默地减小字体大小,因此,如果您采用嵌套在顶部的路线来执行三个表达式任务,则可能需要使用
atop( atop(..., ...), atop(..., phantom() )
来保持大小统一。

如果您在

adj=0
调用参数列表中包含
text
,您将获得左对齐。在代码中测试了接受的答案。


0
投票

我想要这个,但左对齐。在寻找解决方案后,我最终使用了两个

text()
调用,将文本间隔 0.25 英寸,距顶部 0.25 英寸,无论绘图尺寸如何。

plot(1:100)
r2 <- 40.2
rmse <- 0.6
ll = bquote(paste(italic(R)^2," = ",.(r2),"  RMSE = ",.(rmse)))
val=0.25*diff(par('usr')[3:4])/par('pin')[2]
text(par('usr')[1], par('usr')[4] - val, pos=4, labels=ll)
text(par('usr')[1], par('usr')[4] - 2*val, pos=4, labels="Model A")

Image produced by code

© www.soinside.com 2019 - 2024. All rights reserved.