r - 使用 ggmap : clipping when shape file is larger than ggmap 绘制形状文件

标签 r ggplot2 ggmap

当我尝试将 ggmap 与形状文件结合时,我遇到了剪切问题。 Kahle 和 Wickham (2013: 158) 中的示例工作正常,因为来自 ggmap 的光栅图像覆盖了整个形状文件。下面是当我尝试在覆盖较小区域的 ggmap 图上绘制美国各州的形状文件时会发生什么的示例。 ggmap 显示了纽约市,我想用美国各州的边界覆盖它(仅作为示例)。结果 map 没有任何意义。问题是形状文件被剪裁了,ggplot 连接了未剪裁的点。下面是代码。形状文件来自 here .我只是在这里展示最后一个情节。

我怎么解决这个问题?

path <- "PATH TO SHAPEFILE"
library("ggmap")
library("rgdal")

# shapefile
states <- readOGR(dsn = path, layer = "states")
states_df <- fortify(states)
# plot shapefile
plot(states, lwd = 0.1)
ggplot(states_df, aes(long, lat, group = group)) +
    geom_polygon(colour = "black", fill = NA, size = 0.1)


# combine ggmap with shapefile
map <- get_map("new york city", zoom = 10, source = "stamen")
ggmap(map, extent = "device")

ggmap(map, extent = "device") +
    geom_polygon(aes(long, lat, group=group), data = states_df, colour = "red", fill = NA, size = 1)

卡勒、大卫和哈德利·威克姆。 2013. “Ggmap:使用 ggplot2 进行空间可视化。” R 期刊 5(1):144–61。

enter image description here

最佳答案

这是我的尝试。我经常使用 GADM 形状文件,您可以使用 raster 直接导入。包裹。我对纽约、新泽西和 CT 的形状文件进行了子集化。您最终可能不必这样做,但减少数据量可能会更好。当我绘制 map 时,ggplot 会自动删除留在 ggmap 图像 bbox 之外的数据点。因此,我不必做任何额外的工作。我不确定您使用的是哪个 shapefile。但是,GADM 的数据似乎适用于 ggmap 图像。希望这对你有帮助。

library(raster)
library(rgdal)
library(rgeos)
library(ggplot2)

### Get data (shapefile)
us <- getData("GADM", country = "US", level = 1)

### Select NY and NJ
states <- subset(us, NAME_1 %in% c("New York", "New Jersey", "Connecticut"))

### SPDF to DF
map <- fortify(states)

## Get a map
mymap <- get_map("new york city", zoom = 10, source = "stamen")


ggmap(mymap) +
geom_map(data = map, map = map, aes(x = long, y = lat, map_id = id, group = group))

enter image description here

如果您只想要线条,那么以下将是您所追求的。
ggmap(mymap) +
geom_path(data = map, aes(x = long, y = lat, group = group))

enter image description here

关于r - 使用 ggmap : clipping when shape file is larger than ggmap 绘制形状文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29825458/

相关文章:

r - 使用 ggplotly Rangeslider 进行交互式相对表现(股票 yield )

r - 在 R 中,使用 ggplot2 或基本图绘制宽格式数据。有没有办法在不熔化宽格式数据框的情况下使用 ggplot2 ?

r - 连接抖动点的线 - 多组躲避

r - 向 ggmap 添加易于阅读的比例尺(使用 ggsn 包?)

r - 在带有 map() 的嵌套数据框中使用 filter()(和其他 dplyr 函数)

r - 如何获取R中数据框中每个单元格中数字旁边出现的字符串百分比?

css - 将背景颜色从 block 引用更改为 rmarkdown 中的 block 引用

r - ggplot2:添加用于 facet_grid 的变量名称

r - 在 R 中的 ggmap 对象上绘制 geom_segment - 线未出现

r - 在ggplot2中绘制大多边形 map 的小区域