# Labelling panels in R graphics

March 8, 2012
By

(This article was first published on Insights of a PhD student » R, and kindly contributed to R-bloggers)

Labelling a graphics panel in R is easy right?

Sure it is, just use text and define the coordinates.

text(x=5, y=10, "a")

But is there an easy way to get in the same place all the time, even if you have different axis lengths (e.g. 0 to 5 on the x-axis but 0 to 100 on the y-axis)?

I don’t know if there was, but there is now!!!

Copy and run the following code into R and you have the function.

panellab <- function(perc.x, perc.y=perc.x, lab="A", pos="TR", ...){
if(pos=="TR"){
x <- par("usr")[2]-(((par("usr")[2]-par("usr")[1])/100)*perc.x)
y <- par("usr")[4]-(((par("usr")[4]-par("usr")[3])/100)*perc.y)}
if(pos=="TL"){
x <- par("usr")[1]+(((par("usr")[2]-par("usr")[1])/100)*perc.x)
y <- par("usr")[4]-(((par("usr")[4]-par("usr")[3])/100)*perc.y)}
if(pos=="BR"){
x <- par("usr")[2]-(((par("usr")[2]-par("usr")[1])/100)*perc.x)
y <- par("usr")[3]+(((par("usr")[4]-par("usr")[3])/100)*perc.y)}
if(pos=="BL"){
x <- par("usr")[1]+(((par("usr")[2]-par("usr")[1])/100)*perc.x)
y <- par("usr")[3]+(((par("usr")[4]-par("usr")[3])/100)*perc.y)}

text(x, y, labels=lab, ...)
}

To use it, just specify a percentage for the x axis (and y if you want) and a position (e.g. top left, top right…).

panellab(10, lab= "a", pos="TL")

places an a 10% in from the x and y axes in the top left corner

You can add other arguments that text() takes too, such as colours.

panellab(10, lab= "a", pos="TL", col= "red")

the addition of col= “red”, makes the a red.

Simple huh!!

Hope that helps someone!!!