Christopher Costello
Christopher Costello

Reputation: 1256

R - GGmap missing polygons

I'm trying to plot a choropleth map based on the number of geocoordinate points that fall inside of polygons. The shade of blue of a polygon becomes increasingly blue based on the number of points that fall inside of its area.

The problem I'm experiencing is that the polygons are rendering poorly, with entire missing sections. I can't figure out why this is happening.

This should be a working minimally reproducible example (correct me if I'm wrong and I'll fix it up):

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

Upvotes: 0

Views: 201

Answers (1)

Nicol&#225;s Velasquez
Nicol&#225;s Velasquez

Reputation: 5898

You seem to have grouped the geom_polygon by the wrong variable, "id", while you should group it by the variable "group". This leads the geom_polygon to follow the wrong sequence of points.

Try this as your last line:

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

Upvotes: 2

Related Questions