rgraphigraphtidygraph

Network Graph in R


I want to build a network diagram from a dataframe that I have, but I am having troubles.

This is what the dataframe looks like.

Shop Manager
S1 34
S1 12
S2 11
S2 34
S3 34
S4 50

For example, S1 should be connected to S2 and S3 since they have the same manager and so on. Also, is it possible to set the size of the dot based on the number of managers a shop has?

I really appreciate the help. Thanks!


Solution

  • You can try graph_from_adjacency_matrix + tcrossprod + table

    library(igraph)
    g <- graph_from_adjacency_matrix(as.dist(tcrossprod(table(df))))
    

    and plot(g) shows the network like below

    enter image description here


    Another way is bipartite.projection

    df %>%
      graph_from_data_frame() %>%
      set_vertex_attr(name = "type", value = names(V(.)) %in% df$Shop) %>%
      bipartite.projection() %>%
      pluck(2) %>%
      plot()
    

    Data

    > dput(df)
    structure(list(Shop = c("S1", "S1", "S2", "S2", "S3", "S4"), 
        Manager = c(34L, 12L, 11L, 34L, 34L, 50L)), class = "data.frame", row.names = c(NA,
    -6L))
    

    enter image description here