Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto placement of legend box with margin/padding

Tags:

plot

r

legend

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?

like image 843
Rubens Avatar asked Jul 10 '13 01:07

Rubens


1 Answers

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

like image 164
thelatemail Avatar answered Oct 01 '22 11:10

thelatemail