1

在尝试处理我似乎无法调试的数据时,我遇到了几个错误。

这是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
4

1 回答 1

2

如果您设置,您的代码对我有用

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

并删除线

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

你也不应该longlon@mdsumner 提到的那样使用。

这是一个略有不同的解决方案(使用geom_polygonnot geom_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
于 2012-08-05T09:32:42.433 回答