2016-10-21 367 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值」的話。 –