[英]Line break in R plot legend
我在R中創建了許多圖,其中包含來自另一個腳本的數據輸入,每個腳本都保存在一個單獨的變量中 我將變量放在一個字符串中並用\\n
強制換行。 這符合預期,但傳說根本沒有道理。 xjust
和yjust
似乎什么也沒做。 此外,當將圖例放置在底部時,它會延伸到圖的邊緣之外。 知道如何才能正確地將我的傳奇放在情節的角落嗎?
這是一個可重現的代碼片段:
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))
legend
通常用於解釋points
或lines
(以及不同顏色)的含義。 因此,在圖例框( 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))
關於如何使用ggplot2
執行此操作的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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.