使用ggplot对地图上相邻区域进行不同着色

问题描述 投票:3回答:2

我正在尝试使用ggplot制作R中不同区域的地图,其中相邻区域的颜色不同,这与five color theorem描述的内容有关。

地区是加利福尼亚州的一组,用数字编码(这里是c20专栏)。使用ggplot()和geom_map()以及定性比例为区域着色,我得到的最接近的是:

ggplot() + geom_map(data = data, aes(map_id = geoid, fill = as.factor(c20 %% 12)), 
                  map = county) + expand_limits(x = county$long, y = county$lat) +
coord_map(projection="mercator") +
scale_fill_brewer(palette = "Paired") +
geom_text(data = distcenters, aes(x = clong, y = clat, label = cluster, size = 0.2))

问题是来自不同地区(即具有不同数量)的相邻县有时会具有相同的颜色。例如,在洛杉矶附近,来自33和45区的县是相同的颜色,我们在视觉上区分不同的区域。

有没有办法用ggplot做到这一点?

r ggplot2 maps
2个回答
1
投票

试试这个。它采用空间多边形数据框并返回每个元素的颜色矢量,使得没有两个相邻的多边形具有相同的颜色。

您需要先安装spdep软件包。

nacol <- function(spdf){
    resample <- function(x, ...) x[sample.int(length(x), ...)]
    nunique <- function(x){unique(x[!is.na(x)])}
    np = nrow(spdf)
    adjl = spdep::poly2nb(spdf)
    cols = rep(NA, np)
    cols[1]=1
    nextColour = 2

    for(k in 2:np){
        adjcolours = nunique(cols[adjl[[k]]])
        if(length(adjcolours)==0){
            cols[k]=resample(cols[!is.na(cols)],1)
        }else{
            avail = setdiff(nunique(cols), nunique(adjcolours))
            if(length(avail)==0){
                cols[k]=nextColour
                nextColour=nextColour+1
            }else{
                cols[k]=resample(avail,size=1)
            }
        }
    }
    return(cols)
}

测试:

  library(spdep)
  example(columbus)
  columbus$C = nacol(columbus)
  plot(columbus,col=columbus$C+1)

0
投票

这是相当晚的,但是在搜索相同的问题时,我发现了一个名为“MapColoring”的开发包:https://github.com/hunzikp/MapColoring它完全符合您的要求。

© www.soinside.com 2019 - 2024. All rights reserved.