Visualizing an association btw two discrete variables via diagram in R

放肆的年华 提交于 2019-12-11 17:25:46

问题


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:

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


回答1:


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")



来源:https://stackoverflow.com/questions/48549137/visualizing-an-association-btw-two-discrete-variables-via-diagram-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!