how to geom_text() a subset of data

3,337 views
Skip to first unread message

wong, honkit (Stephen)

unread,
Mar 14, 2012, 3:10:45 PM3/14/12
to ggp...@googlegroups.com
Dear All,
Let's say I have a following geom_point() plot, instead of labeling all the
points using geom_text(),
I only want to label a subset of points, how do I do that?

p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))+geom_point()
p + geom_text()

Thanks!

WONG, Hon-Kit (Stephen)

Dennis Murphy

unread,
Mar 14, 2012, 6:35:34 PM3/14/12
to wong, honkit (Stephen), ggp...@googlegroups.com
Hi:

On Wed, Mar 14, 2012 at 12:10 PM, wong, honkit (Stephen)
<hon...@stanford.edu> wrote:
> Dear All,
> Let's say I have a following geom_point() plot, instead of labeling all the
> points using geom_text(),
> I only want to label a subset of points, how do I do that?

Define a subset data frame that contains the x and y coordinates
(possibly modified to correspond to the desired label locations) and
the text labels and use that as input to geom_text(). You also need to
remove the label = argument from the ggplot() call and leave it for
geom_text():

mtsub <- mtcars[sample(seq_len(nrow(mtcars)), 10), ]
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
geom_text(data = mtsub, aes(x = wt + 0.1, label =
rownames(mtsub)), hjust = 0, size = 4)

I just offset the x value by 0.1 and pushed the label to the right of
the point rather than in the center just for illustration.

Dennis

>
> p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))+geom_point()
> p + geom_text()
>
> Thanks!
>
> WONG, Hon-Kit (Stephen)
>

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

Reply all
Reply to author
Forward
0 new messages