24

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)

Manually added fake labels to qplot

0

2 Answers 2

28

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 For highlighting that it often makes sense to label only a subset, e.g. the outliers.
14

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

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.