directlabels: Adding direct labels to ggplot2 and lattice plots
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.
> 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 = "http://r-forge.r-project.org")
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 his blog: Learning R
offers daily e-mail updates
news and tutorials
on topics such as: visualization (ggplot2
), programming (RStudio
, Web Scraping
) statistics (regression
, time series
) and more...
If you got this far, why not subscribe for updates
from the site? Choose your flavor: e-mail
, or facebook