使用ggplot2根据普查数据绘制地图 我有一个用GGPROTT2覆盖在旧金山地图上的点的列表。 每个点都是经度、纬度对。 我希望生成的地图位于经度/纬度坐标系中。 我用哈德利·威克姆的示例文件复制了他的作品。我正在Windows上使用R2.15.1
但是,我尝试使用从下载的cdp文件。 以下是我的代码片段:使用ggplot2根据普查数据绘制地图 我有一个用GGPROTT2覆盖在旧金山地图上的点的列表。 每个点都是经度、纬度对。 我希望生成的地图位于经度/纬度坐标系中。 我用哈德利·威克姆的示例文件复制了他的作品。我正在Windows上使用R2.15.1,r,ggplot2,geospatial,census,R,Ggplot2,Geospatial,Census,但是,我尝试使用从下载的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
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)
有人知道吗
- 无法访问,因此我使用复制错误的
fortify.SpatialPolygonsDataFrame
依赖于将行名称
转换为数字,并且数据的行名称是标识符
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
}
是您希望用作区域参数的标识符,因为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"
作为元素以字母开头的字符向量,当强制为数字时,它将变为NA
as.numeric(rownames(sf@data))
## [1] NA NA NA
## Warning message:
## NAs introduced by coercion
哪一个是给出的警告之一
解决方案
NULL
或1:nrow(sf@data)
#行名
sf@data[['place_id']]链接中的链接似乎是断开的,我编辑了此链接以指向您提供的链接。
# 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"
as.numeric(rownames(sf@data))
## [1] NA NA NA
## Warning message:
## NAs introduced by coercion
# 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()