I am making an R plot and want to position several legends side by side (outside the plotting area). The goal is to have legend placement automated.
I am using the approach from here: https://stackoverflow.com/a/34624632/4978977
Here is the example code with two legends to the right of the plot:
dev.off()
par(mar=c(par('mar')[1:3], 0))
plot.new()
l1 <- legend(0, 0, bty='n', c("group A", "group B"), plot=FALSE, pch=c(1, 2), lty=c(1, 2))
l2 <- legend(0, 0, bty='n', c("group A", "group B"), plot=FALSE, pch=c(1, 2), lty=c(1, 2))
w1 <- grconvertX(l1$rect$w, to='ndc') - grconvertX(0, to='ndc')
w2 <- grconvertX(l2$rect$w, to='ndc') - grconvertX(0, to='ndc')
par(omd=c(0, 1-sum(w1, w2), 0, 1))
plot(1:3, rnorm(3), pch=1, lty=1, type="o", ylim=c(-2, 2))
lines(1:3, rnorm(3), pch=2, lty=2, type="o")
legend(par('usr')[2], par('usr')[4], bty='n', xpd=NA, c("group A", "group B"), pch=c(1, 2), lty=c(1, 2))
legend(par('usr')[2]+l1$rect$w, par('usr')[4], bty='n', xpd=NA, c("group A", "group B"), pch=c(1, 2), lty=c(1, 2))
I can get visually the right amount of margin on the right of the plot to get enough space for both legends side by side.
As I understand l1$rect$w
is width of the first legend in "user" coordinates. As you see in the code - I add this value to the left position of the first legend to get second legend position.
The result is that second legend is shifted to the right but not far enough and it overlaps with the text of the first legend.
How to specify the position of the second legend correctly, so that it does not overlap with the first legend?