Skip to content

Labelling panels in R

August 21, 2012

R is great for making graphics! You have an infinite amount of control over your plots, the only limits being your imagination (and perhaps your R coding ability). Some things are easy to do, others not quite so easy of course. One of the trickier parts, thats not limited to R, is positioning labels on a figure. What do I mean? Well, quite often in journals or where ever you have one figure thats split into multiple panels, easy showing something different (e.g. Figure 1a shows the relationship between miles per gallon and displacement; Fig 1b shows the relationship between mpg and the number of carburettors). Quite often in these situations it can be difficult to get the label (the “a” or the “b”) in the same location relative to the figure region. Which can look crappy. It can be time consuming to get it right.

data(mtcars)
par(mfrow=c(1,2), mai=c(1,0.8,0.3,0.2))
plot(mpg ~ disp, mtcars)
text(420, 31, "a")
plot(mpg ~ carb, mtcars)
text(7.8, 31, "b")

Note how much closer to the right hand side the “b” is in comparison with the “a”

Ive written a function that makes it easy and reproducible. One simple line of code that can be repeated for each panel and the problem is solved! Its available from HERE!! Or via sourcing as below:

source("http://db.tt/FxQnTn55")
par(mfrow=c(1,2), mai=c(1,0.8,0.3,0.2)) 
# (mfrow makes the panels, mai manipulates the margin size)
plot(mpg ~ disp, mtcars)
panellab(perc.x=10, lab="a")
plot(mpg ~ carb, mtcars)
panellab(perc.x=10, lab="b")


The function allows you to specify how far from the corner you want your label in percentage of the graph area. You can specify the percentage for x and y individually (arguments perc.x and perc.y, respectively; specifying only perc.x makes perc.y the same as perc.x). You can also specify which corner using the pos argument (pos = “TR” – top right, “TL” – top left, “BR” – bottom right, “BL” – bottom left; defaults to “TR”). You can also specify any other regular text arguments such as col or font.

Hope its useful to someone!!!

Advertisements

From → Uncategorized

2 Comments
  1. Anton permalink

    Thank you. This is a very nice piece of work. Do you know if it will work with ggplot2 and gridExtra?

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

%d bloggers like this: