使用ggplot为地图上不同的相邻区域着色

Eri*_*poe 5 maps r ggplot2

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

地区是加利福尼亚县的组,用数字编码(这里是列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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

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

Spa*_*man 3

尝试这个。它采用空间多边形数据帧并返回每个元素的颜色向量,以便没有两个相邻的多边形具有相同的颜色。

您需要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)
}
Run Code Online (Sandbox Code Playgroud)

测试:

  library(spdep)
  example(columbus)
  columbus$C = nacol(columbus)
  plot(columbus,col=columbus$C+1)
Run Code Online (Sandbox Code Playgroud)