Search code examples
rpdf-generationr-markdowndiagrammer

DiagrammeR and R Markdown pdf: Remove space around diagram?


I've had quite some problems working with the package DiagrammeR in R Markdown with pdf specified as output. I managed to display the diagram but as you will se in the following, there is quite a lot of space around the diagram.

Have a look at my sample code here:

---
title: "Untitled"
author: "test"
date: "14/05/2020"
output: pdf_document
---

# My Markdown-file
This is my RMarkdown-file. Now I want to add a flowchart using the packages DiagrammeR. 

```{r figure_1, echo = FALSE, fig.align='center', fig.cap = "Flowchart 1: Some explanation"}

DiagrammeR::grViz(" 
      digraph test {

        node [shape = circle] 
          A; B

        A -> B

      }
        ")

```

I now continue writing.

This code produces the following output:

enter image description here

Notice the following:

  1. The diagram is not centered even though I have specified it to be so in the code-chunk.
  2. There is a huge gap between the diagram and the caption.

How do I fix these issues? I love the packages but it might be too hard to work with when output is pdf? Maybe other packages are better?


Solution

  • Good question. I played a little bit around with the markdown chunk options and found the following workaround to embed a png instead of a pdf figure:

    ---
    title: "Untitled"
    author: "test"
    date: "14/05/2020"
    output: 
      pdf_document: 
        keep_tex: yes
    ---
    
    # My Markdown-file
    
    This is my RMarkdown-file. Now I want to add a flowchart using the packages DiagrammeR.
    
    ```{r echo=FALSE, fig.cap = "Flowchart 1: Some explanation", dev='png'}
    library("DiagrammeR")
    grViz("
          digraph test {
            node [shape = circle]
            A, B
    
            A -> B
          }
     ")
    ```
    
    I now continue writing.
    

    Other devices like Cairo_PDF worked also, but not as expected and just produced a png. I left the keep_tex option in to ease debugging.