{spatstat} 的 `nearestsegment()` 会产生不精确的结果吗?

Does {spatstat}'s `nearestsegment()` produce imprecise results?

虽然图比较小,但可以看出有几个点/事件(浅红色)不在彩色线段上,反之亦然。这种偏差从何而来?有没有办法改进我的程序?

我为什么要这样做? 总体目标:

  1. 将点权重作为边权重附加到各个线段;
  2. 然后绘制线段颜色或权重比例(最好发明一些东西,比如热图)。
# Smallest reproducible example 
library(spatstat)
data("chicago")
N <- npoints(chicago)
# create some weights, later useful 
marks(chicago) <- rnorm(N, 5, 2) 

# find to each point nearest line segment 
idx <- nearestsegment(as.ppp(chicago), as.psp(chicago))

# not to my suprise this is quite similar to: 
# (i) retrieve network 
lns <- sf::st_as_sf(maptools::as.SpatialLines.psp(
  spatstat.geom::as.psp(chicago)))
# (ii) retrieve event coords 
events <- data.frame(xcoords = chicago[["data"]]$x,
                     ycoords = chicago[["data"]]$y)
# convert 
pnts <- sf::st_as_sf(events, coords = c("xcoords", "ycoords"))

# get nearest feature 
idx2 <- sf::st_nearest_feature(pnts, lns)

# one deviation 
which(idx != idx2)
#> [1] 1
idx[1]
#> [1] 37
idx2[1]
#> [1] 38

# my overall goal is to transmit the point weights to the 
# respective line segments. With those edge weights I would like to 
# plot some maps, therefore: 

# (I) create igraph object from chicago: 
library(igraph)

edges <- cbind(chicago[["domain"]][["from"]], chicago[["domain"]][["to"]])
chicago_net <- graph_from_edgelist(edges)
adjm <- as.matrix(as_adjacency_matrix(chicago_net))

g <- graph_from_adjacency_matrix(adjm, 'undirected')

vertex_attr(g, name = 'x') <- chicago[["domain"]]$vertices[["x"]]
vertex_attr(g, name = 'y') <- chicago[["domain"]]$vertices[["y"]]

# (II) add point weights as edge weights to graph according to idx: 
weights <- c(rep(NA, nrow(chicago[["domain"]]$lines[["ends"]])))
weights[idx2] <- chicago[["data"]]$marks
E(g)$weight <- weights

# finally plot g via ggraph [same result with igraph.plot()]
library(ggraph)

ggraph(g, x = vertex_attr(g)$x, y = vertex_attr(g)$y) +
  geom_edge_link0(aes(color = weight)) +
  # sth. practical from here: 
  # https://ggraph.data-imaginist.com/reference/scale_edge_colour.html
  scale_edge_colour_viridis() +
  geom_point(data = events, mapping = aes(x = xcoords, y = ycoords), 
             alpha = 0.3, size = 2, shape = 20, col = "red") +
  theme_void()

给予

reprex package (v2.0.1)

于 2022-05-25 创建

仅供参考?nearestsegment描述如下

Given a point pattern and a line segment pattern, this function finds the nearest line segment for each point.


迟早,我用{spatstat}所做的一切都会正常工作,因此我认为我犯了一个大错。

删除邻接矩阵计算;它重新排序图的片段
正确的 g 分配:

g <- graph_from_edgelist(edges)