2017-02-27 192 views
2

我在R中創建了許多圖表,其中每個圖表分別存放在另一個腳本中的數據輸入。我將這些變量放在一個字符串中,並強制使用\n進行換行。這按預期工作,但傳說根本沒有道理。 xjustyjust似乎什麼也沒做。而且,當放置圖例時,在底部,它延伸超過情節的邊緣。任何想法如何能夠正確地將我的傳奇放在劇情的角落?R繪圖圖例中的換行符

這裏可再現的代碼片斷:

plot(c(0,3), c(0,3), type="n", xlab="x", ylab="y") 

a <- 2.3456 
b <- 3.4567 
c <- 4.5678 
d <- 5.6789 

Corner_text <- function(text, location = "bottomright"){ 
    legend(location, legend = text, bty = "o", pch = NA, cex = 0.5, xjust = 0) 
} 
Corner_text(sprintf("a = %3.2f m\n b = %3.2f N/m\UB2\n c = %3.2f deg\n d = %3.2f perc", a, b, c, d)) 
+0

的理由也是空間的一個問題:不要把空格在你的字符串'\ n'後面 – Cath

+1

你真的需要這個盒子嗎? 'legend'假設你有一些「解釋」(如線條或點),如果你沒有(如你的例子),你將在左邊有一個空的空間。在這種情況下,最好使用'text'。 (我可以向你保證'adj'有一些東西;-))。有關詳細信息,請參閱'?legend'。 – Cath

+2

如果你不介意沒有框,你可以嘗試:'text(x = par(「xaxp」)[2] -max(strwidth(strsplit(sprintf(「a =%3.2fm \ nb =%3.2 (n)= f(n)= f(n)= f(n) 「)[1],sprintf(」a =%3.2fm \ nb =%3.2f N/m \ UB2 \ nc =%3.2f deg \ nd =%3.2f perc「,a,b,c,d), adj = c(0,0))',如果分開創建4行,這當然可以簡化 – Cath

回答

3

legend通常是用來說明什麼pointslines(和不同的顏色)表示。因此,在圖例框(bty)內有線條/點應該是的空間。這可能解釋了爲什麼你認爲你的文本沒有左對齊(你的換行符還有空間問題(\n)):如果你在換行符之後放置一個空格,它將成爲下一個第一個字符線,因此文字看起來不合理)。

在你的例子中,你沒有線條或點來解釋,因此,我會使用text而不是legend
要知道軸上的「bottomright」在哪裏,您可以使用圖形參數par("xaxp")par("yaxp")(它給出了第一個和最後一個滴答的值以及軸上滴答的數量)。 在x軸上,從最後一個刻度線開始,您需要向左移動以獲得最寬線條的空間。

R code,它提供了:

# your plot 
plot(c(0,3), c(0,3), type="n", xlab="x", ylab="y") 

# your string (without the extra spaces) 
text_to_put <- sprintf("a = %3.2f m\nb = %3.2f N/m\UB2\nc = %3.2f deg\nd = %3.2f perc", a, b, c, d) 

# the width of widest line 
max_str <- max(strwidth(strsplit(text_to_put, "\n")[[1]])) 

# put the text 
text(x=par("xaxp")[2]-max_str, y=par("yaxp")[1], labels=text_to_put, adj=c(0, 0)) 

# if really you need the box (here par("usr") is used to know the extreme values on both axes) 
x_offset <- par("xaxp")[1]-par("usr")[1] 
y_offset <- par("yaxp")[1]-par("usr")[3] 
segments(rep(par("xaxp")[2]-max_str-x_offset, 2), c(par("usr")[3], par("yaxp")[1]+strheight(text_to_put)+y_offset), c(par("xaxp")[2]-max_str-x_offset, par("usr")[2]), rep(par("yaxp")[1]+strheight(text_to_put)+y_offset, 2)) 

enter image description here

3

如何當你映射aes變量做到這一點使用ggplot2,其中傳說創作是自動的一個例子:

library(ggplot2) 
units <- c('m', 'N/m\UB2', 'deg', 'perc') 
p <- ggplot() + geom_hline(aes(yintercept = 1:4, color = letters[1:4])) + #simple example 
    scale_color_discrete(name = 'legend title', 
         breaks = letters[1:4], 
         labels = paste(letters[1:4], '=', c(a, b, c, d), units)) 

enter image description here

或者情節裏:

p + theme(legend.position = c(1, 0), legend.justification = c(1, 0)) 

enter image description here

或接近的easthetic:

p + guides(col = guide_legend(keywidth = 0, override.aes = list(alpha = 0))) + 
    theme_bw() + 
    theme(legend.position = c(1, 0), legend.justification = c(1, 0), 
     legend.background = element_rect(colour = 'black')) 

enter image description here