【问题标题】:Error changing projection via coord_sf for geom_sf and geom_point at the same time通过 coord_sf 同时为 geom_sf 和 geom_point 更改投影时出错
【发布时间】:2019-06-03 16:22:12
【问题描述】:

我想用geom_sf 绘制地图并从另一个数据集中添加点,然后更改投影。例如:

# 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 地图,但是将坐标投影到远离其原始纬度/经度的位置:

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

会话信息(尝试更新 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 

【问题讨论】:

  • 当我说“投影”时,我可能指的是“坐标系”,GIS 有时会让我感到困惑。

标签: r ggplot2 gis map-projections sf


【解决方案1】:

您可以将点转换为 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))

【讨论】:

  • 泰!附加问题:crs = 4326st_as_sf 通话中重要吗?
  • 是的,您必须以某种方式为 sf 对象分配 crs(也可以这样做 st_as_sf() %&gt;% st_set_crs(4326)),以便 coord_sf 知道要转换的内容。
猜你喜欢
  • 2021-03-13
  • 2019-04-15
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 2021-12-07
相关资源
最近更新 更多