R - GGmap缺少多边形

时间:2018-01-26 18:31:05

标签: r ggplot2 gis ggmap choropleth

我正在尝试根据落在多边形内部的地理坐标点的数量绘制一个等值区域图。多边形的蓝色阴影根据其区域内的点数变得越来越蓝。

我遇到的问题是多边形渲染效果不佳,缺少整个部分。我无法弄清楚为什么会这样。

这应该是一个工作最低限度可重复的例子(如果我错了,请纠正我,我会解决它):

library(httr)
library(rgdal)
library(ggmap)
library(sp)
library(dplyr)

neighborhoods.sp <- readOGR(dsn = content(GET("http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nynta/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson"), as = 'text', encoding = "UTF-8"), layer = "OGRGeoJSON", verbose = F)

tweets.df <- data.frame(label = c(1, 2, 1, 1, 2, 1), lon = c(-74.03220, -73.96854, -73.96295, -73.78130, -74.08530, -73.96854), lat = c(40.76930, 40.78078, -73.96295, 42.65980, 40.69600, 40.78078))

nyc.map <- get_map(location = c(lon = -73.935242, lat = 40.730610), maptype = "terrain", zoom = 10)

tweets.sp.i <- tweets.df.i <- tweets.df
coordinates(tweets.sp.i) <- ~ lon + lat
proj4string(tweets.sp.i) <- proj4string(neighborhoods.sp)
tweets.df.i <- na.omit(cbind(tweets.df.i, over(tweets.sp.i, neighborhoods.sp)))
tweets.df.i <- tweets.df.i[, c("label", "BoroName")]
tweets.df.t <- aggregate(label ~ ., FUN = length, data = tweets.df.i)
tweets.df.n <- aggregate(label ~ ., FUN = length, data = tweets.df.i[tweets.df.i$label == 1, ])
tweets.df.p <- aggregate(label ~ ., FUN = length, data = tweets.df.i[tweets.df.i$label == 2, ])
tweets.df.i <- merge(merge(tweets.df.n, tweets.df.p, by = "BoroName"), tweets.df.t, by = "BoroName")
neighborhoods.df <- tidy(neighborhoods.sp, region = "BoroName")
tweets.by.neighborhood.df.i <- left_join(neighborhoods.df, tweets.df.i, by = c("id" = "BoroName"))
ggmap(nyc.map) + geom_polygon(data = tweets.by.neighborhood.df.i, aes(x = long, y = lat, group = id, fill = label.x), alpha = 0.75)

enter image description here

1 个答案:

答案 0 :(得分:2)

您似乎已将geom_polygon分组为错误的变量“id”,而您应该按变量“group”对其进行分组。这导致geom_polygon遵循错误的点序列。

请尝试将此作为最后一行:

ggmap(nyc.map) + geom_polygon(data = tweets.by.neighborhood.df.i, aes(x = long, y = lat, group = group, fill = label.x), alpha = 0.75) 

enter image description here