Is it possible to get output of pydot graph without intermediate file?
Asked Answered
C

1

8

I have a very simple graph that I want to plot as svg. For example:

# graph.dot
graph { 
        a -- b; 
        b -- c; 
    } 

I am currently using pydot to read the file and then generate the svg file as follows:

import pydot
graphs = pydot.graph_from_dot_file('graph.dot')
graphs[0].write_svg('graph.svg') # there is only 1 graph so the 0 index.

However, I need to do this without the need of intermediate files graph.dot and graph.svg. I have the code content of graph.dot in a string, corresponding to which I need the svg output in string.

I need something like:

graph_dot = "... ..." # string, I have this
graph_svg = convert_dot_to_svg(graph_dot) 
# i need something like convert_dot_to_svg()

My question is not limited to pydot only. If anyone knows a web api using which I can do this, then also it will do.

Thanks a Lot, in advance.

Catarinacatarrh answered 11/7, 2016 at 7:46 Comment(7)
I've never used pydot (but I do know Graphviz), but a quick look at the pydot docs suggests that you can use a file-like object instead of a file. So you should try StringIO or BytesIO from the standard io module.Roentgenotherapy
@PM2Ring you are right that I can use io to take input. But how to replace the write_svg function?Catarinacatarrh
@PM2Ring As mentioned, question isn't limited to pydot itself. Can you tell me a way to get the svg string corresponding to dot string in Graphviz. Any way is fine.Catarinacatarrh
If .write_svg accepts an open file handle instead of a file name, then it will "just work" if you supply it a StringIO or BytesIO object. If you've never used the io module before, I suggest you study the docs & do a few experiments; it's a very useful module.Roentgenotherapy
Ok cool ... Thanks :)Catarinacatarrh
Sorry, I don't have any specifc advice about DOT -> SVG conversion; I normally use the Graphviz command line programs to convert a DOT file to SVG.Roentgenotherapy
No problem, and thanks a lot for your time and valuable comments. Finally, solution could be figured out. I have posted the answer on what worked.Catarinacatarrh
C
11

After spending some more time looking at the available methods on pydot object and graph object, it could be figured out:

The following code works:

import pydot    
dot_string = """graph { 
                    a -- b; 
                    b -- c; 
                } """

graphs = pydot.graph_from_dot_data( dot_string )
svg_string = graphs[0].create_svg() 
Catarinacatarrh answered 11/7, 2016 at 8:28 Comment(2)
FWIW, pydot still needs graphviz to be installed. Quoted from this blog post: "If we look at the Pydot Pypi page you can see already a hint on this as it will tell you the following; Pydot is an interface to Graphviz and can parse and dump into the DOT language used by Grapgiz. Pydot is written in pure Python."Valse
now what do you do with svg_string?Aara

© 2022 - 2024 — McMap. All rights reserved.