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.
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'))
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.
来源:https://stackoverflow.com/questions/25918012/rcustom-color-palette-in-map-with-spplot