Search code examples
graphdotjgrapht

(JGraphT) Export Graph<String, DefaultEdge> as DOT


I use the jgrapht library and I have directed Graphs with Strings as vertices and DefaultEdges as edges. Now I wonder how to export my graph in the DOT format. What would be the best approach for the export? From the jgraph documentation i understand, that I can use the DOTExporter class https://jgrapht.org/javadoc/org/jgrapht/nio/dot/DOTExporter.html For instantiating that class I need a Writer and a VertexProvider which I struggle to instantiate from my given graph.

This is the type of graph I want to export:

Graph<String, DefaultEdge> graph

Solution

  • Here are two examples of exporting a graph in DOT format using the DOTExporter. In the first example, no vertexIDProvider is provided. As a result, the exporter does not know how to name your vertices, so it simply assigns each vertex a unique number. In the second example, I provide a vertexIDProvider. The vertexIDProvider is a Function<V,​String> vertexIdProvider which maps a vertex to a String. In 2nd example I simply map a vertex to its String representation. Finally, In the examples I use a simple Writer. In your implementation you might want to use a FileWriter to write the result to an actual file.

    //Create a graph with some vertices and edges
    Graph<String, DefaultEdge> graph=new SimpleGraph<>(DefaultEdge.class);
    Graphs.addAllVertices(graph, Arrays.asList("v1", "v2", "v3", "v4"));
    graph.addEdge("v1", "v2");
    graph.addEdge("v2", "v3");
    graph.addEdge("v3", "v4");
    graph.addEdge("v4", "v1");
    
    //Create the exporter (without ID provider)
    DOTExporter<String, DefaultEdge> exporter=new DOTExporter<>();
    Writer writer = new StringWriter();
    exporter.exportGraph(graph, writer);
    System.out.println(writer.toString());
    
    //Create the exporter (with ID provider)
    DOTExporter<String, DefaultEdge> exporter2=new DOTExporter<>(v -> v.toString());
    writer = new StringWriter();
    exporter2.exportGraph(graph, writer);
    System.out.println(writer.toString());
    

    Output:

    strict graph G {
      1;
      2;
      3;
      4;
      1 -- 2;
      2 -- 3;
      3 -- 4;
      4 -- 1;
    }
    
    strict graph G {
      v1;
      v2;
      v3;
      v4;
      v1 -- v2;
      v2 -- v3;
      v3 -- v4;
      v4 -- v1;
    }
    

    A more elaborate example can be found in the user documentation.More examples can be found in the DOTExporterTest class.