问题描述
之前一些问题的主题 - 例如this。我无法在 ggmap 层上渲染 sf 层。
require(ggmap)
require(raster)
require(sf)
target_bBox <- c(left = -0.65,bottom = 51.2,right = 0.45,top = 51.8)
map = get_stamenmap(target_bBox,zoom = 9,maptype = 'toner-2010')
# can test this with: ggmap(map)
e = extent(list(x = c(-0.65,0.45),y = c(51.2,51.8)))
r = raster(volcano)
crs(r) = CRS("+proj=longlat +datum=wgs84")
p = raster::rasterTopolygons(r)
sf = st_as_sf(p) %>% st_transform(3857)
# test with: ggplot() + geom_sf(data = sf,aes(fill = layer),col = NA)
ggmap(map) +
geom_sf(data = sf,col = NA,alpha = 0.4,inherit.aes = FALSE)
Coordinate system already present. Adding new coordinate system,which will replace the existing one.
坐标系冲突但没有错误,但没有图层可见。非常感谢任何建议。
This github solution - 使用自定义函数 ggmap_bBox()
从 ggmap 对象中提取边界框 - 仅成功向上述警告添加另一个警告:
Warning message:
In st_is_longlat(x) :
bounding Box has potentially an invalid value range for longlat data
解决方法
您似乎正在尝试绘制伦敦上空的 sf
火山对象,但您已将其定义为 lon/lat 0,0。除此之外,您对 ggmap
和 geom_sf
的调用工作正常。问题只是 sf 对象不在 ggmap 的边界框中。
我不得不将其更改为“空间”对象以使用 maptools::elide
移动它,然后返回到“sf”对象,因为我找不到移动 sf 多边形的简单方法。偏移是眼球近似值。
sf_moved <- sf %>%
st_transform(3857) %>% # <- may be unnecessary
as('Spatial') %>%
maptools::elide(.,shift = c(-80000,6650000)) %>%
as('sf') %>%
st_set_crs(3857) %>%
st_transform(4326)
ggmap(map) +
geom_sf(data = sf_moved,inherit.aes = FALSE,col = NA,aes(fill = layer),alpha = .4) +
scale_fill_viridis_c()