R绘图图例中的换行

3
我使用另一个脚本输入数据来创建许多R中的图表,每个变量都存储在不同的变量中。我将变量放入字符串中并强制换行\n。这可以按预期工作,但图例没有对齐。 xjustyjust似乎没有起到任何作用。此外,将图例放置在右下角时,它会延伸到图表的边缘之外。有什么办法可以将我的图例正确地放置在图表角落处并对齐吗?
以下是可重现的代码片段:
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))
2个回答

3
legend通常用于解释pointslines(以及不同的颜色)代表的内容。因此,在图例框(bty)内,有一个空间供线条/点出现。这可能解释了为什么您认为文本不是左对齐的(您在换行(\n)后也有空间问题:如果您在换行后放置空格,则它将成为下一行的第一个字符,因此文本看起来不是对齐的)。
在您的示例中,您没有使用线条或点进行解释,因此我会使用text而不是legend
要知道“bottomright”在坐标轴上的位置,可以使用图形参数par("xaxp")par("yaxp")(它给出您轴上第一个和最后一个刻度线的值以及刻度线数量)。 在x轴上,从最后一个刻度开始,您需要向左移动以留出最宽线的空间。
R代码中,它如下所示:
# 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
使用 ggplot2 来实现这个例子,当您在 aes 中映射变量时,传说的创建是自动完成的:
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))

在此输入图片描述

或者在图表内部:

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

在此输入图片描述

或更接近你的审美观:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接