R图传奇中的换行符

时间:2017-02-27 11:02:06

标签: r plot legend

我在R中创建了许多绘图,其中包含来自另一个脚本的数据输入,每个脚本都保存在一个单独的变量中。我将变量放在一个字符串中并使用find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -printf "%u\t%s\t%p\n" | sort 强制换行。这符合预期,但传说根本没有道理。 \nxjust似乎没有做任何事情。此外,当放置图例时,例如在直立的情况下,它超出了情节的边缘。我知道如何才能正确地将我的传奇放在情节的角落吗?

这是一个可重现的代码段:

yjust

2 个答案:

答案 0 :(得分:3)

legend通常用于解释pointslines(以及不同颜色)代表的内容。因此,在图例框(bty)内部,应该有一个行/点所在的空间。这可能解释了为什么你认为你的文字没有左对齐(你的换行后你也有空间问题(\n):如果你在换行后放一个空格,它将是你的第一个下一行中的字符,因此文本看起来不合理。)

在您的示例中,您没有要解释的行或点,因此,我会使用text而不是legend
要知道轴上“井下”的位置,可以使用图形参数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

答案 1 :(得分: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))

enter image description here

或在情节内:

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

enter image description here

或者更接近你的东西:

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