首页 文章

使用ggplot2根据人口普查数据绘制 Map

提问于
浏览
3

我有一个我希望使用ggplot2在旧金山 Map 上叠加的点列表 . 每个点都是经度,纬度对 . 我希望生成的 Map 位于经度/纬度坐标系中 . 我设法使用他的示例文件重现了Hadley Wickham的directions for plotting polygon shapefiles . 我正在使用R 2.15.1 for Windows .

但是,我尝试使用从UScensus2010cdp package下载的cdp文件 . 这是我的代码片段:

require("rgdal") 
require("maptools")
require("ggplot2")
require("sp")
require("plyr")
gpclibPermit() # required for fortify method
require(UScensus2010)
require(UScensus2010cdp)
data(california.cdp10)
sf <- city(name = "san francisco", state="ca")
sf.points = fortify(sf)

我收到以下错误:

Using name to define regions.
Error in unionSpatialPolygons(cp, invert(polys)) : input lengths differ
In addition: Warning message:
In split(as.numeric(row.names(attr)), addNA(attr[, region], TRUE)) :
   NAs introduced by coercion

有人知道吗:

  • 赋予fortify()的region参数有什么好处?

  • 如果失败了,ggplot2可以绘制旧金山的未转换纬度/经度坐标的 Map 数据源?

  • 或者,我发现here另一张旧金山 Map ,其数据已被翻译 . 你能告诉我如何将这些数据翻译成原始的lat / long或者为我的一组点进行反向翻译吗?

1 回答

  • 6

    注意:

    问题

    问题产生于 fortify.SpatialPolygonsDataFrame 依赖于将 row.names 转换为数字,而数据的rownames是标识符 .

    ggplot2:::fortify.SpatialPolygonsDataFrame 
    
    function (model, data, region = NULL, ...) 
    {
        attr <- as.data.frame(model)
        if (is.null(region)) {
            region <- names(attr)[1]
            message("Using ", region, " to define regions.")
        }
        polys <- split(as.numeric(row.names(attr)), addNA(attr[, 
            region], TRUE))
        cp <- polygons(model)
        try_require(c("gpclib", "maptools"))
        unioned <- unionSpatialPolygons(cp, invert(polys))
        coords <- fortify(unioned)
        coords$order <- 1:nrow(coords)
        coords
    }
    

    在你的情况下

    row.names(sf@data)
    ## [1] "california_586" "california_590" "california_616"
    

    是您希望用作区域参数的标识符,因为 place statename 不能唯一标识三个多边形 .

    # as.character used to coerce from factor
    lapply(lapply(sf@data[,c('place','state','name')], unique), as.character)
    ## $place
    ## [1] "67000"
    ## 
    ## $state
    ## [1] "06"
    ## 
    ## $name
    ## [1] "San Francisco"
    

    作为字符向量,其中元素以字母字符开头,当强制为数字时,它变为 NA

    as.numeric(rownames(sf@data))
    ## [1] NA NA NA
    ## Warning message:
    ## NAs introduced by coercion
    

    这是给出的警告之一

    解决方案

    • 将列定义为rownames

    • 将row.names设置为 NULL1:nrow(sf@data)

    所以..

    # rownames
    sf@data[['place_id']] <- rownames(sf@data)
    row.names(sf@data) <- NULL
    
    # fortify
    sf_ggplot <- fortify(sf, region = 'place_id')
    # merge to add the original data
    sf_ggplot_all <- merge(sf_ggplot, sf@data, by.x = 'id', by.y = 'place_id')
    # very basic and uninteresting plot
    ggplot(sf_ggplot_all,aes(x=long,y=lat, group = group)) + 
      geom_polygon(aes(fill =pop2000)) + 
      coord_map()
    

    enter image description here

相关问题