I have analysed a dataset of GPS points using density.ppp to generate a sort of heatmap of intensity of the points, as shown below:
The result of density.ppp
has a matrix (v) that contains the information, if the points outside of the polygon of interst are changed to NA
before it is plotted then they will not plot. Here is an example of doing this:
library(maptools)
library(sp)
library(spatstat)
xx <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1],
IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
x <- rnorm(25, -80, 2)
y <- rnorm(25, 35, 1 )
tmp <- density( ppp(x,y, xrange=range(x), yrange=range(y)) )
plot(tmp)
plot(xx, add=TRUE)
points(x,y)
tmp2 <- SpatialPoints( expand.grid( tmp$yrow, tmp$xcol )[,2:1],
proj4string=CRS(proj4string(xx)) )
tmp3 <- over( tmp2, xx )
tmp$v[ is.na( tmp3[[1]] ) ] <- NA
plot(tmp)
plot(xx, add=TRUE)