我有一个包含超过50,000个数据的数据集。该数据集包括对象,经度和纬度(具有以下结构)。
coord <- data.frame(object = c("a","b","c","d","e","f","h","i","j","k"), LON = c(-73.95 ,-73.97,-73.95,-73.91,-73.91,-73.93,-73.96, -73.90,-73.97,-73.94),LAT =c(40.60,40.68,40.68,40.85,40.83,40.72,40.65, 40.74, 40.69, 40.82))
我打算将不同地区的地图着色。我找到了以下示例代码。
library(rgeos)
library(maptools)
library(geojsonio)
library(ggplot2)
URL <- "http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nycd/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson"
fil <- "nyc_community_districts.geojson"
if (!file.exists(fil)) download.file(URL, fil)
nyc_districts <- geojson_read(fil, what="sp")
nyc_districts_map <- fortify(nyc_districts, region="BoroCD")
mids <- cbind.data.frame(as.data.frame(gCentroid(nyc_districts, byid=TRUE)),id=nyc_districts$BoroCD)
gg <- ggplot()
gg <- gg + geom_map(data=nyc_districts_map, map=nyc_districts_map,
aes(x=long, y=lat, map_id=id),
color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + geom_text(data=mids, aes(x=x, y=y, label=id), size=2)
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
然后,我使用此代码为不同的区域着色
library(viridis)
# make up some fill data
set.seed(1492)
df <- data.frame(LON = c(-73.95770,-73.95445,-73.96215,-73.97739,-73.98136,-73.93974,-73.95061, -73.98609 ,-73.95724,-73.93351,-73.94931),LAT =c(40.81099,40.71415,40.71025,40.68983,40.66715,40.79821,40.66830, 40.68980, 40.71636, 40.76621, 40.80273))
pointsSp <- SpatialPoints(coords = df[,c("LON", "LAT")],
proj4string = CRS(proj4string(nyc_districts)))
nyc_districts$pointCount <- 0
for(i in 1:length(nyc_districts)){
x <- nyc_districts[i,]
nyc_districts$pointCount[i] <- length(x[pointsSp,])
}
choro <- data.frame(district=nyc_districts@data$BoroCD,
fill=sample(100, nrow(nyc_districts@data)))
gg <- ggplot()
gg <- gg + geom_map(data=nyc_districts_map, map=nyc_districts_map,
aes(x=long, y=lat, map_id=id),
color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + geom_map(data=choro, map=nyc_districts_map,
aes(fill=fill, map_id=district),
color="#2b2b2b", size=0.15)
gg <- gg + geom_point(data=coord, aes(x=LON, y=LAT),
colour= "red", alpha=1,na.rm=T)
gg <- gg + scale_fill_viridis(name="Pick ups\ndistribution") + geom_text(data=mids, aes(x=x, y=y, label=id), size=2)
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
gg <- gg + theme(legend.position=c(0.1,0.5))
gg
在上面的代码中,使用geom-point我可以在地图上显示不同协调的位置。但我的区域着色是错误的。你能告诉我怎样才能根据&#34; coord&#34;数据集。
答案 0 :(得分:0)
您必须执行与每个多边形相交的点数的“空间连接”。因此,必须将点转换为SpatialPoints
对象。
pointsSp <- SpatialPoints(coords = coord[,c("LON", "LAT")],
proj4string = CRS(proj4string(nyc_districts)))
然后,我们取nyc_districts
的每个多边形并计算每个多边形内的点数。
nyc_districts$pointCount <- 0
for(i in 1:length(nyc_districts)){
x <- nyc_districts[i,]
nyc_districts$pointCount[i] <- length(pointsSp[x,])
}
然后你只需将你的choro代码行更改为以下内容,这基本上将sample(...)
(出于测试目的......)更改为我们在上面创建的变量。之后,您就像在Q中一样创建情节。
choro <- data.frame(district=nyc_districts@data$BoroCD,
fill=nyc_districts$pointCount)