繁体   English   中英

在 R 中用 igraph 绘制图形:边长与权重成正比

[英]plotting graph with igraph in R: edge length proportional to weight

我需要为加权无向图绘制一个简单的图,其中唯一的边在单个中心节点和其他一些(即星型网络拓扑)之间,所以我只需要我的节点等距(即之间的角度相同)每对连续的节点)围绕中心节点。 但是,我的边缘是加权的,我希望边缘长度与权重值成正比。 有什么办法可以在 R 或 Python 中实现这一点吗? 我一直在研究 igraph 包,但似乎找不到合适的布局。 这是我正在使用的示例数据框:

d = data.frame("n1"=c('A','A','A','A'), "n2"=c('B','C','D','E'), "weight"=c(1,1.5,2,5))

谢谢你的帮助!

我不相信有专门的布局可以做到这一点,但是您可以通过创建一组布局坐标然后按权重缩放它们以非常简单的方式实现这种效果。

下面 R 中的示例代码:

library(igraph)

# toy data
d = data.frame("n1"=c('A','A','A','A'), "n2"=c('B','C','D','E'), "weight"=c(1,1.5,2,5))

g <- graph_from_data_frame(d)

# we can create a layout object that is just coordinate positions
coords <- layout_(g, as_star())
coords
#>               [,1]          [,2]
#> [1,]  0.000000e+00  0.000000e+00
#> [2,]  1.000000e+00  0.000000e+00
#> [3,]  6.123234e-17  1.000000e+00
#> [4,] -1.000000e+00  1.224647e-16
#> [5,] -1.836970e-16 -1.000000e+00

# Knowing this is a star the N nodes should have N-1 edges. We can scale
# The N-1 positions by the weights
weight.scale <- c(1, d$weight)

coords2 <- weight.scale * coords
coords2
#>               [,1]          [,2]
#> [1,]  0.000000e+00  0.000000e+00
#> [2,]  1.000000e+00  0.000000e+00
#> [3,]  9.184851e-17  1.500000e+00
#> [4,] -2.000000e+00  2.449294e-16
#> [5,] -9.184851e-16 -5.000000e+00

# we can inspect
plot(g, layout = coords2)

reprex 包(v0.2.1) 于 2019 年 2 月 7 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM