简体   繁体   中英

How to make labels in the legend align right in R?

在此输入图像描述

As this picture shows, how can I make these labels align right?

I am using legend in R.

From ?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)

在此输入图像描述

EDIT:

I can't find a way to automatically align the legend with the lines on the right. But you may be able to produce a legend using text placement and option bty="n" to remove the border.

## 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")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM