[R] ggplot2: how to label lines?

Jeffrey Spies jspies at virginia.edu
Tue Oct 26 08:02:52 CEST 2010


Hi, all,

Let's say I have some time series data--10 subjects measured 20
times--that I plot as follows:

library(ggplot2)
dat <- data.frame(subject=as.factor(rep(1:10, each=20)),
time=rep(1:20, 10), measure=as.vector(replicate(10, rnorm(20,
mean=runif(1, 0, 15), sd=runif(1, 1, 3)))))
p <- qplot(time, measure, data=dat, colour=subject, geom="line")
p

What would be the preferred way to add a single label to every line?
For instance, labels might be most readable at the beginning, end, or
peak (max value) of every line.  I could do:

p + geom_text(aes(label=subject))

But this gets messy when the labels are longer than single digits;
instead, I want a single label per line. I suppose a dataset could be
put together composed of single points and labels and then layered
atop p, but perhaps there is a more direct method.

Any help would be greatly appreciated,

Jeff.



More information about the R-help mailing list