geom_sf将点/形状映射。

7

我使用Tigris包下载代码中的shape文件,

options(tigris_class = "SF") 

虽然我可以轻易地绘制多边形


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

我正在努力创建标记/点而不是填充多边形(例如,像圆形一样在zctas内部),因为我从tigris下载的形状文件没有用于x和y AES映射的经纬度。该形状文件具有“geometry”列,我想知道是否可以使用它?文档https://ggplot2.tidyverse.org/reference/ggsf.html似乎表明geom_sf可用于创建点?(我猜测使用zctas多边形的重心?),但我找不到示例。非常感谢任何提示或其他方法来识别从此Tigris生成的形状文件映射点的代码资源。

1
很抱歉,看起来您似乎没有提供一个完全可重现的示例 - 您的ggplot调用对我无效。您能否尝试在全新的会话中运行您自己的代码,并发布可能缺失的信息?谢谢。 - tjebo
我在我的回答中添加了一个完全可重现的示例。@JaneA,我建议您相应地编辑您的问题。 - Claus Wilke
2个回答

13

您正在查找 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语句的评论:如果geom_sf()stat_sf_coordinates()在数据集中找到几何列,则会自动映射几何列。然而,geom_point()不知道几何列,并因此不会自动映射,因此我们必须手动映射。


5

如果我理解你想实现的功能正确,你可能只需要使用 st_centroid() 函数将数据转换为点……最基本的方式如下:

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

或者说:

ggplot(data=st_centroid(st_geometry(zctas))) +
  geom_sf()

更多细节和示例,请参见: https://r-spatial.github.io/sf/articles/sf5.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接