Skip to content
Prev 1013 / 1236 Next

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

Mark Heckmann <mark.heckmann <at> gmx.de> writes:
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!