[R-gui] ggraphics and retrieving mouse coordinate as npc coordinates

john verzani jverzani at gmail.com
Mon Dec 28 03:44:37 CET 2009


Mark Heckmann <mark.heckmann <at> gmx.de> writes:

> 
> Hi all,
> 
> i tried to retrieve the mouse coordinates from a ggraphics widget  
> using a handler. With base graphics system it works fine, but using  
> grid, the returned values do not make sense to me. How can I transform  
> the returned values to e.g. npc coordinates?
> 
> 	library(RGtk2)
> 	library(gWidgets)
> 
> 	w = gwindow("ggraphics example")
> 	g = ggraphics(cont=w, expand=T)
> 	size(g) <- c(900,900)
> 	Sys.sleep(1)
> 	print(grid.rect())
> 
> 	addHandlerClicked(g, handler = function(h,...) {
>    		x <- h$x; y <- h$y
> 		print(c("pressed at:", c(x,y)))
> 	})	
> 

There are two ways. The first is to mimic the handler call in gWidgetsRGtk2
skipping the call to pltToUsr:


f <- function(h,...) {
  theArgs <- list(...)
  w <- theArgs[[1]]
  e <- theArgs[[2]]
  allocation <- w$GetAllocation()
  xclick <- e$GetX()
  yclick <- e$GetY()
  x <- xclick/allocation$width
  y <- 1 - (allocation$height - yclick)/allocation$height
  print(c(x,y))
}

addHandler(g, signal="button-press-event", handler =f)

(Changing print(c(x,y)) as needed.)

The other is to invert this function which is what converts the (x,1-y) value
above into the output of the handler:

pltToUsr <- function(x,y) {
      plt <- par("plt"); usr = par("usr")
      c( (usr[2]-usr[1])/(plt[2]-plt[1])*(x - plt[1]) + usr[1],
         (usr[4] - usr[3])/(plt[4] - plt[3])*(y - plt[3]) + usr[3]
       )
}



Hope that helps!

> Thanks and merry X-mas
> Mark
> 
> –––––––––––––––––––––––––––––––––––––––
> Mark Heckmann
> Dipl. Wirt.-Ing. cand. Psych.
> Vorstraße 93 B01
> 28359 Bremen
> Blog: www.markheckmann.de
> R-Blog: http://ryouready.wordpress.com
>



More information about the R-SIG-GUI mailing list