Reputation: 690
Is there a way to add labels to each point in a plot? I did this on an image editor just to convey the idea: 1.
The original one was generated with:
qplot(pcomments, gcomments , data = topbtw, colour = username)
Upvotes: 24
Views: 33860
Reputation: 69251
To follow up on Andrie's excellent answer, I frequently employ two methods to add labels to a subset of points on a plot if I need to highlight specific data. Both are demonstrated below:
dat <- data.frame(x = rnorm(10), y = rnorm(10), label = letters[1:10])
#Create a subset of data that you want to label. Here we label points a - e
labeled.dat <- dat[dat$label %in% letters[1:5] ,]
ggplot(dat, aes(x,y)) + geom_point() +
geom_text(data = labeled.dat, aes(x,y, label = label), hjust = 2)
#Or add a separate layer for each point you want to label.
ggplot(dat, aes(x,y)) + geom_point() +
geom_text(data = dat[dat$label == "c" ,], aes(x,y, label = label), hjust = 2) +
geom_text(data = dat[dat$label == "g" ,], aes(x,y, label = label), hjust = 2)
Upvotes: 28
Reputation: 179588
Yes, use geom_text() to add text to your plot. Here is an example:
library(ggplot2)
qplot(mtcars$wt, mtcars$mpg, label=rownames(mtcars), geom="text")
ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars))) + geom_text(size=3)
See the on-line documentation for more information: http://had.co.nz/ggplot2/geom_text.html
Upvotes: 14