directlabels: Adding direct labels to ggplot2 and lattice plots

[This article was first published on Learning R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Sometimes it is preferable to label data series instead of using a legend. This post demonstrates one way of using labels instead of legend in a ggplot2 plot.

> library(ggplot2)
> p <- ggplot(dfm, aes(month, value, group = City,
     colour = City)) + geom_line(size = 1) +
     opts(legend.position = "none")
> p + geom_text(data = dfm[dfm$month == "Dec",
     ], aes(label = City), hjust = 0.7, vjust = 1)
directlabel-006.png

The addition of labels requires manual calculation of the label positions which are then passed on to geom_text(). If one wanted to move the labels around, the code would need manual adjustment – label positions need to be recalculated..

This problem is easily solved with the help of directlabels package by Toby Dylan Hocking that “is an attempt to make direct labeling a reality in everyday statistical practice by making available a body of useful functions that make direct labeling of common plots easy to do with high-level plotting systems such as lattice and ggplot2″.

> install.packages("directlabels", repos = "http://r-forge.r-project.org")
> library(directlabels)

The above plot can be reproduced with one line of code.

> direct.label(p, list(last.points, hjust = 0.7,
     vjust = 1))

In addition to several predefined positioning functions, one can also write their own positioning function. For example, placing the rotated labels at the starting values of each series.

> angled.firstpoints <- list("first.points",
     rot = 45, hjust = 0, vjust = -0.7)
> direct.label(p, angled.firstpoints)
directlabel-011.png

I agree with the author’s conclusion that the directlabels package simplifies and makes more convenient the labeling of data series in both lattice and ggplot2.

Thanks to Baptiste for bringing this package to my attention.

To leave a comment for the author, please follow the link and comment on their blog: Learning R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)