Is there any way to use the Identify command with ggplot 2?
ggplot2, r
Solution
Here is a method that works using only the `grid` and `ggplot2` packages:
library(ggplot2)
library(grid)
x <- 1:10
y <- x^3
qplot(x, y)
downViewport('panel-3-4')
pushViewport(dataViewport(x,y))
tmp <- grid.locator('in')
tmp.n <- as.numeric(tmp)
tmp2.x <- as.numeric(convertX( unit(x,'native'), 'in' ))
tmp2.y <- as.numeric(convertY( unit(y,'native'), 'in' ))
w <- which.min( (tmp2.x-tmp.n[1])^2 + (tmp2.y-tmp.n[2])^2 )
grid.text(w, tmp$x, tmp$y )
If you want a text label instead of the number your could replace `w` in the call to `grid.text` with something like `letters[w]` (or whatever vector of labels you want).
If you are going to be doing several of these then you could wrap this in a function with the last few lines possibly in a loop. You could also add addtional logic to warn if you don't click near a point (like identify does) or to move the label closer or further from the point (this version places the label for the nearest datapoint at the point that you click).
Problem
In this case, everything is ok: ``` x <- 1:10 y <- x^3 plot(x, y) identify(x, y) ``` But, using qplot there are some troubles: ``` x <- 1:10 y <- x^3 qplot(x, y) identify(x, y) ``` Does anybody know a similar command or other way to label specific points in ggplot2 graphs?