How to do selective labeling with GGPLOT geom_point()

You can pass a subset argument to a layer. In your case this would require having the rownames as a column, so they are evaluated properly. You will need to explicitly load plyr to get the function . which makes the syntax easy.

# shamelessly using @marius initial code
library(ggplot2)
library(plyr)
mtcars$name <- row.names(mtcars)
p <- ggplot(mtcars, aes(wt, mpg))

p + geom_point() + geom_text(aes(wt,mpg,label=name), subset = .(wt > 4 | mpg > 25))

Supply a data argument to geom_text:

library(ggplot2)
mtcars$name <- row.names(mtcars)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p + geom_point() + 
  geom_text(data=subset(mtcars, wt > 4 | mpg > 25),
            aes(wt,mpg,label=name))

Resulting plot:

plot1

PS: I'm really not a fan of the p + geom() style of constructing ggplots, I'm pretty sure hadley did it in the original ggplot2 book to demonstrate different modifications of the same plot, but people seem to have picked it up and run with it. Here's how I'd do it:

  • Just add the different components of the plot together with +, don't save each intermediate step.
  • Don't bother saving it to a variable unless you really need to, you can still save it to a file if you need to with ggsave()
  • Put all the aesthetics that are going to apply to the whole plot in the first ggplot call, only modify the other things if necessary

My version:

ggplot(mtcars, aes(wt, mpg, label=name)) +
  geom_point() +
  geom_text(data=subset(mtcars, wt > 4 | mpg > 25))

You could just get an extra variable:

carnames <- row.names(mtcars)
carnames[with(mtcars, !(wt > 4 | mpg > 25))] <- ""

p + geom_point() + geom_text(aes(wt,mpg,label=carnames))

Tags:

Plot

R

Ggplot2