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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With