2013-03-08 74 views
7

我爲多個數據集生成一個圖。每個數據集都應該有它自己的圖例,這些圖例可能包含希臘字母,圖形符號或者子和超字符。我想在循環中生成圖例文本。在R圖的圖例文本中使用子/上標和特殊字符

Bquote工作正常,如果只有一個圖例文本。如果我嘗試添加additinal傳說的文本,該plotmath-commads迷路了,...

x <- 0:10 
y1 = x * x 
y2 = x * 10 

plot (1,1, type="n", xlab=bquote(Omega), ylab="Y", las=1, xlim=range(x), ylim=range(y1, y2)) 
lines(x, y1, col=1, pch=1, type="b") 
lines(x, y2, col=2, pch=2, type="b") 

# generate legend texts (in a loop) 
legend_texts = c(
    bquote(Omega^2) 
    , bquote(Omega%*%10) 
) 
# Using a single bquote works fine: 
#legend_texts = bquote(Omega^2) 
#legend_texts = bquote(Omega%*%10) 

legend(
    "topleft" 
    , legend = legend_texts 
    , col = c(1:2) 
    , pch = c(1:2) 
    , lty = 1 
) 
+1

+1可重現的例子! – A5C1D2H2I1M1N2O1R2T1 2013-03-08 07:39:52

回答

4

更改 「legend_texts」 到:

# generate legend texts (in a loop) 
legend_texts = c(
    as.expression(bquote(Omega^2)) 
    , as.expression(bquote(Omega%*%10)) 
) 

從幫助頁面?legend, 「傳奇」參數描述爲:

一個字符或表達式向量。長度≥1以出現在圖例中。其他對象將被as.graphicsAnnot強制。

輸出:

enter image description here

+0

這裏有輕度閱讀障礙。幫助頁面讀取「表達式向量」,而不是「表達式向量」。 :) – A5C1D2H2I1M1N2O1R2T1 2013-03-08 07:48:25

6

試試這個:

legend_texts = expression(
    Omega^2, Omega*10) 

legend(
    "topleft" 
    , legend = legend_texts 
    , col = c(1:2) 
    , pch = c(1:2) 
    , lty = 1 
    ) 

我不能告訴你,如果想Omega^10Omega*10Omega%*%10,但他們都將產生可接受的plotmath表達式。

enter image description here

+0

比我一遍又一遍地使用'as.expression'更好。 +1 – A5C1D2H2I1M1N2O1R2T1 2013-03-08 07:45:09

+0

當使用'表達式'函數時,通過用逗號分隔元素來創建一個多值表達式向量。 – 2013-03-08 07:50:05

+0

謝謝。我只是重新閱讀幫助頁面並得出結論。 :) – A5C1D2H2I1M1N2O1R2T1 2013-03-08 07:51:14