# Simple Examples with DiagrammeR

UPDATE 2018-12-13: Based on a comment from @nmarkgraf, I added a section on how to export diagrammeR diagrams.

Here are some examples of diagrams build with DiagrammeR:

# Setup

library(tidyverse)
library(DiagrammeR)
library(DiagrammeRsvg)
library(magick)

# DiagrammeR using grViz()

Define the graph:

g1 <- "digraph boxes_and_circles {
graph [layout = circo,
overlap = true]
node [shape = circle,
fixedsize = true,
fontname = Helvetica,
width = 1]
Problem; Plan; Data; Analysis; Conclusion

edge [color = grey]
Problem -> Plan
Plan -> Data
Data -> Analysis
Analysis -> Conclusion
Conclusion -> Problem
}"

Print it to the screen:

grViz(g1)

This diagram is inspired by Figure 1 from the paper of Wild and Pfannkuch, 1999.

# Export

Note that RStudio provides an Export button in the Viewer pane.

# Convert to SVG, and export

SVG is an xml based markup language for defining 2D vector images see Wikipedia.

GraphViz can be described as follows:

Graphviz is open source graph visualization software. Graph visualization is a way of representing structural information as diagrams of abstract graphs and networks. It has important applications in networking, bioinformatics, software engineering, database and web design, machine learning, and in visual interfaces for other technical domains.

We can convert from GraphViz to SVG using this function:

svg <- grViz(g1) %>% export_svg() 

Save this SVG markup as a text file, and your browser will display it.

fileConn<-file("graph.svg")
writeLines(svg, fileConn)
close(fileConn)

# Convert SVG to PNG

There are a number of programs to convert from one image format to another. Image Magick is a popular tool (see this post for some discussion and problems).

Within R, one can call Image Magick, one can call IM using the magick package (see here).

img_svg <- image_read_svg('graph.svg', width = 400)
img_png <- image_convert(img_svg, "png")
image_write(img_png, path = "graph.png", format = "png")