简体   繁体   中英

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

I need to make a simple plot for a weighted undirected graph, in which the only edges are between a single central node and some others (ie a star network topology), so I just need my nodes to be equally spaced (ie same angle between each consecutive pair of nodes) around the central one. However, my edges are weighted and I'd like the edge length to be proportional to the weight values. Is there any way to accomplish this in R or Python? I've been looking into the igraph package but can't seem to find a suitable layout. This is the example data frame I'm using:

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

Thanks for your help!

I don't believe there is a specific layout designed to do this, but you can achieve this effect in a pretty straightforward way by creating a set of layout coordinates and then scaling them by your weights.

Example code in R below:

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)

Created on 2019-02-07 by the reprex package (v0.2.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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