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

时间:2019-01-08 22:53:50

标签: r ggplot2 gis map-projections sf

我想用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地图,但是将坐标投影到其原始纬度/经度附近:

Map of NC and one weird coordinate.

我尝试了各种组合,首先将点转换为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 

1 个答案:

答案 0 :(得分:4)

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