2012-09-02 84 views
3

我有一列要使用ggplot2在舊金山地圖上疊加的點。 每個點都是經度,緯度對。 我希望生成的地圖位於經度/緯度座標系中。 我設法使用他的示例文件重現了Hadley Wickham的directions for plotting polygon shapefiles。我在Windows上使用R 2.15.1。使用ggplot2基於人口普查數據繪製地圖

但是,我試圖使用從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 

有誰知道:

  1. 什麼是一個很好的價值給予的設防區域的參數( )?
  2. 如果失敗,那麼ggplot2可以繪製舊金山未經轉換的緯度/經度座標的地圖數據源?
  3. 或者,我發現here舊金山的另一張地圖,其資料被翻譯。你能告訴我如何將這些數據翻譯成原始緯度/經度或者對我的一組點進行反向翻譯?
+1

鏈接[UScensus2010cdp包(http://lakshmi.calit2.uci.edu/census2000/censuspackages/UScensus2010cdp_1.00.tar.gz)內的鏈接出現被打破 – mnel

+0

謝謝,我編輯這個指向你給的鏈接。 –

回答

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([email protected]) 
## [1] "california_586" "california_590" "california_616" 

是你希望作爲區域參數來使用,如placestatename沒有唯一識別三個多邊形的標識符。

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

作爲字符向量,其中的元素與字母字符開始,當強制轉換爲數字,變得NA

as.numeric(rownames([email protected])) 
## [1] NA NA NA 
## Warning message: 
## NAs introduced by coercion 

被給予

    的警告之一
  1. 將列定義爲rownames
  2. 將row.names到NULL1:nrow([email protected])

所以..

# rownames 
[email protected][['place_id']] <- rownames([email protected]) 
row.names([email protected]) <- NULL 

# fortify 
sf_ggplot <- fortify(sf, region = 'place_id') 
# merge to add the original data 
sf_ggplot_all <- merge(sf_ggplot, [email protected], 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