Search code examples
rdiagram

Visualizing an association btw two discrete variables via diagram in R


Assume two variables (state and group). Instances of state (s) may share a property with specific instances of group (g). For example, s1, s2 and s3 may have an association with g1.

I would like to visualize the association between the two variables in the form of a diagram like to one displayed below:

enter image description here

I would like to generate such a diagram with R. What R package would you recommend me to use?


Solution

  • Based on the suggestion of lukeA, I came up with the following code that addresses the above-mentioned need.

    In Shell:

    $ cat table
    s1  g1
    s2  g1
    s3  g1
    s4  g2
    s5  g2
    s6  g2
    s7  g3
    s8  g4
    s9  g5
    s10 g5
    

    In R:

    library(igraph)
    
    # Reading data from file
    m <- as.matrix(read.table(file="~/Desktop/table", sep="\t"))
    
    # Generating igraph
    g <- graph_from_edgelist(m, directed=FALSE)
    V(g)$type <- bipartite.mapping(g)$type
    coords <- layout_as_bipartite(g)
    
    # Plotting operations
    plot.igraph(g, layout = -coords[,2:1]) # Preliminary plotting (why necessary?)
    plot.igraph(g, layout = -coords[,2:1],
        vertex.shape="rectangle", # For vertex.foo and edge.foo commands, see: http://igraph.org/r/doc/plot.common.html
        vertex.size=50,
        vertex.size2=20,
        vertex.color=NA,
        vertex.label.color= "black")
    
    # Adding title to plot
    title("My first igraph")
    

    enter image description here