首页 > 解决方案 > geom_sf 映射点/形状

问题描述

我正在使用 Tigris 包下载带有代码的形状文件,

options(tigris_class = "SF") 

虽然我可以轻松地映射多边形

ggplot(data=zctas) +
  geom_sf(aes())

我正在努力创建一个标记/点而不是一个填充的多边形(例如,一个形状 - 就像 zctas 内的一个圆圈),因为我从底格里斯岛拉下来的形状文件没有 x 的纬度/经度和 y AES 映射。形状文件有一个“几何”列,我想知道我是否可以使用它?

这里的文档,https://ggplot2.tidyverse.org/reference/ggsf.html

似乎表明geom_sf可以用来创建点?(我猜想使用 zctas 多边形的质心?)但我找不到一个例子?感谢任何资源来识别从这个 Tigris 生成的形状文件中映射点的代码,和/或提示和/或替代方法。

标签: rggplot2geospatialsftigris

解决方案


您正在寻找stat_sf_coordinates(),在此处描述

library(ggplot2)

nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `/Library/Frameworks/R.framework/Versions/3.6/Resources/library/sf/shape/nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> epsg (SRID):    4267
#> proj4string:    +proj=longlat +datum=NAD27 +no_defs

ggplot(nc) +
  geom_sf()

ggplot(nc) +
  geom_sf() +
  stat_sf_coordinates()
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
#> not give correct results for longitude/latitude data

ggplot(nc) +
  geom_sf() +
  geom_point(
    aes(color = SID74, size = AREA, geometry = geometry),
    stat = "sf_coordinates"
  ) +
  scale_color_viridis_c(option = "C") +
  theme(legend.position = "bottom")
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
#> not give correct results for longitude/latitude data

reprex 包(v0.3.0)于 2019-11-03 创建

关于最后一个示例调用中的geometry = geometry语句的一条评论:如果在数据集中找到几何列,两者都会自动映射几何列。但是,不知道几何列,因此不自动映射,因此我们必须手动映射。aes()geom_sf()stat_sf_coordinates()geom_point()


推荐阅读