2012-08-04 19 views
1

使用我无法调试的数据尝试时,出现了几个错误。使用R中的空间数据时发生错误

这里是[R脚本https://dl.dropbox.com/u/28231177/This%20Should%20Work.R
下面是数据https://dl.dropbox.com/u/28231177/my_data.csv

这里是包含错误的最后几行,当我运行它们:

pds <- fortify(sf_map) 
# Using OBJECTID to define regions. 
pds$OBJECTID <- as.integer(pds$OBJECTID) 
# Error in `$<-.data.frame`(`*tmp*`, "OBJECTID", value = integer(0)) : 
# replacement has 0 rows, data has 16249 


### Make the map 

p1 <- ggplot(my_data, aes(map_id = zip)) 
p1 <- p1 + geom_map(aes(fill=vol, map_id = zip), map = pds) 
p1 <- p1 + expand_limits(x = pds$lon, y = pds$lat) + coord_equal() 
p1 + xlab("Basic Map with Default Elements") 
# Error in unit(x, default.units) : 'x' and 'units' must have length > 0 
+0

另外,这里是shape文件http://dl.dropbox.com/u/28231177/sfzipcodes.zip – user1576537 2012-08-04 19:55:30

+1

什么名字( PDS)?我敢说OBJECTID不是其中之一。行pds $ OBJECTID < - as.integer(pds $ OBJECTID)假定列存在,检查该假设是否足够简单。 – mdsumner 2012-08-04 22:35:39

+0

@mdsumner,这是我得到的: 'pds < - fortify(sf_map) #使用OBJECTID定义区域。 名称(pds) #[1]“long”“lat”“order”“hole”“piece”“group”“id”' 看起来你是对的。应该设置哪一列? ID? – user1576537 2012-08-05 06:54:59

回答

2

您的代码对我的作品如果你设置了

pds <- fortify(sf_map, region = "ID") 

和removin克线

pds$OBJECTID <- as.integer(pds$OBJECTID) 

而且你应该使用longlon由@mdsumner提及。

这里有一个稍微不同的解决方案(使用geom_polygongeom_map

library(maptools) 
library(ggplot2) 

## 'fortify' needs 'library(gpclib)' locally available 
gpclibPermit() 

## Import the shapefile 
sf_map <- readShapeSpatial("sfzipcodes", ID = "ID") 

## Import the data 
my_data <- read.csv("my_data.csv") 
my_data <- unique(my_data) 

## Merge the data 
sf_df <- fortify(sf_map, region='ID') 
sf_df <- merge(sf_df, my_data, by.x="id", by.y="zip", all=FALSE) 
sf_df <- sf_df[order(sf_df$group, sf_df$order), ] 

## Make the map 
p2 <- ggplot(sf_df, aes(x=long, y=lat, group=group, fill=vol)) 
p2 <- p2 + geom_polygon() + coord_equal() 
p2 <- p2 + xlab("Basic Map with Default Elements") 
p2 
相关问题