sf
包似乎比sp
更加用户友好,用来处理空间数据。例如,如果我有一组纬度/经度坐标,我可以很容易地在ggplot2
的开发版本中绘制:
library(sf)
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
# generate some data
set.seed(123)
y = rnorm(10, mean=40, sd=20)
x = rnorm(10, mean=-100, sd=30)
# collect to data.frame
xy = data.frame(x=x,y=y)
# create sf object
xy.sf = sf::st_as_sf(xy, coords=c("x", "y"), crs=4269)
# plot points
ggplot(data=xy.sf) + geom_sf()
ggplot2::geom_sf
函数知道 xy.sf
对象的几何形状是一组点,因此我不需要调用 ggplot2::geom_point()
等函数。但是,假设我想基于这组点添加另一个几何图形。
例如,如果我想生成一个轮廓层来显示点的聚集情况,我可以使用
ggplot2::geom_density2d
或 ggplot2::stat_density2d
,如此答案和此答案中所建议的那样。然而,以下代码:
ggplot(data=xy.sf) +
geom_sf() +
geom_density2d(data=xy.sf, aes(x=x,y=y,colour=..level..))
生成了以下图像:
请注意,等高线似乎具有反转的坐标!
我尝试调整上面的代码,但无法使其正常工作。我意识到sf
包是相当新的,但这张地图非常接近正确!有什么想法吗?
编辑:忘记添加会话信息
> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_2.2.1.9000 sf_0.4-3
loaded via a namespace (and not attached):
[1] Rcpp_0.12.9 magrittr_1.5 maps_3.1.1 units_0.4-4
[5] MASS_7.3-47 munsell_0.4.3 geosphere_1.5-5 colorspace_1.3-2
[9] lattice_0.20-35 rjson_0.2.15 jpeg_0.1-8 rlang_0.1.1
[13] stringr_1.2.0 udunits2_0.13 plyr_1.8.4 tools_3.4.0
[17] rgdal_1.2-5 grid_3.4.0 gtable_0.2.0 png_0.1-7
[21] DBI_0.5-1 ggthemes_3.3.0 lazyeval_0.2.0 assertthat_0.1
[25] digest_0.6.12 tibble_1.3.1 ggmap_2.6.1 reshape2_1.4.2
[29] mapproj_1.2-4 labeling_0.3 sp_1.2-4 stringi_1.1.2
[33] compiler_3.4.0 RgoogleMaps_1.4.1 scales_0.4.1 proto_1.0.0
sf
的最新版本是0.5-1,但它需要GDAL 2.0或更高版本,我还没有安装。) - eipi10sf
0.5.1。 - GGambasf
0.5.1。仍然能够正确地绘制图形。但是,如果我明确地反转坐标,即geom_density2d(aes(x=y, y=x, colour=..level..))
,则我可以重现你的图形。 - eipi10x
为y
,y
为x
,这对于data.frame
没有关系,但对于geom_density2d
有影响。这解决了我在“真实”数据中遇到的问题,其中我一直收到错误x not found
。那是因为geom_density2d
没有从xy.sf
获取x
,而是从向量x
本身获取!当我删除x
时,我会得到相同的错误。 - juan