directlabels: Adding direct labels to ggplot2 and lattice plots

January 3, 2010

(This article was first published on Learning R, and kindly contributed to R-bloggers)

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)

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 = "")
> 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)

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


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)