2016-10-21 362 views
1

我想使用bquote来绘制图例,但是在我的图例中添加两行时出现问题。例如:使用bquote在R中的两行中的图例

这工作:

plot(1:10) 
r2=0.99 
legend("topleft",legend=bquote(R^{2} ~ "=" ~.(r2)),bty = "n") 

enter image description here

但是,如果我添加第二行:

plot(1:10) 
r2=0.99 
pval=0.01 
legend("topleft",legend=c(bquote(R^{2} ~ "=" ~.(r2)),paste("P-value =",pval)),bty = "n") 

我的传说载体的整个第一要素是 “扩展” 。这是为什么?

enter image description here

回答

2

这是因为c - 函数不能连接通过bquote返回的对象类型的多个实例。大多数人认为bquote返回R表达式,但它不。它返回调用并且不会连接成列表。您需要将expression函数应用于通过多次调用返回到bquote的项目,以将它们放入“表达式”列表中。这是由托马斯·拉姆利在2005年解释上Rhelp:

legend("topleft",legend=do.call('expression', 
           list(bquote(R^{2} == .(r2)), 
             bquote("P-value" == .(pval))) ), 
        bty = "n") 

enter image description here

有另一种方法,如果你wnat建立这种说法传说,这将允许与c()一起串起表达式。重新定义bquote返回表达式:

bquote2 <- function (expr, where = parent.frame()) 
{ 
    unquote <- function(e) if (is.pairlist(e)) 
     as.pairlist(lapply(e, unquote)) 
    else if (length(e) <= 1L) 
     e 
    else if (e[[1L]] == as.name(".")) 
     eval(e[[2L]], where) 
    else as.call(lapply(e, unquote)) 
    as.expression(unquote(substitute(expr))) 
} 
legend("topleft", 
     legend=c(bquote2(R^{2} ~ "=" ~.(r2)), 
        bquote2(paste("P-value =",pval))), 
     bty = "n") 
+0

啊!我认为它们是语言对象,但我不知道它们可以像这样组合。 –

+0

如果bquote确实返回了一个表达式,我相信你可以使用'c',因为表达式列表是类似列表的对象。我会看看我是否可以对其代码进行修改。 –

1

我设法生产出像你想用什么如下:

textleg <- substitute(atop(paste(R^2==k), 
          plain(P-value)==j), list(k = r2, j=pval)) 
legend("topleft",legend=textleg,bty = "n") 

enter image description here

编辑:

@ 42-提出的建议,添加引号会将我的减号'P值'改为连字符:

enter image description here

+0

是的,这很接近。我仍然对行没有正确对齐感到恼火:P – GabrielMontenegro

+0

(真正的小问题):我同意你努力使用更多的plotmath操作符,但是'P'和'value'之间的负号扩展得比如果你引用了“P值”的话。 –