Search code examples
rplotlegend

Legend position in a base-r plot is affected by the size of the initial plot window?


I found that the location of the legend in a base-r plot will change if you stretch the plot window to a different size. What follows are some screenshots of the example plot produced by the codes:

u1=seq(0,1,0.01); v1=(-u1)*sin(2*pi*u1)
u2=seq(0,1,0.01); v2=exp(-u2)*cos(2*pi*u2)

plot(u1, v1, type="l")
lines(u2, v2, col=2, lty=2)
legend("topright", c("line 1", "line 2"), lty=1:2, col=1:2)

First, I plot the figure, zoom it in to approximatedly the Rstudio interface window size. The results look like these: enter image description here enter image description here

Then, I run the same codes, except for that I start with a narrower plot window in the Rstudio interface. enter image description here

Again, zooming the new plot in to roughly the same size as the last one gives the following result: enter image description here

It should be clear from my screenshots that the legend takes up different proportion of the plot because of the change in initial plot window size.

Is there any approach to totally fix the position of the legend? Otherwise I find it difficult to reproduce exactly identical plots.


Solution

  • You can specify the bounding box of the legend in user co-ordinates. This means the legend box will scale with the plotting panel:

    legend(x = c(0.8, 1.04), 
           y = c(0.65, 0.808), 
           legend = c("line 1", "line 2"), 
           lty = 1:2, 
           col = 1:2)
    

    For example:

    enter image description here

    enter image description here

    enter image description here