 parvin karimi - 4 years ago 124
R Question

# placing legend outside a dynamically changing plot R

In my R code below, I have two situations each resulting in a different plot depending on

`S`
being larger OR smaller than
`1`
. I was wondering how I can take out (move up) the current legend and put it above the plot at the same place for either of the resulting plots?

Note: Due to Y axis being on log-scale, I have used
`10^par('usr')`
but I need to add a number to
`10^par('usr')`
(i.e.,
`(10^par('usr')) + a number`
) such that "this number" puts the legend in the exact same place above either of the resulting plots?

Here is the R code:

`````` S <- 0.25    ### !!!  Change this to "24" and see how another plot will appear !!! ###
Ur <- c(0.25, 24, 16)

if(S>=1){

plot(1, 1, type = "n", xlim = c(0,1.5), ylim = c(1/3, 100), log="y", bty="n", ann=F, axes=F, xaxs="i")

axis(side=1, at = seq(0,1.5,.25),labels = c("0",".25",".5",".75","1","1.25","1.5"))
axis(side=2, at = c(1/3, 1, 3, 10, 30, 100),labels = c("1/3", "1", "3", "10", "30", "100"),las=1)

}else{

plot(1, 1, type = "n", xlim = c(0,1.5), ylim = c(.01, 3), log="y", bty="n", ann=F ,axes=F, xaxs="i")

axis(side=1, at = seq(0,1.5,.25),labels = c("0",".25",".5",".75","1","1.25","1.5"))
axis(side=2, at = c(.01, 1/30, 1/10, 1/3, 1, 3),labels = c("1/100", "1/30", "1/10", "1/3", "1", "3"),las=1)
}

legend(0, (10^par("usr")), bquote(paste("Selected Prior:              ",bold('PN')," = ", .(round(S,3)))), ## Legend
pch = 21,cex=2,pt.bg="green", col="red", pt.cex=2.8, bty="n")
`````` P Lapointe
Answer Source

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')," = ", .(round(S,3)))), ## Legend
pch = 21,cex=1,pt.bg="green", col="red", pt.cex=2, bty="n", inset=c(0,-0.03))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download