使用igraph实现环形网络图顺时针布局并固定节点a于顶部
顺时针排布环形图的修改方案
核心修改点
原代码基于layout_in_circle生成的环形布局默认沿逆时针方向环绕,虽然能通过旋转坐标把节点a固定在顶部,但环绕方向不符合顺时针要求。只需两步调整即可实现目标:
- 对初始环形布局的x轴坐标做取反操作,把原本逆时针的圆周走向翻转为顺时针,该操作不会改变节点在圆周上的相对间距
- 完全保留原有
rot函数的坐标旋转逻辑,确保节点a始终对齐到环形最顶端的位置
修改后可直接运行的代码
library('igraph') nodes <- c('a','b','c','d') x <- c(0,1,2,3) y <- c(0,1,2,3) from <- c('a','b','c','d') to <- c('b','c','d','a') NodeList <- data.frame(nodes, x ,y) EdgeList <- data.frame(from, to) net <- graph_from_data_frame(vertices = NodeList, d= EdgeList, directed = TRUE) # rotate rows of matrix mat so that row number mx is at top # where mx defaults to row having largest value in 2nd column rot <- function(mat, mx = which.max(mat[, 2])) { if (mx == 1) mat else mat[c(mx:nrow(mat), 1:(mx-1)), ] } # 生成环形布局,翻转x坐标切换为顺时针方向 circle_layout <- layout_in_circle(net) circle_layout[, 1] <- -circle_layout[, 1] plot(net, layout = rot(circle_layout))
最终效果
修改后的图会保持节点a在环形正顶部的位置,带方向的边沿顺时针方向依次串联a、b、c、d四个节点,完全符合顺时针排布的要求。
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

