R:带有贴图的地图中的自定义调色板 [英] R:Custom color palette in map with spplot

查看:62
本文介绍了R:带有贴图的地图中的自定义调色板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用sp包中的spplot在多个多边形上引入自定义调色板. 我正在绘制几个字段,并想显示我的等级,其值可以为0、1、2、4或5.为此,我需要使用自定义颜色.我试过的是:

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)

但是,它会产生重复的颜色,如下图所示.我该如何解决?我知道如何用ggplot做到这一点,但是出于几个原因,我需要知道如何使用spplot做到这一点. 非常感谢您的帮助.

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.

这是一个地图的示例,该地图的工作方式符合我的需要:

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)

我注意到以下情况:当我用数据对原始的"Large SpatialPolygonsDataframe"进行子集化时,生成的地图是"Formal Class SpatialPolygonsDataframe".在我上面发布的示例中,不会发生这种情况.谁能告诉我是什么原因造成的?不幸的是,我无法上传原始(敏感)数据.

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.

推荐答案

当您的zcolnumeric时,会发生这种情况.将其转换为factor,您的图应按预期显示.

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

如果将t1$TYPE_3转换为数字,则会看到此行为:

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

因此,假设存在6种可能的因子水平,标签为0到5,请尝试:

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

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

,然后使用zcol='Rating.fac'并将6种颜色的矢量传递给col.regions.

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

这篇关于R:带有贴图的地图中的自定义调色板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆