Search code examples
rgraphvizdiagrammer

How to use GraphViz graphs in DiagrammeR for R


I am trying to use a GraphViz graph in DiagrammeR. How can I do this?

myGraph = grViz("
digraph boxes_and_circles {

  # a 'graph' statement
  graph [overlap = true, fontsize = 10]

  # several 'node' statements
  node [shape = box,
        fontname = Helvetica]
  A; B; C; D; E; F

  node [shape = circle,
        fixedsize = true,
        width = 0.9] // sets as circles
  1; 2; 3; 4; 5; 6; 7; 8

  # several 'edge' statements
  A->1 B->2 B->3 B->4 C->A
  1->D E->A 2->4 1->5 1->F
  E->6 4->6 5->7 6->7 3->8
}
")

and then I want to use it in DiagrammeR, but it will not allow it.

render_graph(myGraph)

Gives:

Error: class(graph) == "dgr_graph" are not all TRUE

Is there a way I need to convert or input the GraphViz graph into the DiagrammeR environment?


Solution

  • grViz takes a string describing the graph (vis.js style) : it is the interpreted by vis.js. Its return value is then an htmlwidget object.

    render_graph takes a dgr_graph object, created using the create_graph function.

    you can see in the DiagrammeR doc

    library(DiagrammeR)
    
    # Create a simple NDF
    nodes <-
      create_nodes(
        nodes = 1:4,
        type = "number")
    
    # Create a simple EDF
    edges <-
      create_edges(
        from = c(1, 1, 3, 1),
        to = c(2, 3, 4, 4),
        rel = "related")
    
    # Create the graph object,
    # incorporating the NDF and
    # the EDF, and, providing
    # some global attributes
    graph <-
      create_graph(
        nodes_df = nodes,
        edges_df = edges,
        graph_attrs = "layout = neato",
        node_attrs = "fontname = Helvetica",
        edge_attrs = "color = gray20")
    
    # View the graph
    render_graph(graph)
    

    DiagrammeR can produce Graphviz code : From the doc mentioned below : "If you'd like to return the Graphviz DOT code (to, perhaps, share it or use it directly with the Graphviz command-line utility), just use output = "DOT" in the render_graph()"

    So

    1. you can use create_graph to produce graphviz dot code
    2. you can use graphviz dot code directly with grViz in DiagrammeR