如何使图例中的标签在R中对齐?

时间:2015-08-16 03:29:17

标签: r plot alignment legend

enter image description here

如图所示,我该如何使这些标签对齐?

我在R中使用传奇。

1 个答案:

答案 0 :(得分:4)

来自?legend

## right-justifying a set of labels: thanks to Uwe Ligges
x <- 1:5; y1 <- 1/x; y2 <- 2/x
plot(rep(x, 2), c(y1, y2), type = "n", xlab = "x", ylab = "y")
lines(x, y1); lines(x, y2, lty = 2)
temp <- legend("topright", legend = c(" ", " "),
           text.width = strwidth("1,000,000"),
           lty = 1:2, xjust = 1, yjust = 1,
           title = "Line Types")
text(temp$rect$left + temp$rect$w, temp$text$y,
     c("1,000", "1,000,000"), pos = 2)

enter image description here

修改

我无法找到一种方法来自动将图例与右侧的线条对齐。但您可以使用text展示位置和选项bty="n"生成图例以删除边框。

## similar to above
x <- 1:5; y1 <- 1/x; y2 <- 2/x
plot(rep(x, 2), c(y1, y2), type = "n", xlab = "x", ylab = "y")
lines(x, y1); lines(x, y2, lty = 2)
temp <- legend("topright", legend = c(" ", " "),
           text.width = strwidth("1,000,000"),
           lty = 1:2, xjust = 1, yjust = 1, bty="n")

text(4, 2,"lbl1")
text(3.9, 1.92,"mylbl2")

enter image description here