Plotting the Digraph with graphviz in python from DOT file
Asked Answered
P

3

21

This is the API reference for graphviz. I could not find any method that generates a directed graph from an existing dot source file. Methods like render and view save in a new file.

How can I display a graph from existing dot code?

Probate answered 30/1, 2017 at 17:41 Comment(0)
P
29

I was able to solve it using Source class.

from graphviz import Source
temp = """
digraph G{
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 5 [label="root"]
1 [label="1 (Hello)"]
2 [label="2 (how)"]
2 -> 1 [label="advmod"]
3 [label="3 (are)"]
4 [label="4 (you)"]
5 [label="5 (doing)"]
5 -> 3 [label="aux"]
5 -> 2 [label="advmod"]
5 -> 4 [label="nsubj"]
}
"""
s = Source(temp, filename="test.gv", format="png")
s.view()

Output

The output will be in same folder, and format can be altered.

PS - To install graphviz on Ubuntu. First install using sudo apt install graphviz and then sudo pip install graphviz, else it won't work.

Probate answered 30/1, 2017 at 18:27 Comment(2)
I get a strange error AttributeError: 'function' object has no attribute 'splitlines'Supernatural
@johnktejik I similarly got AttributeError: 'Dot' object has no attribute 'splitlines'. Solved it by running dot.to_string() before passing to Source()Acacia
C
19

You can use the Source.from_file('/path/to/dot_file') function as defined in the API.

Thus the code will be:

from graphviz import Source
path = '/path/to/dot_file'
s = Source.from_file(path)
s.view()
Chela answered 21/6, 2018 at 11:15 Comment(2)
python3.7 /tmp/graphviz.py Traceback (most recent call last): File "/tmp/graphviz.py", line 3, in <module> from graphviz import Source File "/tmp/graphviz.py", line 3, in <module> from graphviz import Source ImportError: cannot import name 'Source' from 'graphviz' (/tmp/graphviz.py)Merideth
it flashed on my screen for a millisecond then disappeared. How do I get it to stay?Supernatural
B
0

I put a very short code for displaying graph using a dot file in Python.

The code is like this:

from graphviz import Source

path = 'abcd.dot'
s = Source.from_file(path)
print(s.source)

s.render('abcd.gv', format='jpg',view=True)
Bringhurst answered 20/5, 2021 at 3:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.