Converting dot to png in python
Asked Answered
M

9

48

I have a dot file generated from my code and want to render it in my output. For this i have seen on the net that the command is something like this on cmd

dot -Tpng InputFile.dot -o OutputFile.png  for Graphviz

But my problem is that I want to use this inbuilt in my python program.

How can i do so ??

I looked at pydot but can't seem to find an answer in there.....

Mvd answered 15/3, 2011 at 18:20 Comment(0)
A
28

pydot needs the GraphViz binaries to be installed anyway, so if you've already generated your dot file you might as well just invoke dot directly yourself. For example:

from subprocess import check_call
check_call(['dot','-Tpng','InputFile.dot','-o','OutputFile.png'])
Acima answered 15/3, 2011 at 18:25 Comment(0)
I
71

Load the file with pydot.graph_from_dot_file to get a pydot.Dot class instance. Then write it to a PNG file with the write_png method.

import pydot

(graph,) = pydot.graph_from_dot_file('somefile.dot')
graph.write_png('somefile.png')
Interrelate answered 15/3, 2011 at 18:29 Comment(6)
This works like a charm, but let me ask a (silly) question: why does it work with (graph, ) = pydot... but not with graph = pydot... (I get AttributeError: 'list' object has no attribute 'write_png')?Novikoff
"TypeError: 'Dot' object is not iterable". I got the above error for the line "(graph,) = pydot.graph_from_dot_file('somefile.dot')". why am i getting this error and how do i fix this?Parochialism
I am using exactly this but I get an issue saying [Errno 2] "dot" not found in path.Crossopterygian
@GuilhermeFelipeReis That sounds like a GraphViz configuration issue. Do you have GraphViz dot installed? Is it in your PATH environment variable? graphviz.gitlab.io/downloadInterrelate
@JudgeMaygarden it was missing the binary, so I added apk add --update --no-cache graphvizCrossopterygian
I'm also facing "dot" not found in path. and I have it in the PATH environment variable. I can run dot in Anaconda Prompt.Chemisorb
A
28

pydot needs the GraphViz binaries to be installed anyway, so if you've already generated your dot file you might as well just invoke dot directly yourself. For example:

from subprocess import check_call
check_call(['dot','-Tpng','InputFile.dot','-o','OutputFile.png'])
Acima answered 15/3, 2011 at 18:25 Comment(0)
S
6

You can use pygraphviz. Once you have a graph loaded, you can do

graph.draw('file.png')
Springspringboard answered 15/3, 2011 at 18:26 Comment(0)
L
5

You can use graphviz:

# Convert a .dot file to .png
from graphviz import render
render('dot', 'png', 'fname.dot')

# To render an existing file in a notebook
from graphviz import Source
Source.from_file("fname.dot")
Lighten answered 11/3, 2020 at 3:51 Comment(0)
A
4

You can try:

import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
os.system('dot -Tpng random.dot -o random.png')
Algoid answered 26/8, 2018 at 20:3 Comment(3)
The OP specifically asked for code that is "inbuilt in my python program", implying a preference for an answer that does not depend on an external command. You also have written non-portable Windows code that relies on a specific version and installation directory for Graphviz.Anzac
Invoking a subshell is an extremely poor practice from a security standpoint as it creates a command injection attack vector, and should be avoided at all cost.Hodgkinson
github.com/pydot/pydot/blob/…Michal
G
4

1st Solution)

Going further with the approach of @Mauricio Carrero by setting the PATH inside the script (the same PATH set in the environment variables does not have this effect!):

import os
import pydotplus
from sklearn.tree import export_graphviz

os.environ['PATH'] = os.environ['PATH']+';' + r'C:\Users\Admin\Anaconda3\Library\bin\graphviz'

# first export the dot file only if needed
export_graphviz(clf, out_file=filename + ".dot", feature_names = feature_names)
# now generate the dot_data again
dot_data = export_graphviz(clf, out_file=None, feature_names = feature_names)
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
graph.write_png(filename + "_gv.png")

This made it possible to save the dot_data to png. Choose your own local paths, you might also have installed graphviz in `C:/Program Files (x86)/Graphviz2.38/bin/

This solution also came from Sarunas answer here: https://datascience.stackexchange.com/questions/37428/graphviz-not-working-when-imported-inside-pydotplus-graphvizs-executables-not

2nd Solution)

You can also avoid the error

Exception has occurred: InvocationException
GraphViz's executables not found

by simply giving it what it wants, as it asks for the executables of the graphviz object:

graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
# graph is now a new Dot object!
# That is why we need to set_graphviz_executables for every new instance
# This cannot be set globally but must be set again and again
# that is why the PATH solution (1st Solution) above seems much better to me
# see the docs in https://pydotplus.readthedocs.io/reference.html
pathCur = 'C:\\Program Files (x86)\\Graphviz2.38\\bin\\'
graph.set_graphviz_executables({'dot': pathCur+'dot.exe', 'twopi': pathCur +'twopi.exe', 'neato': pathCur+'neato.exe', 'circo': pathCur+'circo.exe', 'fdp': pathCur+'fdp.exe'})
graph.write_png(filename + "_gv.png")

p.s: These 2 approaches were the only solutions working for me after 2 hours of calibrating erroneuos installations and full uninstall and install again, all varieties of PATH variables, external and internal graphviz installation, python-graphviz, pygraphviz and all of the solutions I could find in here, or in Convert decision tree directly to png or in https://datascience.stackexchange.com/questions/37428/graphviz-not-working-when-imported-inside-pydotplus-graphvizs-executables-not?newreg=a789aadc5d4b4975949afadd3919fe55

For conda python-graphviz, I got constant installation errors like

InvalidArchiveError('Error with archive C:\\Users\\Admin\\Anaconda3\\pkgs\\openssl-1.1.1d-he774522_20ffr2kor\\pkg-openssl-1.1.1d-he774522_2.tar.zst.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nCould not unlink')

For conda install graphviz, I got

InvalidArchiveError('Error with archive C:\\Users\\Admin\\Anaconda3\\pkgs\\openssl-1.1.1d-he774522_21ww0bpcs\\pkg-openssl-1.1.1d-he774522_2.tar.zst.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nCould not unlink')

pygraphviz needs MS Visual C++ which I did not want to install:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

In the end, no guide was working to really set the PATH variables correctly except for the 1st Solution approach.

Grandam answered 20/5, 2020 at 19:39 Comment(0)
D
2

Here is the code that worked for me on windows 11 system using a pycharm terminal using venv python 3.8 interpreter.

from graphviz import render
import os
os.environ['PATH'] = os.environ['PATH']+';' + r"C:\Program Files\Graphviz\bin" #find binaries of graphviz and add to path
render('dot','png','classes.dot')

this will create a classes.dot.pg file (I don't know how to fix the name but this is a png file you can open)

The classes dot was generated on terminal using

pyreverse package_path

pyreverse comes with pylint.

Installations:

pip install pylint

(install pylint only if you are creating classes.dot file)

pip install graphviz

Desrochers answered 11/5, 2022 at 10:35 Comment(0)
A
0

This would create a graph 'a' to 'b' and save it as a png file.

code:

from graphviz import Digraph

dot = Digraph()
dot.node('a')
dot.node('b')
dot.edge('a','b')

dot. Render("sample.png")
Ablaze answered 23/11, 2022 at 13:39 Comment(0)
I
-2
from graphviz import render
dot.render(directory='doctest-output', view=True)
Irrelative answered 5/9, 2022 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.