r - 在ggplot map 上叠加多边形

标签 r ggplot2 gis shapefile ggmap

我正在努力在谷歌地图上覆盖社区边界。我正在尝试关注此 code .我的版本如下。你看到有什么明显的错误吗?

#I set the working directory just before this...
chicago = readOGR(dsn=".", layer="CommAreas")
overlay <- spTransform(chicago,CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay)
location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)
ggmap(get_map(location=location,zoom = 10, maptype = "terrain", source = "google",col="bw")) +
  geom_polygon(aes(x=long, y=lat, group=group), data=overlay, alpha=0)+
  geom_path(color="red")

任何见解将不胜感激。感谢您的帮助和耐心。

最佳答案

这对我有用:

library(rgdal)
library(ggmap)

# download shapefile from:
#   https://data.cityofchicago.org/api/geospatial/cauq-8yn6?method=export&format=Shapefile

# setwd accordingly

overlay <- readOGR(".", "CommAreas")
overlay <- spTransform(overlay, CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay, region="COMMUNITY") # it works w/o this, but I figure you eventually want community names

location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)

gmap <- get_map(location=location, zoom = 10, maptype = "terrain", source = "google", col="bw")

gg <- ggmap(gmap)
gg <- gg + geom_polygon(data=overlay, aes(x=long, y=lat, group=group), color="red", alpha=0)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg

enter image description here

如果环境中出现任何问题,您可能想要重新启动 R session ,但您可以在 geom_polygon 调用中设置线条颜色和 alpha 0 填充(就像我所做的那样)。

您还可以:

gg <- gg + geom_map(map=overlay, data=overlay, 
                    aes(map_id=id, x=long, y=lat, group=group), color="red", alpha=0)

而不是 geom_polygon,它使您能够在一次调用与两次调用中绘制 map 并执行美学映射(如果您根据其他值着色)。

关于r - 在ggplot map 上叠加多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26344510/

相关文章:

r - 尝试在测试数据集上使用 model.matrix 函数

R创建列组合来自两列的信息

r - 是否可以使用 ggplot2 修复轴边距?

R - 将 (ggplot) fiddle 图的宽度修改为 y 变量的函数

r - K-均值算法:Lloyd、Forgy、MacQueen、Hartigan-Wong

r - 模糊 LEFT 与 R 连接

r - 如何添加水平线显示ggplot2中所有组的平均值?

google-maps - 在 GIS 服务中写入纬度和经度元组的首选顺序

r - 使用 sf::st_write() 将空间数据从 R 写入 MS SQL Server

r - 如何将 terra R 包与需要身份验证的云优化 geotiff 结合使用?