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)
有人知道吗:
UScensus2010cdp,所以使用UScensus2000cpd哪个复制错误.问题源于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 state和name不唯一确定三个多边形.
# 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)
这是给出的警告之一
NULL或1: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)
