rbipartite

How do you convert bipartite graph into a network matrix with colored cells?


I have a bipartite graph but I want to convert it into a cell matrix like the image below that I found from a paper. I find it much easier to read and visualize especially with my much larger datasets. I used the bipartite R package to create my bipartite graph, but now sure how to make a cell matrix with colored cells based on interaction values (I'd like to set the scale myself).

Here is the image, it is from this paper:

enter image description here

And if needed, here is my code and dput for a smaller version of my dataset:

code:

plotweb(data.mat,
        method="normal",
        text.rot = 90,
        labsize = 1,
        y.width.low = 0.05,
        col.high = "#66A61E",
        col.interaction = "#E6AB02",
        col.low = "#E7298A",
        bor.col.interaction =  NA,
        arrow="none",
        empty=TRUE,
        plot.axes=FALSE,
        ybig=1)

dataset:

> dput(data.mat)
structure(c(7336L, 1640L, 26293L, 111533L, 71255L, 161705L, 104046L, 
169975L, 395822L, 153999L, 6780L, 10866L, 131162L, 239110L, 130786L, 
88922L, 46725L, 99169L, 109625L, 203947L, 2258L, 550L, 47109L, 
1813L, 362753L, 14451L, 17025L, 30251L, 308L, 34412L, 11L, 0L, 
56988L, 1360L, 4L, 5L, 107L, 31L, 56L, 868L, 31775L, 31L, 327L, 
19L, 180L, 4284L, 77L, 27L, 0L, 854L, 5L, 143L, 4622L, 264L, 
7945L, 51L, 14545L, 32L, 8L, 126L, 66L, 0L, 6L, 14130L, 5L, 9L, 
165L, 1017L, 5L, 115L, 65L, 5L, 9572L, 77L, 820L, 165L, 521L, 
788L, 17L, 538L), dim = c(10L, 8L), dimnames = list(c("Arctium lappa", 
"Cichorium intybus", "Circium arvense", "Circium vulgare", "Hypericum perforatum", 
"Leucanthemum vulgare", "Plantago lanceolata", "Trifolium pratense", 
"Trifolium repens", "Tripleurospermum inodorum"), c("Cladosporium", 
"Alternaria", "Aureobasidium", "X....1", "Golovinomyces", "Podosphaera", 
"Ampelomyces", "X....2")))

I'd like to convert this into a matrix graph, and color cells from light to dark setting my own range if possible.


Solution

  • If we reshape the data a bit so we have one row per square, we can use geom_tile() to make the plot. For example

    library(ggplot2)
    as.data.frame(data.mat) |>
      tibble::rownames_to_column("id1") |>
      tidyr::pivot_longer(-id1, names_to="id2") |>
      ggplot() + 
        aes(id2, id1, fill=value) + 
        geom_tile() + 
        theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
    

    You wind up with enter image description here