[R-sig-Geo] plotting only polygons with points inside.

Roger Bivand Roger.Bivand at nhh.no
Wed Jan 23 08:53:08 CET 2008


On Tue, 22 Jan 2008, Milton Cezar Ribeiro wrote:

> Dear all,
>
> Following a code suggested by Roger Bivand (thanks Roger!), I made a 
> little modification to my own case.
>
> My questions are: (1) how can I plot only those polygons where I have 
> "cnt">0;

subset the SpataialPolygonsDataFrame object with "[", and plot this object 
with add=TRUE;

> (2) how can I define classes of "cnt" (like 1-5; >5 to 20; >20-100) and 
> choose a color for each level of cnt?

Have a look at the classInt package, fixed style. Using cut() (creates 
an *un*ordered factor with indices increasing in encountered levels) is 
less satisfactory than findInterval() - essentially you need a vector of 
colours, a vector of breaks, and

col=cols[findInterval(x, brks, all.inside=TRUE)]

should get you there.

> (3) just suppose that my points have an attribute like species name, how 
> can I generate a new collum like cnt_species with the number of species 
> on each polygon?

Done below (if I understand you correctly), see summary(r.grd.df) - cnt is 
the new variable with one value per spatial entity. Choose a more suitable 
name than cnt when making the data frame.

Roger

>
> Below follow the code wrote by Roger Bivand.
>
> Thanks in advance
>
> Miltinho
>
> ===
> library(sp)
> start.point <- -5
> cco <- c(start.point,start.point)
> csize <- c(1,1)
> n <- abs(cco[1]*2)+1
> cnum <- c(n,n)
> grd <- GridTopology(cco, csize, cnum)
> r.grd <- as(grd, "SpatialPolygons")
>
> set.seed(1)
> x <- rnorm(10000)
> y <- rnorm(10000)
> xy <- SpatialPoints(cbind(x, y))
>
> o1 <- overlay(xy, r.grd)
> res <- numeric(prod(cnum))
> tres <- table(o1)
> ntres <- as.integer(names(tres))
> res[ntres] <- tres
> IDs <- sapply(slot(r.grd, "polygons"), function(x) slot(x, "ID"))
> resdf <- data.frame(cnt=res, row.names=IDs)
> r.grd.df <- SpatialPolygonsDataFrame(r.grd, resdf)
> spts <- list("sp.points", xy, pch=".", col="black")
> spplot(r.grd.df, "cnt", sp.layout=spts)
>
>
>
> para armazenamento!
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no




More information about the R-sig-Geo mailing list