tags:

views:

1089

answers:

6

How can I render the value of points in a plot in the plot itself?

Thank you.

+1  A: 

Use text():

plot(1:10, 1:10) 
text(5, 5, "Foo")

and see help(text) for options on placing the text. The function is vectorised so you can also do something akin to

 text(1:10, 1:10, LETTERS[1:10])

if you have vectors of text and positions.

Dirk Eddelbuettel
+9  A: 
Vince
Minor points: You have a typo on line 5 (ploy instead of plot); and I'd be tempted to use format or formatC rather than round, since you want a string returning not a number. Try, e.g., format(y, trim=TRUE, digits=2)
Richie Cotton
Thanks Richie. I thought about format, but I figured round()'s function would be more apparent to a beginner. And paste() will convert to strings.
Vince
+1  A: 

similar to Vince's answer except using ggplot2:

b0 = 2.5; b1 = 2
n = 20
x = rnorm(n, 20, 15)
y = b0 + b1*x + rnorm(n, 0, 15)
dat<-data.frame(x,y)
library(ggplot2)
ggplot(data=dat)+geom_text(aes(x=x,y=y),size=4,label=paste(round(x, 2), round(y, 2), sep=", "))

character size can be changed by altering the size parameter.

Ian Fellows
I should look into ggplot more. It seems to be growing in popularity. I've been using lattice for the hard stuff.
Vince
A: 
x <- 1/3
plot(1,type="none",ann=FALSE)
## text and values only
text(mean(par("usr")[1:2]),mean(par("usr")[3:4])-par("cxy")[2]*2,
     paste("z = ",round(x,2)))
## text, values, and mathematical expressions
text(mean(par("usr")[1:2]),mean(par("usr")[3:4]),
     bquote(x^2==.(round(x,2))))
text(mean(par("usr")[1:2]),mean(par("usr")[3:4])-par("cxy")[2],
     substitute(gamma==value,list(value=round(x,2))))
Stephen
+2  A: 

With ggplot2 you can add both the points and the labels. Putting the aes() in ggplot() has the benefit that this aes() will be the default for all geoms. Hence, in this case you only need to specify the x and values once, but they are used by both geom_point() and geom_text()

The modified code of Ian Fellows would look like this:

b0 <- 2.5
b1 <- 2
n <- 20
dat <- data.frame(x = rnorm(n, 20, 15))
dat$y <- b0 + b1*dat$x + rnorm(n, 0, 15)
dat$text <- with(dat, paste(round(x, 2), round(y, 2), sep=", "))
library(ggplot2)
ggplot(data=dat, aes(x = x, y = y, label = text)) + geom_point() + geom_text(size=4, hjust = 1, vjust = 1)
Thierry
A: 

Maybe this can help as well

# example data
dat <- data.frame(name = sample(letters[1:4],20, replace=T), x1 = rnorm(20,2), x2 = 42+x1*rnorm(20,0,2))
# plot the data
plot(dat$x1,dat$x2)
# use identify to print name for each 'dot' that you click with left mouse
identify(dat$x1,dat$x2,labels=name)
# When done identifying point, click with right mousebutton.

I like this functionality for interactive purposes. Dont know how to achieve this in ggplot though

Andreas