R 如何将geom_sf生成的地图放在ggmap生成的光栅上
我尝试了以下代码:R 如何将geom_sf生成的地图放在ggmap生成的光栅上,r,ggplot2,maps,ggmap,sf,R,Ggplot2,Maps,Ggmap,Sf,我尝试了以下代码: library(ggplot2) library(ggmap) library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) str(nc) Classes ‘sf’ and 'data.frame': 100 obs. of 15 variables: $ AREA : num 0.114 0.061 0.143 0.07 0.153 0.097 0.062 0.091
library(ggplot2)
library(ggmap)
library(sf)
nc <- st_read(system.file("shape/nc.shp", package = "sf"))
str(nc)
Classes ‘sf’ and 'data.frame': 100 obs. of 15 variables:
$ AREA : num 0.114 0.061 0.143 0.07 0.153 0.097 0.062 0.091 0.118 0.124 ...
$ PERIMETER: num 1.44 1.23 1.63 2.97 2.21 ...
$ CNTY_ : num 1825 1827 1828 1831 1832 ...
$ CNTY_ID : num 1825 1827 1828 1831 1832 ...
$ NAME : Factor w/ 100 levels "Alamance","Alexander",..: 5 3 86 27 66 46 15 37 93 85 ...
$ FIPS : Factor w/ 100 levels "37001","37003",..: 5 3 86 27 66 46 15 37 93 85 ...
$ FIPSNO : num 37009 37005 37171 37053 37131 ...
$ CRESS_ID : int 5 3 86 27 66 46 15 37 93 85 ...
$ BIR74 : num 1091 487 3188 508 1421 ...
$ SID74 : num 1 0 5 1 9 7 0 0 4 1 ...
$ NWBIR74 : num 10 10 208 123 1066 ...
$ BIR79 : num 1364 542 3616 830 1606 ...
$ SID79 : num 0 3 6 2 3 5 2 2 2 5 ...
$ NWBIR79 : num 19 12 260 145 1197 ...
$ geometry :sfc_MULTIPOLYGON of length 100; first list element: List of 1
..$ :List of 1
.. ..$ : num [1:27, 1:2] -81.5 -81.5 -81.6 -81.6 -81.7 ...
..- attr(*, "class")= chr "XY" "MULTIPOLYGON" "sfg"
- attr(*, "sf_column")= chr "geometry"
- attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
..- attr(*, "names")= chr "AREA" "PERIMETER" "CNTY_" "CNTY_ID" ...
map <- get_map("north carolina", maptype = "satellite", zoom = 6, source = "google")
a <- unlist(attr(map,"bb")[1, ])
bb <- st_bbox(nc)
ggplot() +
annotation_raster(map, xmin = a[2], xmax = a[4], ymin = a[1], ymax = a[3]) +
xlim(c(bb[1], bb[3])) + ylim(c(bb[2], bb[4])) +
geom_sf(data = nc, aes(fill = AREA))
库(ggplot2)
图书馆(ggmap)
图书馆(sf)
nc您可以使用sf
软件包中的绘图方法来执行此操作。您需要指定坐标参考系,我们需要假设(看起来正确)为3857
库(ggplot2)
图书馆(ggmap)
图书馆(sf)
nc_shp我自己也在努力解决这个问题,在我的帮助下,我想出了一个解决方案。ggmap对象的边界框在WGS84(EPSG:4326)中,但实际光栅在EPSG:3857中。您必须破解ggmap对象的边界框,使其与基础数据位于相同的CRS中:
库(ggplot2)
图书馆(ggmap)
图书馆(sf)
#>链接到GEOS 3.6.2、GDAL 2.3.0、项目4.5.1.0
nc你能发布str(nc)
(编辑你的问题)的结果吗?你的解决方案完美地将我的多边形与谷歌底图对齐。现在我无法在绘图上使用ggplot2::annotate()或ggimage::geom_image()。在使用ggmap_bbox函数后,您对如何标记或添加自定义符号有何想法?
library(ggplot2)
library(ggmap)
library(sf)
nc_shp <- st_read(system.file("shape/nc.shp", package = "sf"))
nc_map <- get_map("north carolina", maptype = "satellite", zoom = 6, source = "google")
st_crs(nc_map)
# Coordinate Reference System: NA
# assume the coordinate refence system is 3857
plot(st_transform(nc_shp, crs = 3857)[1], bgMap = nc_map)