14

I'm trying create image of diagrammer graph but it creates blank files instead. My data frame:

df <- data.frame(col1 = c( "Cat", "Dog", "Bird"), col2 = c( "Feline", "Canis", "Avis"), stringsAsFactors=FALSE)

The rest of code:

png("C:\\tmp\\anim.png")
uniquenodes <- unique(c(df$col1, df$col2))
library(DiagrammeR)
nodes <- create_node_df(n=length(uniquenodes), nodes = seq(uniquenodes), type="number", label=uniquenodes)
edges <- create_edge_df(from=match(df$col1, uniquenodes), to=match(df$col2, uniquenodes), rel="related")

g <- create_graph(nodes_df=nodes, edges_df=edges)
render_graph(g)
dev.off()
Deividas Kiznis
  • 431
  • 1
  • 6
  • 20
  • 3
    These graphs are mainly used to be rendered in html pages and not saved on a image file. However, the package allows to save them with `?export_graph` (although I didn't test, since it seems you need extra packages). – nicola Mar 11 '17 at 16:38
  • @nicola, your suggestion works. Should be the answer in my opinion.... – A5C1D2H2I1M1N2O1R2T1 Mar 11 '17 at 16:50

4 Answers4

20

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")
Sergey
  • 1,166
  • 14
  • 27
9

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/

Gregory
  • 91
  • 1
  • 1
0

First install DiagrammeRsvg and rsvg packages. At the end of code add thees lines:

export_graph(graph_name,
file_name = "pic.png",
file_type = "png")

With this you can create not only png image and pdf also.

Deividas Kiznis
  • 431
  • 1
  • 6
  • 20
0

The above code generates and error:

Error: export_graph() REASON:

  • The graph object is not valid() REASON:
  • The graph object is not valid

Not sure whether there is a workaround besides

graph %>%
export_svg() %>%
charToRaw %>%
rsvg_pdf("graph.pdf")
fRuser
  • 11