【问题标题】:sf to data.frame: why as_Spatial needed before as.data.framesf 到 data.frame:为什么在 as.data.frame 之前需要 as_Spatial
【发布时间】:2020-11-04 22:27:51
【问题描述】:

假设我想为 geom_sf() 绘图添加标签,以获得以下信息:

截至 2020 年 11 月,该方法不存在,因此我收到警告,但尝试时未绘制任何内容:

library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
ggplot() +
  geom_sf(data = nc, aes(label = CNTY_ID))

 Warning message:
 Ignoring unknown aesthetics: label

当尝试通过 geom_text() 手动添加标签时,我不知道如何从 nc 转到可以在ggplot:

如果我尝试以下操作,则输出不符合预期:

nc2 <- nc %>% st_centroid() %>%        # ok, transform multypoligon to centroid
  as.data.frame()                      # does not return something useful, WHY ?

但如果我这样做:

nc2 <- nc %>% st_centroid() %>%  
  as_Spatial() %>%                     # this is nonsense, why ?
  as.data.frame()

现在,使用以下内容,我可以得到最初想要的带有适当标签的图。

ggplot() +
  geom_sf(data = nc) +
  geom_text(data=nc2, aes(coords.x1, coords.x2, label=CNTY_ID))

sf tibble/data.frame 到的推荐方式是什么 格图?在我看来这是一项普通的任务,必须经过两个步骤 (as_Spatial() + as.data.frame()) 是错误的。

【问题讨论】:

标签: r ggplot2 sf geom-text


【解决方案1】:

您可以在 ggplot 中使用 stat_sf_coordinatesgeom = "text"。您甚至不需要创建第二个数据框;您可以将st_centroid 作为参数传递。

以下实际上是一个完整的代表,应该适用于任何安装了最新版本的 ggplot2 和 sf 的人:

ggplot2::ggplot(sf::st_read(system.file("shape/nc.shp", package = "sf"))) +
  ggplot2::geom_sf() +
  ggplot2::stat_sf_coordinates(fun.geometry = sf::st_centroid,
                               ggplot2::aes(label = CNTY_ID), geom = "text")

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多