igraph绘图报错:如何按指定坐标绘制足球球员位置网络图?
解决igraph绘制指定坐标有向图的报错问题
问题说明
我有一个包含3列的传球数据DataFrame(示例代码如下),希望用igraph绘制有向图,让每个球员顶点处于指定坐标。但运行现有代码时出现报错:
Error in norm_coords(layout, -1, 1, -1, 1) : `layout' not a matrix
实际数据包含32个唯一ID、252行,需要高效为每个ID指定位置的方法。
示例数据代码:
id <- c("Muller", "Muller", "Ter Stegen", "Musiala", "Musiala", "Musiala", "Pavard") tid <- c("Davies", "De Ligt", "Muller", "Kimmich", "Pavard", "Lewandowski", "De Ligt") Passes <- c(14, 5, 1, 10, 23, 4, 1) Passes <- data.frame(id, tid, Passes)
现有报错的绘图代码:
g <- graph.data.frame(Passes, directed = TRUE) set_edge_attr(g, "weight", value= E(g)$Passes) coords <- data.frame(id = c("Ter Stegen", "Musiala", "Davies", "Kimmich", 'De Ligt', "Lewandowski", "Muller", "Pavard"), x= c(0.5, 1, 1, 1, 2, 3, 3, 3.5), y= c(1, 1.8, 1.4, 1, 0.6, 1.8, 1.6, 1.2)) plot(g, vertex.size= 2, edge.arrow.size = 0.3, vertex.label.cex = 0.8, edge.curved=.2, asp = 0, vertex.label.dist=0.7, layout=coords, xlim = c(0, 4), ylim = c(0, 2))
报错原因
igraph的layout参数要求传入数值矩阵,且矩阵的行顺序必须与图中顶点的顺序(V(g)$name返回的顺序)完全对应。你传入的是dataframe,且坐标表的ID顺序和图顶点顺序不匹配,因此触发报错。
解决方法
1. 修正坐标格式与顺序
将坐标dataframe转换为矩阵,并按照图的顶点顺序重新排序:
# 提取图的顶点顺序 vertex_order <- V(g)$name # 按照顶点顺序重新排列坐标表,确保每个顶点都有对应坐标 coords_sorted <- coords[match(vertex_order, coords$id), ] # 提取x、y列转换为矩阵(这一步是关键) layout_matrix <- as.matrix(coords_sorted[, c("x", "y")])
2. 完整修正后的绘图代码
g <- graph.data.frame(Passes, directed = TRUE) set_edge_attr(g, "weight", value= E(g)$Passes) # 定义坐标表 coords <- data.frame(id = c("Ter Stegen", "Musiala", "Davies", "Kimmich", 'De Ligt', "Lewandowski", "Muller", "Pavard"), x= c(0.5, 1, 1, 1, 2, 3, 3, 3.5), y= c(1, 1.8, 1.4, 1, 0.6, 1.8, 1.6, 1.2)) # 处理坐标为符合要求的矩阵 vertex_order <- V(g)$name coords_sorted <- coords[match(vertex_order, coords$id), ] layout_matrix <- as.matrix(coords_sorted[, c("x", "y")]) # 绘图 plot(g, vertex.size= 2, edge.arrow.size = 0.3, vertex.label.cex = 0.8, edge.curved=.2, asp = 0, vertex.label.dist=0.7, layout=layout_matrix, xlim = c(0, 4), ylim = c(0, 2))
3. 批量处理32个ID的高效方法
如果你的实际数据有32个唯一ID,提前准备好包含所有ID的坐标表(确保无遗漏),然后用上述match方法自动对齐顺序即可,无需手动调整:
# 假设你有包含所有32个ID的完整坐标表full_coords full_coords <- data.frame( id = c("ID1", "ID2", ..., "ID32"), # 所有32个球员ID x = c(...), # 对应x坐标 y = c(...) # 对应y坐标 ) # 处理坐标矩阵 vertex_order <- V(g)$name coords_sorted <- full_coords[match(vertex_order, full_coords$id), ] layout_matrix <- as.matrix(coords_sorted[, c("x", "y")]) # 绘图 plot(g, layout=layout_matrix, ...) # 其他参数按需调整
这样就能保证每个顶点都匹配到正确的坐标,同时符合igraph对layout参数的格式要求。
内容的提问来源于stack exchange,提问作者Emmy W
相关产品推荐
相关产品推荐

