2017-02-27 334 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