R - GGmap 缺少多边形

R - GGmap missing polygons

我正在尝试根据落入多边形内的地理坐标点的数量绘制等值线图。根据落入其区域内的点数,多边形的蓝色阴影会越来越蓝。

我遇到的问题是多边形渲染不佳,整个部分缺失。我不明白为什么会这样。

这应该是一个最小可重现的工作示例(如果我错了请纠正我,我会修复它):

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)

您似乎按错误的变量 "id" 对 geom_polygon 进行了分组,而您应该按变量 "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)