---
title: "DiagrammeR"
author: "Ella Kaye"
date: "06/04/2017"
output:
  html_document: default
  pdf_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(cache = FALSE)
```

```{r}
library("DiagrammeR")
```

This relates to the documentation available at http://rich-iannone.github.io/DiagrammeR/docs.html.

**Note that the function names in the NDF/EDF section have changes sinces the documentation was released.**

Here is a **Graphviz**

```{r}
grViz("
digraph rmarkdown {
A -> B 
}
", height = 200)
```

Here is a **mermaid**

```{r}
mermaid("
graph LR 
A --> B
", height = 200)
```

Reading in a .gv file
```{r}
grViz("graphvis-example.gv")
```

Reading in a .mmd file
```{r}
mermaid("mermaid-example.mmd")
```

## NDFs (node data frames) and EDFs (edge data frames)
```{r NDFs}
# Create a node data frame
nodes_1 <-
  create_node_df(
    n = 4,
    nodes = c("a", "b", "c", "d"),
    label = FALSE,
    type = "lower",
    style = "filled",
    color = "aqua",
    shape = c("circle", "circle",
              "rectangle", "rectangle"),
    data = c(3.5, 2.6, 9.4, 2.7))

# Create another node data frame
nodes_2 <-
  create_node_df(
    n = 4,
    nodes = 1:4,
    label = TRUE,
    type = "upper",
    style = "filled",
    color = "red",
    shape = "triangle",
    data = c(0.5, 3.9, 3.7, 8.2))
```

```{r EDFs}
# Create an edge data frame
edges_1 <-
  create_edge_df(
    from = c("a", "a", "b", "c"),
    to = c("b", "d", "d", "a"),
    rel = "requires",
    color = "green",
    data = c(2.7, 8.9, 2.6, 0.6))

# Create another edge data frame
edges_2 <-
  create_edge_df(
    from = c("e", "g", "h", "h"),
    to = c("g", "h", "f", "e"),
    rel = "receives",
    arrowhead = "dot",
    color = "red")
```

Combining the NDFs, combining the EDFs
```{r combine, eval = FALSE}
# now need items in the different 'nodes' columns to be the same type
all_nodes <- combine_ndfs(nodes_1, nodes_2)
all_edges <- combine_edfs(edges_1, edges_2)
```

## Graph creation
```{r}
# Create a simple NDF
nodes <-
  create_node_df(
    n = 4,
    nodes = 1:4,
    type = "number")

# Create a simple EDF
edges <-
  create_edge_df(
    from = c(1, 1, 3, 1),
    to = c(2, 3, 4, 4),
    rel = "related")

# N.B. the creation of attr_theme is new since the documentation
attr_theme <- list(graph_attrs = "layout = neato",
    node_attrs = "fontname = Helvetica",
    edge_attrs = "color = gray20")

# Create the graph object,
# incorporating the NDF and
# the EDF, and, providing
# some global attributes
graph <-
  create_graph(
    nodes_df = nodes,
    edges_df = edges,
    attr_theme = attr_theme
)

# View the graph
render_graph(graph)
render_graph(graph, output = "DOT")
```

### Random graph
```{r}
library(magrittr)
create_random_graph(n = 15, m = 30, set_seed = 30) %>%
  render_graph(output = "visNetwork")
```

