Search code examples
rresizealignmentlegend

R how to make legend position independent from graph size


Here is my code; basically I am putting four graphs on the same plot device and putting a legend on each. [edit: I am working with RStudio]

dev.new()
par(mfrow=c(2,2), oma=c(0,0,2,0))

#plot1
plot(parameters...)
par(new=TRUE)
plot(parameters, col="red")
legend("bottomright", c("seed match", "background"), bty="n", lty=c(1,1),
    col=c("red","black"), cex=0.8, inset=0)

#plot2
plot(parameters...)
par(new=TRUE)
plot(parameters..., col="red")
legend("bottomright", c("seed match", "background"), bty="n", lty=c(1,1),
    col=c("red","black"), cex=0.8,inset=0)

#etc. same for plot2 and plot 3

title("bla bla bla", outer=TRUE)

I have two issues with this. (1) even though I specified "bottomright", the legend doesn't seem to be aligned to the bottom right, the wider I resize the graph horizontally, the more space there is between the legend and the right of the graph.

(2) the amount of space the legend occupies is inadequate. I tried modifying cex= but that only takes care of font size, the overall space occupied by the legend remains, meaning that the smaller the font, the bigger the space between lines. I would like the legend to be a little less "spread out".

Illustration This looks sort of OK, although I would like to decrease the space between lines inside the legend: before resizing

But when I resize horizontally it doesn't. I would like to tether the legend to the right of the graph. after resizing


Solution

  • (1): As your graphs are all scaled the same way, you could use x and y coordinates to position the legend, not the key words. e.g.:

    legend(x = 0.25, y = 35, c("seed match", "background"), bty="n", lty=c(1,1), col=c("red","black"), cex=0.8, inset=0)
    

    (2): I don't know if there exists a way to manipulate line spacing via legend(), I didn't find one. I always switch to manual generation of the legend via mtext(), abline() and such when the legend has to look really pretty. It is more work but you got control over every aspect of your legend.

    One last comment: I guess you want your graph to like nice not on your screen but on some sort of paper or presentation. I always generate graphs with devices like cairo_ps(), svg() or jpeg() (jpeg only on rare occasions because it is raster, not vector-based). These functions give you more control about your graphs than exporting the R Graphics Device. But the way a graph looks changes with the device, each one needs to be configured separately. Better do it only for the one you are going to use in the end.

    I hope this helps