[R-sig-Geo] Plot categorical data from SpatialPolygonsDataFrame in color with label: plot() vs spplot()

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Jun 10 12:00:50 CEST 2010


On Thu, Jun 10, 2010 at 10:47 AM, christiaan pauw <cjpauw at gmail.com> wrote:
> Hi everybody
>
> I have a town map with a polygon for every individual stand. I have
> interview data in a SpatialPolygonsDataFrame (SPDF) for some of them. Now I
> want to print a map in pdf (as large as A0 !)  that displays:
>
> 1. All stands in the town
> 2. The ones we have done interviews with in one of four colours depending in
> the value of a categorical variable (factor) with four levels.
> 3. The stand number (which is also a variable in the data frame)
>
> I have tried using plot() and spplot. With plot I can get 1 and 2 (very
> nicely with thin lines for 1.) With spplot I can get 1. and 3. (labels
> scaled correctly but lines very thick). I include a reproducible example of
> how far I got.
>
> x <- readShapePoly(system.file("shapes/sids.shp", package="maptools"))
> x at data$cat=sample(1:4,length(xx at data[,1]),replace=TRUE)

 what's 'xx'? I'll assume you meant 'x' and carry on...

> x at data$select=sample(0:1,length(xx at data[,1]),replace=TRUE)
> my.select=x[x$select==1,]plot(x,lwd=0.025,main="Whatever")
> plot(my.select[which(my.select$cat==1),],lwd=0.05,col="green",add=TRUE)
> plot(my.select[which(my.select$cat==2),],lwd=0.05,col="grey",add=TRUE)
> plot(my.select[which(my.select$cat==3),],lwd=0.05,col="brown",add=TRUE)
> plot(my.select[which(my.select$cat==4),],lwd=0.05,col="red",add=TRUE)
> text(coordinates(x),x at data$NAME,cex=0.025)
>
> # Everything worked except the last line. Why?
> # I have the colours but not the lables

 You've not given the text() function a character argument!
x at data$NAME is a factor, so I think text() thinks this is your Y
coordinate. Try:

 > plot(x)
 > text(coordinates(x),x at data$NAME,cex=0.25)
 > text(coordinates(x),as.character(x at data$NAME),cex=0.25)

 the first fails horribly (draws numbers at odd places) but the second works.

 I'm not sure if cex=0.025 works since I don't have an electron
microscope handy in order to read it!  There may be limitations on
very small text sizes with some graphics devices. There certainly is
on my eyes...

 Also, you can probably plot the coloured ones in one go. Something like:

 > mypal = c("green","grey","brown","red")
 > plot(my.select,col=mypal[my.select$cat])

there are other ways of mapping values to colours, such as my
colourschemes package [shameless plug!], but this is the simplest.

hope that helps

Barry



More information about the R-sig-Geo mailing list