--- title: "Stat 5421 Lecture Notes: Graphical Models" author: "Charles J. Geyer" date: "`r format(Sys.time(), '%B %d, %Y')`" output: html_document: md_extensions: -tex_math_single_backslash mathjax: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML pdf_document: md_extensions: -tex_math_single_backslash --- # License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0/). # R * The version of R used to make this document is `r getRversion()`. * The version of the `rmarkdown` package used to make this document is `r packageVersion("rmarkdown")`. * The version of the `network` package used to make this document is `r packageVersion("network")`. # 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](../notes/graph.pdf). This is just about drawing graphs using R. [TIMTODWI](https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it). There is an [R task view on graphical models](https://cloud.r-project.org/web/views/gR.html) 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](../notes/graph.pdf#page=2). 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. ```{r make.graph} nodeset <- LETTERS["U" <= LETTERS & "Y" != LETTERS] nodeset 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 ``` Now we can plot it. ```{r label=plot.graph,fig.align="center",fig.cap="A Directed Graph"} library(network) bar <- network(foo) plot(bar, displaylabels = TRUE) ``` If we want an undirected graph, we have to remake the network object. ```{r plot.undirected,fig.align="center",fig.cap="An Undirected Graph"} bar <- network(foo, directed = FALSE) plot(bar, displaylabels = TRUE) ``` 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](undirected.png)