Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With this code:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p + geom_point() + geom_text(aes(wt, mpg, label=row.names(mtcars)))

I obtain this graph:

enter image description here

How can I modify the code above so that it only labels point where wt > 4 or mpg > 25, while the rest of the points remain unlabeled.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
605 views
Welcome To Ask or Share your Answers For Others

1 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...