Draw Network in R (control edge thickness plus non-overlapping edges)

后端 未结 4 789
醉话见心
醉话见心 2021-01-30 15:27

I need to draw a network with 5 nodes and 20 directed edges (an edge connecting each 2 nodes) using R, but I need two features to exist:

  1. To be able to control the
4条回答
  •  迷失自我
    2021-01-30 15:45

    If it is ok for the lines to be curved then I know two ways. First I create an edgelist:

    Edges <- data.frame(
        from = rep(1:5,each=5),
        to = rep(1:5,times=5),
        thickness = abs(rnorm(25)))
    
    Edges <- subset(Edges,from!=to)
    

    This contains the node of origin at the first column, node of destination at the second and weight at the third. You can use my pacake qgraph to plot a weighted graph using this. By default the edges are curved if there are multiple edges between two nodes:

    library("qgraph")
    qgraph(Edges,esize=5,gray=TRUE)
    

    qgraph

    However this package is not really intended for this purpose and you can't change the edge colors (yet, working on it:) ). You can only make all edges black with a small trick:

    qgraph(Edges,esize=5,gray=TRUE,minimum=0,cut=.Machine$double.xmin)
    

    For more control you can use the igraph package. First we make the graph:

    library("igraph")
    g <- graph.edgelist(as.matrix(Edges[,-3]))
    

    Note the conversion to matrix and subtracting one because the first node is 0. Next we define the layout:

    l <- layout.fruchterman.reingold(g)
    

    Now we can change some of the edge parameters with the E()function:

    # Define edge widths:
    E(g)$width <- Edges$thickness * 5
    
    # Define arrow widths:
    E(g)$arrow.width <- Edges$thickness * 5
    
    # Make edges curved:
    E(g)$curved <- 0.2
    

    And finally plot the graph:

    plot(g,layout=l)
    

    igraph

提交回复
热议问题