Plot a Legend Outside of the Plotting Area in Base Graphics

Plot a legend outside of the plotting area in base graphics?

Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty='L' you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

 set.seed(1) # just to get the same random numbers
par(xpd=FALSE) # this is usually the default

plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L')
# this legend gets clipped:
legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

# so turn off clipping:
par(xpd=TRUE)
legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

Plotting legend outside plot in R

See the help for legend:

The location may also be specified by setting x to a single keyword
from the list "bottomright", "bottom", "bottomleft", "left",
"topleft", "top", "topright", "right" and "center". This places the
legend on the inside of the plot frame at the given location.

So you can place the legend outside the plotting region by giving its coordinates manually:

legend(-0.2, 0.3, legend = c("apple", "orange", "tree"),
bty = "n", xpd=TRUE, mar=c(7,7,7,7), cex = 1, pch = c(10, 15, 1))

placing legend outside a dynamically changing plot R

You can use the inset argument in legend.To do so, you need to use legend location as a word. In your case, "topleft". This way, you do not need to provide specific location based on your "y".

The inset argument allows you to offset the legend. In the present case, the y is offset by -0.03.

I also use par(xpd=TRUE)to expand the allowed plotting space. Finally, I also changed the font size to produce the following charts.

par(xpd=TRUE)
legend("topleft", legend=bquote(paste("Selected Prior: ",bold('PN'[10])," = ", .(round(S,3)))), ## Legend
pch = 21,cex=1,pt.bg="green", col="red", pt.cex=2, bty="n", inset=c(0,-0.03))

Sample Image
Sample Image

Adding a legend to the outside of a multiple graph plot in R

?par, look for xpd:

A logical value or NA. If FALSE, all plotting is clipped to the plot region, if TRUE, all plotting is clipped to the figure region, and if NA, all plotting is clipped to the device region. See also clip.

Use xpd=NA so the legend is not cut off by the plot or figure region.

legend(x="topright",inset=c(-0.2,0),c("4 year moving average",
"Simple linear trend"),lty=1,col=c("black","red"),cex=1.2, xpd=NA)

Results:
legend outside plot

Hiding the Legend in this Graph

This should work:
plot(GA, legend = FALSE)

P.S, if you are not familiar with a package function I always find it helpful to look up the R-documentation in the console using ??GA::plot



Related Topics



Leave a reply



Submit