[R-sig-Geo] plotting polygons of one shapefile in different colors?

Roger Bivand Roger.Bivand at nhh.no
Thu Sep 26 20:57:52 CEST 2013


On Thu, 26 Sep 2013, cyndy-jer wrote:

> Hi Maren -
>
> (yes I'm Cyndy :)
>
> Well, thanks, but yikes!  Surely there is an easier way?  I've gotten pretty
> close by trying to use spplot and rColorBrewer, but I'm not quite there.  I
> have 3 'n' values as part of my SpatialPolygonDataFrame, and somehow the
> below only plots 2 of them,

The easier way is to get to know and like factors, categorical variables 
typically with few levels:

library(sp)
data(meuse.grid)
coordinates(meuse.grid) <- c("x", "y")
gridded(meuse.grid) <- TRUE
class(meuse.grid$ffreq)
library(RColorBrewer)
spplot(meuse.grid, "ffreq1",
  col.regions=brewer.pal(nlevels(meuse.grid$ffreq), "Accent"))

but if the plotted variable is numeric (or integer):

meuse.grid$ffreq1 <- as.integer(meuse.grid$ffreq)
spplot(meuse.grid, "ffreq1", 
col.regions=brewer.pal(nlevels(meuse.grid$ffreq), "Accent"))

you get trouble because at= by default splits the range of the variable 
into 20, cycling the colours. You can fix at=

spplot(meuse.grid, "ffreq1", at=seq(0.5, 3.5, 1),
  col.regions=brewer.pal(nlevels(meuse.grid$ffreq), "Accent"))


but if your variable is really categorical, convert it to factor 
representation, and live gets easier.

Roger

>
> (my dataframe is named 'gimmie')
>
> numpoly=length(unique(gimmie$n))
>
> # the below yields a plot of three colors
> display.brewer.pal(numpoly, "Accent")
>
> #the below yields my map but with only two of the three above colors, yet
> the scale bar shows
> #three colors with the three values I KNOW are in my 'n' values in the
> shapefile
> spplot(gimmie, c("n"), xlim=c(minx,maxx), ylim=c(miny,maxy),
> col.regions=brewer.pal(numpoly, "Accent"))
>
> ? I don't see why this doesn't work as I expect.  Any ideas, anyone?
>
>
>
> --
> View this message in context: http://r-sig-geo.2731867.n2.nabble.com/plotting-polygons-of-one-shapefile-in-different-colors-tp7584720p7584727.html
> Sent from the R-sig-geo mailing list archive at Nabble.com.
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Department of Economics, NHH Norwegian School of Economics,
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