You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中使用tbl_graph计算路网两点间驾驶距离

基于tbl_graph计算路网节点间驾驶距离的实现方法

核心思路

tbl_graph是基于igraph的扩展工具,直接利用igraph的最短路径函数,就能以你添加的edge_length作为权重,计算两个节点间的驾驶距离。

具体实现步骤

  1. 加载依赖包
    确保已加载igraph和tidygraph:
library(igraph)
library(tidygraph)
  1. 计算节点间最短驾驶距离
    假设你的路网tbl_graph对象名为road_graph,直接调用shortest.paths()函数:
# 计算n1(110393)和n2(319271)之间的最短路径距离
driving_dist <- shortest.paths(
  graph = road_graph,
  v = 110393,  # 起点节点ID
  to = 319271, # 终点节点ID
  weights = E(road_graph)$edge_length, # 用edge_length作为权重
  mode = "all" # 双向路网用"all";单向路网需改为"out"或"in"
)

# 转换为数值格式并输出
driving_dist <- as.numeric(driving_dist)
cat("驾驶距离:", driving_dist, "\n")
  1. 可选:可视化最短驾驶路径
    如果需要将路径可视化,用ggraph配合ggplot2实现:
library(ggraph)
library(ggplot2)

# 获取最短路径的节点序列
path_nodes <- shortest.paths(
  road_graph,
  v = 110393,
  to = 319271,
  weights = E(road_graph)$edge_length,
  mode = "all",
  output = "vpath"
)[[1]]

# 给路网标记路径节点
road_graph_with_path <- road_graph %>%
  activate(nodes) %>%
  mutate(is_on_path = node_id %in% path_nodes)

# 绘制路径图
ggraph(road_graph_with_path, layout = "manual", x = x, y = y) +
  geom_edge_link(color = "gray80", alpha = 0.3) + # 绘制全部路网
  geom_edge_link(
    data = . %>% activate(edges) %>% filter(from %in% path_nodes & to %in% path_nodes),
    color = "red", size = 1 # 高亮最短路径
  ) +
  geom_node_point(aes(color = is_on_path), size = 0.6) +
  scale_color_manual(values = c("FALSE" = "black", "TRUE" = "red")) +
  theme_void()

注意事项

  • 确认节点ID的类型与tbl_graph中存储的一致,若节点ID为字符型,需把110393和319271转为字符传入。
  • 注意edge_length的单位(米/公里),可根据需求转换(比如除以1000得到公里数)。
  • 若路网包含单向通行路段,需根据实际方向调整mode参数("out"表示起点到终点的单向,"in"则相反)。

内容的提问来源于stack exchange,提问作者stats_noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:52:26