【问题标题】:Limit Simple Features Plot based on geojson Polygon基于 geojson 多边形的限制简单特征图
【发布时间】:2020-03-07 11:01:27
【问题描述】:

我想根据 geojson 中定义的多边形来限制绘图,以便它只显示蓝色阴影区域 here

即只需绘制内部的特征,包括环路。

geojson 可用here

最好在边缘添加一个缓冲区以包括环路。

我绘制所有特征的代码(不受geojson限制)。

library(tidyverse)
library(osmdata)

bounding_box <- getbb("Birmingham", featuretype = "city")

streets <- bounding_box %>%
  opq()%>%
  add_osm_feature(key = "highway", 
                  value = c("motorway", "trunk", "primary", "secondary", "tertiary")) %>%
  osmdata_sf()

ggplot() +
  geom_sf(data = streets$osm_lines,
          inherit.aes = FALSE,
          color = "grey",
          size = 1) +
  theme_void() +
  theme(
    plot.background = element_rect(fill = "white"),
    legend.position = "none"
  ) +
  coord_sf(xlim = c(-1.933, -1.869),
       ylim = c(52.46,  52.496),
       expand = FALSE) 

【问题讨论】:

    标签: r ggplot2 geospatial sf


    【解决方案1】:

    我在下面假设对象streets 已经通过运行问题中代码的前几行来定义。下一步是使用 read_sf()sf 包中读取多边形。下一行转换为更合适的坐标系(OSGB 1936 / British National Grid),因为在 lon/lat 坐标中无法添加以米为单位的缓冲区。使用st_buffer()添加一个40米的缓冲区,最后将坐标转换回WGS84:

    library(sf)
    area <- read_sf("~/Birmingham CAZ 2020.GeoJSON") %>%
            st_transform(27700) %>%
            st_buffer(units::set_units(40, m)) %>%
            st_transform(4326)
    

    当然,您需要使路径适应您实际存储文件的位置。然后我使用st_intersection() 提取位于多边形内部的streets$osm_lines 部分:

    streets_area <- st_intersection(poly, streets$osm_lines)
    

    最后,我使用您问题中的代码制作了情节。请注意,我在第二行添加了一个多边形图层,以证明街道确实位于多边形内:

    ggplot() +
      geom_sf(data = area) +
      geom_sf(data = streets_area,
              inherit.aes = FALSE,
              color = "grey",
              size = 1) +
      theme_void() +
      theme(
        plot.background = element_rect(fill = "white"),
        legend.position = "none"
      ) +
      coord_sf(xlim = c(-1.933, -1.869),
           ylim = c(52.46,  52.496),
           expand = FALSE)
    

    【讨论】:

    • 感谢@Stibu,这行得通。我现在意识到这个区域有点太小了,因为它切断了环路,所以将在 uMap 中手工制作一个稍大的区域。
    • @Chris 在 R 中可以轻松地在多边形周围添加缓冲区。如果您编辑问题以要求在多边形周围添加缓冲区,我可以将其包含在我的答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2018-01-24
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多