【问题标题】:Drawing maps based on census data using ggplot2使用 ggplot2 根据人口普查数据绘制地图
【发布时间】:2012-08-27 08:53:54
【问题描述】:

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

但是,我尝试使用从UScensus2010cdp package 下载的 cdp 文件。 这是我的代码 sn-p:

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

有人知道吗:

  1. 为 fortify() 的 region 参数赋予什么好的值?
  2. 如果失败,ggplot2 可以绘制的旧金山地图数据源是否具有未转换的纬度/经度坐标?
  3. 另外,我找到了here 旧金山的另一张地图,其数据已被翻译。您能告诉我如何将这些数据转换为原始纬度/经度或对我的一组点进行反向转换吗?

【问题讨论】:

  • 链接中指向UScensus2010cdp package 的链接似乎已损坏
  • 谢谢,我编辑了这个指向你提供的链接。

标签: r ggplot2 geospatial census


【解决方案1】:

注意:

问题

问题源于fortify.SpatialPolygonsDataFrame 依赖于将row.names 转换为数字,并且数据的行名是标识符。

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

这是给出的警告之一

解决方案

  1. 将列定义为行名
  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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2015-04-13
    相关资源
    最近更新 更多