r - 将 ggmap crs 与 geom_sf 对齐并使用 coord_sf 应用地图限制时出现问题
问题描述
我正在尝试创建一个在顶部绘制空间数据的地图。我正在使用 ggmap 跟踪示例,然后使用 geom_sf 添加新西兰海岸线。我有两个问题:
- map_data(nz) 的投影与 ggmap 的投影不匹配,因此海岸线未与地图对齐,即使两者都在 WGS84 经纬度。
- 当我尝试将 coord_sf(xlim, ylim) 应用于绘图时,出现 st_cast.POINT 错误:
恐怕reprex需要一个谷歌密钥。这篇文章中的方法对我不起作用
library(sf)
library(dplyr)
library(ggmap)
nz <- map_data("nz") %>%
st_as_sf(coords = c("long", "lat"), remove = FALSE, crs = st_crs(4326)) %>%
group_by(group) %>%
summarise(
region = region[1],
do_union = FALSE
) %>%
st_cast("LINESTRING") %>%
ungroup()
gkey <- readLines("sjrw_google_key.dat")
register_google(key = gkey)
basemap <- get_map(location = c(lon = 175.5, lat = -38),
zoom = 8,
maptype = 'terrain-background',
source = 'stamen')
attr(basemap, "bb")
#> ll.lat ll.lon ur.lat ur.lon
#> bottom -39.37417 173.7449 -36.604 177.2606
ggmap(basemap) +
geom_sf(data = nz, inherit.aes = FALSE) +
coord_sf(crs = st_crs(4326)) +
coord_sf(xlim = c(174.5, 176.5), ylim = c(-39.2, -36.6))
#> Coordinate system already present. Adding new coordinate system, which will replace the existing one.
# Error in st_cast.POINT(x[[1]], to, ...) :
# cannot create MULTILINESTRING from POINT
由reprex 包于 2021-10-21 创建(v2.0.1)
解决方案
这有点棘手,因为我无法在没有 API 的情况下重新创建示例。我不使用ggmap
自己,所以我不确定,但它听起来像coord_sf()
(或它的限制)不喜欢ggmap
?
您如何通过在获取底图时提供限制来准确检索要绘制的区域,例如在此示例中R:裁剪/缩放地图
或者这个示例描述了将特定区域下载为底图https://gis.stackexchange.com/questions/155334/ggmap-clip-a-map
此外,您不应该有两条单独的行用于coord_sf()
; 第二个将覆盖第一个,您也可能没有第一个。也许是因为crs
被覆盖/忽略,限制与数据坐标不匹配?将这些组合成一行,看看会发生什么。或者,不要将 crs 设置在里面coord_sf()
;尝试使用data = nz %>% st_transform(4326)
ingeom_sf()
代替。
推荐阅读
- android - 在 Android Firefox 上添加到主屏幕不会屏蔽图标
- python - 使用 Spacy Python 将名称替换为序列号
- r - 用于条件分解的 R 浮点问题
- robotframework - 运行关键字并返回状态在关键字结束之前卡住
- unity3d - Unity 中用于 MRTKv2/Hololens2 的 2D 屏幕叠加
- laravel - 无法将类添加到 Laravel 表单选择
- reactjs - 你能帮助解决 react-native 中的错误吗
- virtual-machine - 在 Virtual Box 中导入 Kali 后出现黑屏?
- node.js - conv.data 在 DialogFlow 的后续意图中丢失
- multithreading - 特征,并行 ConjugateGradient 失败:更多线程,更多成本