Python中将点转换为png

48

我有一个从我的代码生成的dot文件,想要在我的输出中呈现它。为此,我在网上看到了一个命令,类似于在cmd上执行:

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

但我的问题是我想在我的Python程序中使用它。

我该怎么做?

我查看了pydot,但似乎找不到答案...

9个回答

71

使用pydot.graph_from_dot_file加载文件,获得一个pydot.Dot类实例。然后使用write_png方法将其写入PNG文件。

import pydot

(graph,) = pydot.graph_from_dot_file('somefile.dot')
graph.write_png('somefile.png')

2
这个方法非常好用,但是让我问一个(愚蠢的)问题:为什么使用(graph, ) = pydot...可以工作,而使用graph = pydot...就不行(我得到了AttributeError: 'list' object has no attribute 'write_png')? - pepa.dvorak
1
"TypeError: 'Dot' object is not iterable"。 我在"(graph,) = pydot.graph_from_dot_file('somefile.dot')"这行代码中遇到了上述错误。为什么会出现这个错误,我该如何修复它? - bananagator
3
我正在使用正是这个,但出现问题,显示 [Errno 2] "dot" not found in path. - Guilherme Felipe Reis
1
@GuilhermeFelipeReis,这听起来像是GraphViz的配置问题。您是否已安装了GraphViz dot?它是否在您的PATH环境变量中?https://graphviz.gitlab.io/download/ - Judge Maygarden
@JudgeMaygarden,它缺少了二进制文件,所以我增加了apk add --update --no-cache graphviz - Guilherme Felipe Reis
4
我也遇到了“dot”在路径中找不到的问题,但是我已经将其添加到了PATH环境变量中。我可以在Anaconda Prompt中运行dot - Alisson Reinaldo Silva

28

pydot 需要安装 GraphViz 二进制文件,因此如果您已经生成了 .dot 文件,最好直接自己调用 dot。例如:

from subprocess import check_call
check_call(['dot','-Tpng','InputFile.dot','-o','OutputFile.png'])

6
您可以使用pygraphviz。一旦您加载了一个图形,您可以执行以下操作:
graph.draw('file.png')

5
您可以使用 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")

4
你可以尝试以下方法:
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
os.system('dot -Tpng random.dot -o random.png')

OP特别要求代码“内置在我的Python程序中”,这意味着他更喜欢不依赖于外部命令的答案。您还编写了非可移植的Windows代码,依赖于Graphviz的特定版本和安装目录。 - Captain Lepton
从安全角度来看,调用子shell是一种极其不良的做法,因为它会创建一个命令注入攻击向量,应该尽可能避免使用。 - CervEd
https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L129 - joefromct

4

第一种解决方案)

采用@Mauricio Carrero的方法,在脚本中设置PATH(在环境变量中设置的PATH没有此效果):

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")

这使得将dot_data保存为png成为可能。选择你自己的本地路径,你可能也已经在`C:/Program Files (x86)/Graphviz2.38/bin/`中安装了graphviz。

这个解决方案也来自Sarunas在这里的答案: https://datascience.stackexchange.com/questions/37428/graphviz-not-working-when-imported-inside-pydotplus-graphvizs-executables-not

第二个解决方案)

你也可以避免这个错误

Exception has occurred: InvocationException
GraphViz's executables not found

只需按照它请求的方式提供Graphviz对象的可执行文件,即可满足其所需:

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")

注:在校准错误的安装和全面卸载并重新安装,各种路径变量,外部和内部graphviz安装,python-graphviz、pygraphviz以及我能在这里或Convert decision tree directly to png此处找到的所有解决方案都不能解决问题。以下是两种可行的解决方法:

对于conda python-graphviz,我一直遇到安装错误,例如:

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')

对于conda安装graphviz,我遇到了以下问题:

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需要MS Visual C++,但我不想安装它:

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

最终,除了第一种解决方案之外,没有任何指南能够真正正确地设置PATH变量。

2

这是在 Windows 11 系统上使用 Pycharm 终端和 venv Python 3.8 解释器工作的代码。

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')

这将创建一个classes.dot.pg文件(我不知道如何修复名称,但这是一个可以打开的png文件)。
使用以下命令在终端上生成类图:

pyreverse package_path

pyreverse包含在pylint中。
安装方法如下:

pip install pylint

(仅在创建classes.dot文件时安装pylint)

pip install graphviz


0

这将创建一个从'a'到'b'的图形,并将其保存为png文件。

代码:

from graphviz import Digraph

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

dot. Render("sample.png")

-2
from graphviz import render
dot.render(directory='doctest-output', view=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接