【问题标题】:Cannot plot sf layer on top of ggmap无法在 ggmap 上绘制 sf 层
【发布时间】:2023-03-23 23:42:02
【问题描述】:

以前的一些问题的主题 - 例如。 this。我无法让 sf 层在 ggmap 层上呈现。

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, aes(fill = layer), 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

【问题讨论】:

    标签: r ggmap sf


    【解决方案1】:

    您似乎正试图在伦敦上空绘制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()
    

    【讨论】:

    • 天哪。新手错误 - 我忘记将范围分配给栅格对象extent(r) = e
    • 每个人都会遇到。分配范围会比我的方法容易得多!
    猜你喜欢
    • 2022-01-17
    • 2020-09-23
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    相关资源
    最近更新 更多