Thursday, September 23, 2010

How to add text at specified coordinates using ggplot2

Suppose we want to plot x1 vs. y1 contained in a data.frame data, and then add text directly on the graph.

> head(data[,c(1, 10:11)])
  ptid          x1       y1
1    1  0.51666667 2.142857
2    2  0.59999999 2.400000
3    3  1.35000000 3.000000
4    4 -0.08333333 2.142857
5    5          NA 2.500000
6    6  0.96666668 2.666667

Here is a code snippet:

ggplot(data, aes(x1, y1)) + geom_point() + geom_smooth(method="lm") +
       opts(title = "Approach 1") +
       xlab("X1") + ylab("Y1") +
       geom_text(aes(x2,y2,label = texthere), 
          data.frame(x2=2, y2=2.8, texthere="Text Here"))

Note, that we use two different data frames in ggplot() and in geom_text(). The data frame in geom_text() specifies the coordinates (x2=2 and y2=2.8) and the label to place at that point. 


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

Followers

Blog Archive

google analytics