How to nicely annotate a ggplot2 (manual)

I had a similar problem and solved it with JD Long answer. But as a results of ggplot2 updating to version 0.9.0 I noticed that all geom_text()calls rendered somewhat blurred on the plots.

Thanks to kohske I discovered that this code

ggplot(data2, aes(x=time, y=value, group=type, col=type))+
geom_line()+
geom_point()+
theme_bw() +
geom_text(aes(7, .9, label="correct color", color="NA*")) +
geom_text(aes(15, .6, label="another correct color!", color="MVH")) 

plots the geom_text nrow(data2)times!

The correct way for supplying data to geom_text is building a different data.frame holding coordinates, labels and colors for the strings you want to be plotted:

data2.labels <- data.frame(
  time = c(7, 15), 
  value = c(.9, .6), 
  label = c("correct color", "another correct color!"), 
  type = c("NA*", "MVH")
  )

ggplot(data2, aes(x=time, y=value, group=type, col=type))+
  geom_line()+
  geom_point()+
  theme_bw() +
  geom_text(data = data2.labels, aes(x = time, y = value, label = label))

If you use geom_text() instead of annotate() you can pass a group color to your plot:

ggplot(data2, aes(x=time, y=value, group=type, col=type))+
geom_line()+
geom_point()+
theme_bw() +
geom_text(aes(7, .9, label="correct color", color="NA*")) +
geom_text(aes(15, .6, label="another correct color!", color="MVH")) 

So using annotate() it looks like this: alt text http://www.cerebralmastication.com/wp-content/uploads/2010/03/before.png

then after using geom_text() it looks like this: alt text http://www.cerebralmastication.com/wp-content/uploads/2010/03/after.png

Tags:

R

Ggplot2