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

使用R语言igraph包绘制带地理坐标节点时位置错误的问题排查

Troubleshooting Incorrect Geographical Layout in igraph

Let's break down the issues in your code and fix them to get the correct geographic positioning of your nodes:

1. You're referencing the wrong vertex property for matching

When you create a graph with graph_from_data_frame(), the vertex names are stored in V(main)$name—not V(main)$from. The from field only exists in your original edge data frame, not as a vertex attribute. Your original code tried to match V(main)$from (which doesn't exist) to meta$name, leading to incorrect (or possibly NA) latitude/longitude values assigned to your vertices.

2. Your layout matrix has reversed coordinates

In standard geographic plotting, the x-axis corresponds to longitude (east-west position) and the y-axis corresponds to latitude (north-south position). You had latitude first in your matrix, which swaps the axes and puts nodes in the wrong places.

Fixed Full Code

library(igraph)

# Create edge data and graph
city <- data.frame(from = c("London", "Paris", "Beijing", "Berlin"), to = c("Beijing", "Berlin", "London", "Paris"))
main <- graph_from_data_frame(city)

# Metadata
meta <- data.frame(name = c("Paris", "Hong Kong", "London", "Rome", "Berlin", "Beijing", "Madrid"), 
                   latitude = c(48.52, 22.26, 51.30, 41.54, 52.30, 39.9, 40.23), 
                   longitude = c(2.17, 114.12, 0.10, 12.29, 13.25, 116.3, 3.43))

# Correctly assign vertex attributes using vertex names
V(main)$latitude <- meta$latitude[match(V(main)$name, meta$name)]
V(main)$longitude <- meta$longitude[match(V(main)$name, meta$name)]

# Build layout matrix with correct coordinate order: longitude (x) first, latitude (y) second
location <- matrix(c(V(main)$longitude, V(main)$latitude), ncol = 2)

# Plot with labels to verify positions
plot(main, vertex.label = V(main)$name, vertex.size = 8, edge.width = 1, layout = location)

What This Fixes

After running this code, you'll see:

  • Beijing (high longitude, mid latitude) on the far right
  • London (low longitude, high latitude) on the far left
  • Paris and Berlin clustered in the middle-left, matching their actual European locations

This should resolve the incorrect positioning issue you were seeing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:02:49