How to export images of diagrammer in R

If you want to export to svg without first rendering the image.

require(magrittr)
require(DiagrammeR)
require(DiagrammeRsvg)
require(xml2)

graphobject %>%
  export_svg() %>%
  read_xml() %>%
  write_xml("graph.svg")

The advantage of NOT rendering the image first is a cleaner, smaller and crispier svg file. Optimization and prettifying the code can be done using: https://jakearchibald.github.io/svgomg/


This solution is form this thread.

library(DiagrammeR)
library(DiagrammeRsvg)
library(magrittr)
library(rsvg)

graph <-
    "graph {
        rankdir=LR; // Left to Right, instead of Top to Bottom
        a -- { b c d };
        b -- { c e };
        c -- { e f };
        d -- { f g };
        e -- h;
        f -- { h i j g };
        g -- k;
        h -- { o l };
        i -- { l m j };
        j -- { m n k };
        k -- { n r };
        l -- { o m };
        m -- { o p n };
        n -- { q r };
        o -- { s p };
        p -- { s t q };
        q -- { t r };
        r -- t;
        s -- z;
        t -- z;
    }
"

grViz(graph) %>%
    export_svg %>% charToRaw %>% rsvg_pdf("graph.pdf")
grViz(graph) %>%
    export_svg %>% charToRaw %>% rsvg_png("graph.png")
grViz(graph) %>%
    export_svg %>% charToRaw %>% rsvg_svg("graph.svg")

Tags:

R

Diagrammer