Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use the Identify command with ggplot 2?

Tags:

r

ggplot2

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?

like image 384
Davi Moreira Avatar asked May 10 '12 00:05

Davi Moreira


2 Answers

You may convert your plot, made with ggplot2 to interactive graph by using function ggplotly from package plotly, e.g.:

library(ggplot2)
library(plotly)

# Prepare data
x <- 1:10  
y <- x^3 
names <- paste("Point", LETTERS[x])

# Make a plot with `ggplot` as usual
qplot(x, y, label = names) 

# Convert it to interactive plot
ggplotly()

Then move your cursor over a point of interest and find information about it.

like image 190
GegznaV Avatar answered Sep 30 '22 11:09

GegznaV


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

like image 25
Greg Snow Avatar answered Sep 30 '22 11:09

Greg Snow