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

Yuv*_*l F 4 r geospatial ggplot2 census

我有一个我希望使用ggplot2在旧金山地图上叠加的点列表.每个点都是经度,纬度对.我希望生成的地图位于经度/纬度坐标系中.我设法重现了Hadley Wickham 使用他的示例文件绘制多边形shapefile方向.我正在使用R 2.15.1 for Windows.

但是,我尝试使用从UScensus2010cdp包下载的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)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

有人知道吗:

  1. 给fortify()的region参数有什么好处?
  2. 如果失败了,ggplot2可以绘制旧金山的未转换纬度/经度坐标的地图数据源?
  3. 或者,我在这里找到另一张旧金山地图,其数据已被翻译.你能告诉我如何将这些数据翻译成原始的lat/long或者为我的一组点进行反向翻译吗?

mne*_*nel 7

注意:

问题

问题源于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
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下

row.names(sf@data)
## [1] "california_586" "california_590" "california_616"
Run Code Online (Sandbox Code Playgroud)

你希望作为区域参数来使用,作为标识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"
Run Code Online (Sandbox Code Playgroud)

作为一个字符向量,其中元素以字母字符开头,当强制转换为数字时,它就变成了 NA

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

这是给出的警告之一

  1. 将列定义为rownames
  2. 将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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述