3

I am struggling with introducing a custom color palette on several polygons using spplot from the sp package. I am plotting several fields and want to show my rating , which can have the values 0,1,2,4 or 5. I need to use custom colors for that. What I tried is:

spplot(Map,zcol="Rating", 
       col.regions=c("0"="#00cc00","1"="#ffff66","2"="#e5c100",
                     "3"="orange","4"="#ff5e5e","5"="red"), 
       colorkey=TRUE)

However, it is producing a repetition of colors like in the map below. How can I solve this? I know how I can to it with ggplot, but for several reasons I need to know how to do it with spplot. Thank a lot for your help.

Edit: Here an example with a map that does work the way I need it:

con <- url("http://gadm.org/data/rda/DEU_adm3.RData")
print(load(con))
close(con)
t1<-gadm[grep("Sachsen|Hessen|Bayern",gadm$NAME_1),]
col=c("red","yellow")
spplot(t1,zcol="TYPE_3",col.regions=col)

I noticed the following: When I subset the original "Large SpatialPolygonsDataframe" with my data, the resulting map is a "Formal Class SpatialPolygonsDataframe". This does not happen in the example I just posted above. Can anyone tell me what causes this behaviour? Unfortunately I cannot upload the original (sensitive) data.

Map produced by spplot with repetitive color code (not desired)

user2386786
  • 725
  • 9
  • 25
  • Does it work the way you expect if you change your code to `col.regions=c("#00cc00", "#ffff66", "#e5c100", "orange", "#ff5e5e", "red")` – eipi10 Sep 18 '14 at 18:11
  • It will be easier to help you if you post a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so that others can reproduce your problem and try to solve it. – eipi10 Sep 18 '14 at 20:46

1 Answers1

1

This occurs when your zcol is numeric. Convert it to factor and your plot should appear as expected.

You can see this behaviour if you convert t1$TYPE_3 to numeric:

t1$TYPE_3.num <- as.numeric(t1$TYPE_3)
spplot(t1, 'TYPE_3.num', col.regions=c('red', 'yellow'))

t1

So assuming there are 6 possible factor levels, with labels 0 through 5, try:

Map$Rating.fac <- factor(M$Rating, levels=0:5)

and then use zcol='Rating.fac' and pass a vector of 6 colours to col.regions.

jbaums
  • 27,115
  • 5
  • 79
  • 119