Automatically calculate the appropriate insertion value for legends

Is it possible to automatically get the corresponding inset value inset that the left corner of the legend is always outside the upper right corner of the graph?

In the graph below, I had to try a few values ​​for inset manually. It would be nice not to do this manually, since I need to make some graphs.

 graphics.off() windows(width = 5, height = 5) set.seed(42) par(mar = c(5,5,1,10)) plot(rnorm(50,15,5), rnorm(50,15,3), xlim = c(0,30), ylim = c(5,25), pch = 19, col = c("red","blue")) par(xpd = TRUE) legend("topright", inset = c(-.80, 0), pch = 19, col = c("red","blue"), legend = c("LEGEND 1","Second Legend")) 

enter image description here

+6
source share
1 answer

After calling plot before adding legend use par("usr") * to extract the coordinates of the plot area.

Then, instead of positioning the legend using the "keyword" and inset use x and y with the upper right coordinates of the plot area obtained from par("usr") . Adjust x with a suitable ratio.

 coord <- par("usr") legend(x = coord[2] * 1.05, y = coord[4], pch = 19, col = c("red", "blue"), legend = c("LEGEND 1", "Second Legend")) 

enter image description here


And just for fun, a more confusing alternative.

After plot ting, call legend with the topright position, but without building it on the device ( plot = FALSE ) and assign an object to it.

Retrieve the left x and top y coordinate of the legend window and its width (see the "Value" section in ?legend ) to be used in x and y in legend :

 leg <- legend("topright", pch = 19, col = c("red", "blue"), legend = c("LEGEND 1", "Second Legend"), plot = FALSE) legend(x = (leg$rect$left + leg$rect$w) * 1.05, y = leg$rect$top, pch = 19, col = c("red", "blue"), legend = c("LEGEND 1", "Second Legend")) 

enter image description here


* From ?par

usr A vector of the form c(x1, x2, y1, y2) giving the extrema of the user coordinates of the construction area.

The location calculations that are performed when specifying the inset parameters are actually based on par("usr") (see line 188-199 in the legend code ).

+4
source

Source: https://habr.com/ru/post/1014742/


All Articles