0

So this question has been asked here and here... but I cant seem to adapt it to my problem. I am trying to create a bipartite graph using the igraph package in R, that looks something like this:

graph

The code im using to try this is:

# create all pairs and turn into vector for graph edges
pairs <- expand.grid(1:6, 1:6) # create all pairs
pairs <- pairs[!pairs$Var1 == pairs$Var2, ] # remove matching rows
ed <- as.vector(t(pairs)) # turn into vecotr


# create graph
g <- make_empty_graph(n = 6)
g <- add_edges(graph = g, edges = ed)
plot(g)

This will a create a graph... but im trying to make it resemble the graph in the image, with, say, (1,2,3) on the top and (4,5,6) on the bottom.

I tried using make_bipartite_graph() and layout_as_bipartite... but I cant seem to get it to work... any suggestions?

Electrino
  • 2,636
  • 3
  • 18
  • 40
  • The data and the graph you posted do not seem to have anything to do with one another. To create a graph you should have an incidence matrix or a matrix/data.frame with at least 2 columns, the edges' end points. – Rui Barradas Feb 09 '21 at 19:26
  • I'll edit the question to make it more clear – Electrino Feb 09 '21 at 19:28

1 Answers1

2

If the graph is created straight from the data.frame it will not be a bipartite graph.

library(igraph)

g <- graph_from_data_frame(df)
is.bipartite(g)
#[1] FALSE

But it will be a bipartite graph if created from the incidence matrix.

tdf <- table(df)
g <- graph.incidence(tdf, weighted = TRUE)
is.bipartite(g)
#[1] TRUE

Now plot it.

colrs <- c("green", "cyan")[V(g)$type + 1L]
plot(g, vertex.color = colrs, layout = layout_as_bipartite)

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thanks. I wonder would it be possible to use this type of layout with `ggnet2` from the `GGally` package? I will post a separate question for this. – Electrino Feb 09 '21 at 20:14