Search code examples
rdataframegraphdiagrammer

DiagrammeR: Devise a graph from a dataframe


Objective (In the R environment): extract nodes and edges from a dataframe to use them for modeling a graph!!

I am trying to learn how to work with DiagrammeR or any other graph modeling libraries in order to get a graph such as the one in below (you can follow the link [The GRAPH1]) from a data frame :

The data frame:

a b c classes
1 2 0  a
0 0 2  b
0 1 0  c

I have used DiagrammeR library and defined nodes and edges manually by these commands:

library(DiagrammeR)
egrViz("
digraph boxes_and_circles{
#add the node statement
node[shape=box]

a; b; c;
#add the nodge statement

a->a [label=1]; a-> b[label=2]; b->c[label=2]; c->b[label=1]



graph [nodesep=0.1]

}

  ")

Could you help me to understand how I can get the nodes and edges automatically? Thank you in advance.

enter image description here


Solution

  • You can do this with the igraph package. Your data frame is an adjacency matrix and igraph contains a function to make that into a graph. My code below adds a layout to position the vertices in the positions that you indicated in your sample graph.

    ## Your data
    df = read.table(text="a b c classes
    1 2 0  a
    0 0 2  b
    0 1 0  c", 
    header=TRUE)
    
    library(igraph)
    
    g = graph_from_adjacency_matrix(as.matrix(df[,1:3]), weighted=TRUE)
    LO = matrix(c(0,0,0,3,2,1), ncol=2)
    plot(g, layout=LO, edge.label=E(g)$weight, vertex.shape="rectangle",
        vertex.color="white", edge.curved=c(0,0,0.15,0.15))
    

    Graph from Adjacency Matrix