zoom to point

by Jamie M. Kass

I do lots of spatial stuff in R. I used to be an ArcGIS guy in the days when I was a GIS Analyst, but I made the switch when I got (back) to grad school. At first, the only reason I shrugged off ESRI products was because I thought I’d be cooler if I used only open source software. I did become cooler, much cooler. And I retain my love/hate relationship with ArcGIS, mostly because I am accustomed to it (I use ArcGIS operating on muscle memory). But there is arguably one thing that GIS software is superb for: panning and zooming quickly around big maps. I find myself using R for nearly all the spatial stuff I do now, but there are still times when I grudgingly have to trudge back to ArcGIS for ease of navigation. Zooming and navigating around on plots in R is not exactly smooth.

That’s why I wrote a little function to zoom to points on a raster. It’s not multi-purpose by any means, but you can hack it to do anything you want. This makes examining raster values around points a cinch.

# r = raster to zoom into
# p = single point coordinates you want to zoom to, 
# as vector c(lat, lon)
# rad = radius of zoom in units of projection

zoom2pt <- function(r, pt, rad) {
  ext <- c(pt[1]-rad, pt[1]+rad, pt[2]-rad, pt[2]+rad)
  plot(r, ext=ext)
  points(pt[1], pt[2])
}

And here’s another simple function that zooms around to multiple points. Just press Return to go to the next one. This only works on dataframes of point locations, and will error if you input just one set of coordinates. Keep in mind that if you escape the function before it finishes, par(ask=TRUE) will remain on — just set it to FALSE.

# r = raster to zoom into
# p = multiple point coordinates you want to zoom to, 
# as dataframe with columns (lon, lat)
# rad = radius of zoom in units of projection

zoomAround <- function(r, pts, rad) {
  np <- nrow(pts)
  par(ask=TRUE)
  for (i in 1:np) {
    zoom2pt(r, pts[i,], rad)
  }
  par(ask=FALSE)
}