R:Custom color palette in map with spplot

我的未来我决定 提交于 2019-12-21 20:46:30

问题


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.


回答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'))

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!