微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 terra SpatRaster 作为 ggmap 底图

如何解决使用 terra SpatRaster 作为 ggmap 底图

总结:如何使用 SpatRaster 对象作为 ggmap 的底图?

嗨,我正在使用 ggplot 在 R 中制作地图。我想要来自 OpenStreetMaps 的底图,然后我想在顶部绘制多边形等。

ggmap 包曾经是完美的,但现在使用谷歌地图太复杂了,OpenStreetMaps 根本不起作用。

我遇到过 ggspatial::annotation_map_tile(),但它不允许使用那么多地图类型,而且速度也非常慢,所以我想尽可能避免使用它。

我还遇到过 maptiles::get_tiles(),它有更多选择,而且速度似乎更快。 ?

问题在于它返回的 SpatRaster 对象(来自 terra 包)不会自动用作 ggmap 的基本地图。 有办法转换吗?

通过查看 ggmap 的 get_stamenmap() 中发生的情况,我已经设法完成了部分任务,但地图显示为绿色。我认为这是因为 raster::raster()raster::as.raster() 不能像我希望它们在这种对象类型上那样工作,但我对这些类一无所知,所以我不知道去哪里下一个

library(dplyr)
library(ggmap)
library(sf)
library(maptiles)

nc <- st_read(system.file("shape/nc.shp",package = "sf"),quiet = TRUE)
nc_osm <- get_tiles(nc,crop = TRUE)

# This is what it should look like
plot_tiles(nc_osm)

what the map should look like

# I don't kNow these data types I'm trying to convert to
nc_ggmap <- nc_osm %>%
  raster::raster() %>%
  raster::as.raster()

# Set attributes manually,like in get_stamenmap()
class(nc_ggmap) <- c("ggmap","raster")
attr(nc_ggmap,"bb") <- data.frame(ll.lat = 33.8,ll.lon = -84.3,ur.lat = 36.5,ur.lon = -75.4)
attr(nc_ggmap,"source") <- ""

# Try to map it... green ?
nc_ggmap %>%
  ggmap()

the map looks ok,but green

顺便说一句,我已经设法使用 ggplot 绘制对象,通过计算每个像素的颜色并将它们用于 fill 美学,但我稍后需要对我的多边形使用该美学,这这就是为什么我非常热衷于使用 ggmap 方法

nc_osm %>%
  terra::as.data.frame(xy = TRUE) %>%
  as_tibble() %>%
  mutate(hex = rgb(lyr.1,lyr.2,lyr.3,maxColorValue = 255)) %>%
  ggplot(aes(x,y,fill = hex)) +
  geom_tile() +
  scale_fill_identity() +
  coord_fixed() +
  theme_void()

plotted with ggplot,but uses fill aesthetic

解决方法

我不太明白你的问题,因为在我看来你要求什么,然后你写道你设法找到了解决你一开始提出的问题的方法。

也就是说,如果您只需要一种以上的填充美感,您可以使用 ggnewscalehere。 通过这种方式,您可以为每个图层绘制具有不同填充(或颜色,如果需要)美学的多个图层。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。