【问题标题】:create evenly spaced polylines over counties using R使用 R 在县上创建均匀间隔的折线
【发布时间】:2021-02-07 00:14:56
【问题描述】:

我想创建从北到南的等距多段线,每条线之间的间距为 50 英里,长 10 英里。不确定这是否可以使用 sf 包。在下面的示例中,我想让线条填充华盛顿州的县。


library(tigris)
library(leaflet)

states <- states(cb = TRUE)

counties<-counties(cb=TRUE)

counties<- counties%>%filter(STATEFP==53)

states<- states%>%filter(NAME=="Washington")

leaflet(states) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = "white",
              color = "black",
              weight = 0.5) %>%
  addPolygons(data=counties,color='red',fillColor = 'white')%>%
  setView(-120.5, 47.3, zoom=8)

我已更新,在下方添加了我想做的图片。

【问题讨论】:

  • 你只想要一条从西到东穿过华盛顿中部的垂直线吗?
  • 你能分享一张你想要输出的图像吗?
  • 我在上面的问题中添加了我想做的事情的图像。谢谢!

标签: r geospatial sf rgeo-shapefile


【解决方案1】:

您可以通过指定坐标从头开始创建multilinestring sf 对象。

您可以从华盛顿的extent(边界框)获取这些坐标,但您可能也有兴趣了解如何创建网格,我将在下面演示,因为它可能会有所帮助。

复制并粘贴这个可重现的示例:

library(tidyverse)
library(tigris)
library(leaflet)
library(sf)
library(raster)

states <- states(cb = TRUE)

# subset for WA and transform to a meter-based CRS 
states <- states %>% 
  filter(NAME == "Washington") %>% 
  st_transform(crs = 3857) # Mercator

# fifty miles in meters
fm <- 80467.2

# subset for Washington
states_sp <- as(states, "Spatial")

# create a grid, convert it to polygons to plot
grid <- raster(extent(states_sp), 
               resolution = c(fm, fm), 
               crs = proj4string(states_sp))
grid <- rasterToPolygons(grid)
plot(states_sp)
plot(grid, add = TRUE)

# find the top y coordinate and calculate 50 mile intervals moving south
ty <- extent(grid)[4]  # y coordinate along northern WA edge
ty <- ty - (fm * 0:7)  # y coordinates moving south at 10 mile intervals

# create a list of sf linestring objects
l <- vector("list", length(ty))
for(i in seq_along(l)){
  l[[i]]  <- 
    st_linestring(
      rbind(
        c(extent(grid)[1], ty[i]),
        c(extent(grid)[2], ty[i])
      )
    )
}

# create the multilinestring, which expects a list of linestrings
ml <- st_multilinestring(l) 

plot(states_sp)
plot(as(ml, "Spatial"), add = TRUE, col = "red")

如您所见,我使用函数as(sf_object, "Spatial")st_as_sf(sp_object)sfsp 对象之间来回切换。使用这些将数据转换为您的需求。

【讨论】:

  • 这与我所追求的非常接近。我已经用我想要实现的图像更新了这个问题。您的代码可以做到这一点吗?此外,如果没有其他答案,如果我无法得到我想要的东西,我会奖励你支票。感谢您的帮助!
  • 据我所知,没有开箱即用的功能可以准确地创建您正在寻找的内容,因此您需要通过测量以米为单位的距离从头开始创建多线串对象-based CRS,遍历列表以定义行st_linestring(rbind(c(x1, y1), c(x2,y1))),然后将这些列表元素绑定到具有st_multilinestring(my_list_of_lines) 的单个多行字符串对象中。我提供的内容应该可以让您大部分时间到达那里,您只需要更改坐标即可。
  • 听起来不错。我刚刚意识到我也可以每隔 X 英里将线路分开,这样就可以了。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多