Skip to content

Instantly share code, notes, and snippets.

@peterdalle
Last active October 31, 2018 16:36
Show Gist options
  • Save peterdalle/549704635c0d35d1303a6240bdcd0262 to your computer and use it in GitHub Desktop.
Save peterdalle/549704635c0d35d1303a6240bdcd0262 to your computer and use it in GitHub Desktop.
How to include DiagrammeR grViz() diagram and graphs in your RMarkdown
Include a DiagrammeR grViz() diagram into your RMarkdown document without the need to create a graph PDF file separately.
Based on the code from https://github.com/rich-iannone/DiagrammeR/issues/133#issuecomment-284370996.
```{r}
# Install packages.
install.packages(c("DiagrammeR", "DiagrammeRsvg", "rsvg", "magrittr"))
```
```{r}
# Function to create graph for PDF's.
create_pdf_diagram <- function(filename, code, dpi=NULL){
utils::capture.output({
DiagrammeR::grViz(code) %>%
DiagrammeRsvg::export_svg() %>%
base::charToRaw() %>%
rsvg::rsvg_pdf(filename)
}, file="NUL")
knitr::include_graphics(path=filename, dpi=dpi)
}
```
The graph below will be created in as a separate PDF file and included automatically in the PDF using the newly created `create_pdf_diagram()` function.
```{r graph, fig.cap="A nice graph with this nice caption.", fig.width=8, fig.height=4}
# Example GraphViz code to create graph.
graphcode <- "digraph nice_graph {
node [fontname = Helvetica]
a [label = '@@1']
b [label = '@@2-1']
c [label = '@@2-2']
d [label = '@@2-3']
e [label = '@@2-4']
f [label = '@@2-5']
g [label = '@@2-6']
h [label = '@@2-7']
i [label = '@@2-8']
j [label = '@@2-9']
a -> {b c d e f g h i j}
}
[1]: 'top'
[2]: 10:20"
# Create graph diagram as PDF file.
create_pdf_diagram("graph.pdf", graphcode)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment