8

I'm trying to automatically place a legend box in a plot, but I'm still in trouble with it. I'd like to place the legend box close to the corner of the plot, but with a small padding/margin.

Using predefined positions, like "topright" or "bottomleft", place the legend too close/upon the border of the plot, like here; and I find it amazingly upsetting to keep on trying pixel by pixel to reach a nice placement to the box, as shown here.

I was wondering if there was anyway to position the legend box based on the width of the plot itself, and not on max/min values. Something that would automatically position the legend about p% close to a defined corner. Is there anyway to do so in R? Or even a way to add some padding to predefined positions?

Community
  • 1
  • 1
Rubens
  • 14,478
  • 11
  • 63
  • 92

1 Answers1

13

Use the inset= option to legend

inset: inset distance(s) from the margins as a fraction of the plot region when legend is placed by keyword.

E.g.:

plot(1:10)
legend("topleft","blah",inset=0.05)

If you would like to make sure that the legend is inset the same distance from the corner, dependent on the x:y ratio of your plot, you could do something a little more complicated like:

plot(1:10)
xyratio <- do.call("/",as.list(par("pin")))
inset.amount <- 0.05
legend("topleft","blah",inset=c(inset.amount,inset.amount * xyratio))

This will fall apart when you resize the plot device though.

enter image description here

thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • 1
    If you wanted to "roll your own" you could have tried: `legend(par('usr')[3] +0.1*( par('usr')[4]-par('usr')[3]), par('usr')[4] -0.1*( par('usr')[4]-par('usr')[3]) ,legend="TEST")` – IRTFM Jul 10 '13 at 01:44
  • @DWin I was in fact expecting something like that, but long as `inset` is doing the job, guess it'll suffice. Thanks for the alternative, anyway. (: – Rubens Jul 10 '13 at 01:54
  • 1
    @Rubens - I have updated to show another alternative that will allow you to specify an inset that is scaled to the x/y ratio of the plot. – thelatemail Jul 10 '13 at 02:01
  • @thelatemail And now I'll have to wait and start a bounty to reward your answer! (: Very nice job! Thanks very much! – Rubens Jul 10 '13 at 02:24
  • @Rubens so much for the bounty xD – MichaelChirico Nov 01 '17 at 02:19
  • 3
    @MichaelChirico Like forever, ma non tanto! :D – Rubens Nov 01 '17 at 10:24