License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0/).

R

Drawing Graphs

This is not the lecture notes about graphic models for categorical data. That is in a PDF done via knitr rather than R markdown.

This is just about drawing graphs using R. TIMTODWI. There is an R task view on graphical models that list 8 CRAN packages and 2 Bioconductor packages for dealing with graphical models.

We will just illustrate using R package network. We will draw the graphs that are Figures 1 and 2 of the other notes.

R function network in R package network makes objects of class "network" that can then be plotted. It wants the graph presented as an adjacency matrix which is a matrix whose row and column indices are nodes of the graph and the entries of the matrix are zero if there is no edge from one node to another and one otherwise. We can use the same matrix for both directed and undirected graphs. So we set up the matrix for Figure 2.

nodeset <- LETTERS["U" <= LETTERS & "Y" != LETTERS]
nodeset
## [1] "U" "V" "W" "X" "Z"
foo <- matrix(0, nrow = length(nodeset), ncol = length(nodeset))
rownames(foo) <- colnames(foo) <- nodeset
foo["V", "W"] <- foo["W", "X"] <- foo["W", "Z"] <- foo["X", "Z"] <- 1
foo
##   U V W X Z
## U 0 0 0 0 0
## V 0 0 1 0 0
## W 0 0 0 1 1
## X 0 0 0 0 1
## Z 0 0 0 0 0

Now we can plot it.

library(network)
## network: Classes for Relational Data
## Version 1.16.1 created on 2020-10-06.
## copyright (c) 2005, Carter T. Butts, University of California-Irvine
##                     Mark S. Handcock, University of California -- Los Angeles
##                     David R. Hunter, Penn State University
##                     Martina Morris, University of Washington
##                     Skye Bender-deMoll, University of Washington
##  For citation information, type citation("network").
##  Type help("network-package") to get started.
bar <- network(foo)
plot(bar, displaylabels = TRUE)
A Directed Graph

A Directed Graph

If we want an undirected graph, we have to remake the network object.

bar <- network(foo, directed = FALSE)
plot(bar, displaylabels = TRUE)
An Undirected Graph

An Undirected Graph

Every time you redo your plots, the graph nodes will be in different positions. But this doesn't matter. The nodes don't really have positions, only connections (edges).

On the other hand, one can just draw the graph in some drawing application and include it in the Rmarkdown Undirected Graph