gpt4 book ai didi

r - 同时通过 coord_sf 更改 geom_sf 和 geom_point 的投影时出错

转载 作者:行者123 更新时间:2023-12-01 22:09:40 29 4
gpt4 key购买 nike

我想用 geom_sf 绘制 map 并添加来自另一个数据集的点,然后更改投影。例如:

# setup
library(ggplot2)
library(sf)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
point <- data.frame(id = "hi", lat = 36, long = -80) # point inside NC

# can change projection
ggplot() +
geom_sf(data = nc) +
coord_sf(crs = st_crs(3347))

# can add a point
ggplot() +
geom_sf(data = nc) +
geom_point(data = point, aes(x = long, y = lat))

# but can't do both: see plot attached
ggplot() +
geom_sf(data = nc) +
geom_point(data = point, aes(x = long, y = lat)) +
coord_sf(crs = st_crs(3347))

见下图。其他两个图看起来很正常;最后一个转换 NC map 没问题,但投影坐标接近原始纬度/经度:

Map of NC and one weird coordinate.

我已经尝试了各种组合,首先将点转换为 sf 对象,在调用 ggplot 之前更改它们的投影以保持一致,但到目前为止都无济于事。任何建议都会有所帮助; PS 我对 GIS 还很陌生。

session 信息(尝试更新 R 和 sf/ggplot2 包):

> sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.2

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] sf_0.7-2 ggplot2_3.1.0

loaded via a namespace (and not attached):
[1] Rcpp_1.0.0 rstudioapi_0.8 bindr_0.1.1 magrittr_1.5
[5] units_0.6-2 tidyselect_0.2.5 munsell_0.5.0 colorspace_1.3-2
[9] R6_2.3.0 rlang_0.3.1 plyr_1.8.4 dplyr_0.7.8
[13] tools_3.5.2 grid_3.5.2 gtable_0.2.0 e1071_1.7-0
[17] DBI_1.0.0 withr_2.1.2 class_7.3-15 lazyeval_0.2.1
[21] assertthat_0.2.0 tibble_2.0.0 crayon_1.3.4 bindrcpp_0.2.2
[25] purrr_0.2.5 glue_1.3.0 labeling_0.3 compiler_3.5.2
[29] pillar_1.3.1 scales_1.0.0 classInt_0.3-1 pkgconfig_2.0.2

最佳答案

您可以将 point 转换为 sf 对象并设置 crs(也许您忘记设置 crs?)。这是因为 coord_sf 可以将图层转换为普通投影,但它们需要是 sf 对象才能知道如何执行此操作。

### add this below creation of point object
point <- st_as_sf(point, coords = c("long", "lat"), crs = 4326)

ggplot() +
geom_sf(data = nc) +
geom_sf(data = point) +
coord_sf(crs = st_crs(3347))

enter image description here

关于r - 同时通过 coord_sf 更改 geom_sf 和 geom_point 的投影时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100887/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com