par(“usr”) is my new friend for inserting legends in plots!

Download R script here.

# Create fake data
x1 <- seq(0.1, 10, 0.5) + rnorm (length(seq(0.1, 10, 0.5)), 0.25)
y1 <- seq(0.1, 10, 0.5) + rnorm (length(seq(0.1, 10, 0.5)), 0.25)

# Plot
plot(x1, y1, pch = 20, cex = 2.5)

# Determine plot boundaries, in units of the data
xmin <- par("usr")[1]
xmax <- par("usr")[2]
ymin <- par("usr")[3]
ymax <- par("usr")[4]

#Now determine the size of the legend you would like to plot.
#Right now the exact location is not important, we just want 
# to know the dimension!  Note that we are treating the legend
#as a variable and we are NOT plotting the legend on the figure!
lgd <- legend(x = mean(c(xmin,xmax)), y =  mean(c(ymin,ymax)),
c("Your data name"), pch = c(20), col = c("black"), plot = F)

# Add legend in the lower right corner:
legend(x = xmax - lgd$rect$w, y =  ymin + lgd$rect$h,
c("Your data name"), pch = c(20), col = c("black"), plot = T)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s