Legend with dot and string in R

I have two datasets (x1, y1) and (x1, y2). I made a regression for each set and would like to build them on the same plot (with both points and regression lines). Here is my code

x1 <- 1:5 y1 <- x1 + rnorm(x1) y2 <- x1 + 2 + rnorm(x1) fit1 <- lm(y1 ~ x1) fit2 <- lm(y2 ~ x1) plot(x1, y1, pch = 1, ylim = c(min(y1, y2), max(y1, y2)), xlab = "x", ylab = "y") points(x1, y2, pch = 2) abline(fit1, lty = 1) abline(fit2, lty = 2) legend("topleft", legend = c("Line 1", "Line 2"), pch = c(1, 2), lty = c(1, 2)) 

This is what I got.

enter image description here

What I really want in the legend is to make a dot and a line side by side, and not above each other, which should look like this.

enter image description here

Any suggestions are greatly appreciated!

+8
r plot legend
source share
2 answers

I think you can do it like this:

 legend('topright',c('','name'),lty=c(1,NA),pch=c(NA,'X'),bg='white',ncol=2) 

The interval may be a bit uncomfortable, but it separates the line and the symbol. If you intend to have several pairs of line symbols in your legend, be sure to configure them, for example, lty=c(1,2,3,NA,NA,NA) .

+9
source share

Not very elegant, you can easily make two legends side by side. Legend location coordinates can be saved for convenience (for example, in lgd below):

Ex.

 lgd <- legend("topleft", legend = c("", ""), pch = NA, lty = c(1, 2), bty="n") legend(lgd$rect$left+lgd$rect$w, lgd$rect$top, legend = c("Line 1", "Line 2"), pch = c(1,2), bty="n") 

I personally like @CarlWitthoft's solution ...

+2
source share

All Articles