#graphviz 学习
# 在安装完Graphviz后,并将路径填入系统环境变量PATH中,
# 或用下述方法添加 ,注意加上r
# 写明graphviz的bin文件目录
import os
#os.environ["PATH"] += os.pathsep + r"D:\Software_install\graphviz-2.46.1\Graphviz\bin"
os.environ["Path"] += os.pathsep + r"D:\Software_install\graphviz-2.46.1\Graphviz\bin"
print(os.pathsep)# 分号
# pip install graphviz
import graphviz
graphviz.version()
# (2, 46, 1)
# 双击可jupyter notebook隐藏结果,单击可展开隐藏的结果。
创建主图
dot = graphviz.Digraph(name=‘G’,format=“png”, filename=‘angles.gv’,node_attr={‘shape’: ‘record’, ‘height’: ‘.1’},fontsize=‘11’)
实例化一个Digraph对象(有向图)
name:生成的图片的图片名,format:生成的图片格式
dot.attr(compound=‘true’)
dot.attr(rankdir=‘LR’, size=‘8,5’)
使用graph_attr,node_attr,and edge_attr参数来改变图,节点,连接的默认显示。
可以通过使用Digraph(strict=True)或类似的初始化图形来避免多条边。这样如果稍后添加一个同名的新节点,Graphviz本身会替换原有的节点。
设置图属性
dot.attr(bgcolor=‘blue’)
加入节点
dot.node(name=‘node0’, label=graphviz.nohtml(‘ | G|’), shape=‘record’,
color=“lightsalmon”, style = “filled”, fontname=“Microsoft YaHei”)
name:这个节点对象的名称,
label:节点名,如果label以<开头,以>结尾的话,引擎按照HTML-like标签进行解析。
node shape值为 record正方型 或者Mrecord圆角正方型 时, 节点就是记录节点,其内容由label定义。
rankdir值不同时,分割行或者列相互转换
用 | 分割多列,用 标记行的port值,箭头可指向其准确位置 ,用{ | } 分割多行
使用"\n", “\l” and "\r"分割label内容为多行:\n换行居中对齐;\l 靠左对齐;\r 靠右对齐
label=“node0 \n第一个开始节点\l节点说明\r是这样子\l对齐的是吧\l靠对齐”
节点label属性的内容可以是html,通常情况是一个tabel,可以指定其属性样式等html所支持的标签。
digraph {
d[label=<
11 | 22 |
33 | 44 |
c->d:f2;
e->d:l3;
}
对于字面上应该以 开头’<‘和结尾的字符串’>‘,使用该graphviz.nohtml()函数禁用尖括号的特殊含义并应用正常的引用/转义
使用graphviz.nohtml(str) 返回字符串’<…>‘在引用中不被视为 DOT HTML 字符串。即,’<…>'内的内容将被视为字面意思,但在图中不显示。
Args: s: String in which leading '<'
and trailing '>'
should be treated as literal.
literal adj.字面意义的; 完全按原文的; 缺乏想象力的;n.误印;
[例句]She probably should have vetted this speech But no, I’m talking about sleep in the literal sense
应该事先审查这次演讲不过别想歪了我这里的“睡”是字面意义的
shape 取值:‘Mdiamond’ ‘Msquare’ ‘record’ ,‘egg’,‘star’
color:画节点的线的颜色,取值:“peachpuff”,
style 取值:“filled”,
fontname 防止字体乱码情况,取值:“Microsoft YaHei”)
dot.attr(rank=‘same’) # rank=‘same’ 使得节点的处于同一排列
dot.node(‘A’)
dot.node(‘X’)
节点属性统一设置
dot.attr(‘node’, shape=‘doublecircle’)# 使得以下的节点都是双圆
dot.node(‘LR_0’)
dot.node(‘LR_3’)
dot.node(‘LR_4’)
dot.attr(‘node’, shape=‘circle’)# 使得以下的节点都是圆
dot.edge(‘LR_0’, ‘LR_2’, label=‘SS(B)’)
dot.edge(‘LR_0’, ‘LR_1’, label=‘SS(S)’)
加入边
edges():方法可以一次添加多个边, 每个边用字符串表示, 比如 cb 表示从 c 到 b 的边,即edges画边
edge():方法一次添加一个边
dot.edges([‘ab’, ‘ac’, ‘bd’, ‘cd’])
dot.edges([(‘struct1:f1’, ‘struct2:f0’), (‘struct1:f2’, ‘struct3:here’)])
dot.edge(‘d’, ‘e’, label=‘n’, len=‘1.00’)
dot.edge(‘c’, ‘e’, ltail=‘cluster0’)
dot.edge(‘b’, ‘f’, lhead=‘cluster1’)
dot.edge(‘c’, ‘g’, ltail=‘cluster0’, lhead=‘cluster1’) ## ??
dot.edge(‘e’, ‘clusterB’) # 节点与子图的边
dot.edge(‘clusterC’, ‘clusterB’)# 子图与子图的边
dot.edge_attr.update(arrowhead=‘vee’, arrowsize=‘2’)
添加子图的方法
NOTE: the subgraph name needs to begin with ‘cluster’ (all lowercase)
so that Graphviz recognizes it as a special cluster subgraph
如果name子图的 以’cluster’(全部小写)开头,则布局引擎将其视为特殊的集群子图
有两种使用方法:
第一个选项,graph作为唯一的参数:
p = graphviz.Graph(name=‘parent’)
p.edge(‘spam’, ‘eggs’)
c = graphviz.Graph(name=‘child’, node_attr={‘shape’: ‘box’})
c.edge(‘foo’, ‘bar’)
p.subgraph©
第二种用法,带有with-block(省略graph参数):
with dot.subgraph(name=‘cluster_1’) as c:
# c for cluster
c.attr(fontcolor=‘white’)
c.attr(‘node’, shape=‘circle’, style=‘filled’, fillcolor=‘white:black’,gradientangle=‘360’, label=‘n9:360’, fontcolor=‘black’)
# style 取值 ‘filled’ ‘radial’
c.node(‘n9’)
c.node_attr.update(style=‘filled’, color=‘white’)
c.node_attr[‘style’] = ‘filled’
for i, a in zip(range(8, 0, -1), range(360 - 45, -1, -45)):
# zip中的range取小不取大
c.attr(‘node’, gradientangle=‘%d’ % a, label=‘n%d:%d’ % (i, a))
c.node(‘n%d’ % i)
c.attr(label=‘Linear Angle Variations (white to black gradient)’)
当subgraph()用作上下文管理器时,
通过strict=None 复制 directory、 engine、 format、 renderer、 formatter和encoding 的父 图值来创建新图
这些复制的属性仅与从 with-block 中 独立渲染子图(即作为独立图)相关
弹出查看
dot.view(filename=“水果”, directory=“D:\MyTest”)
把图形画出来,并自动显示图片(弹出来),一般使用view()进行调试
filename:图片的名称,若无filename,则使用Digraph对象的name,默认会有gv后缀
directory:图片保存的路径,默认是在当前路径下保存
print(dot.source) #打印生成的源代码
src = graphviz.Source(‘digraph “the holy hand grenade” { rankdir=LR; 1 -> 2 -> 3 -> lob }’)# 呈现现成的DOT Graph源代码字符串
render():把图形画出来,一般使用render保存图片的时候,view=False(不弹出图片)
直接渲染现有的DOT源文件(例如使用其他工具创建的),您可以使用该graphviz.render()功能。
render() 方法用来生成选定格式的图片。
dot.render(‘test-output/round-table.gv’, view=True)
传入view=True将使用系统默认的程序打开渲染后的图片(pdf,png,svg,等)。
反斜杠转义和形式<…>的字符串在DOT语言 中具有特殊含义。
如果您需要逐字呈现任意字符串(例如,来自用户输入),请考虑先用函数graphviz.escape()包装它们。
arbitrary adj.任意的; 武断的; 随心所欲的; 专横的; 专制的;
[例句]The method is simple comparatively and valid for arbitrary input.本文所述的方法比较简便、且适用于输入为任意的情形。
pipe输出
通过使用 Graph 或者Digraph 的pipe()方法,可以直接的查看Graphviz渲染命令的字符串。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>h = Graph(‘hello’, format=‘svg’)
h.edge(‘Hello’, ‘World’)
print(h.pipe().decode(‘utf-8’))
值得注意的是渲染的命令返回的是原始的stdout。当像svg或plain输出plain-text格式,需要像上面的代码对返回的值进行解码。
Graph与Digraph对象有一个 repr_mimebundle()方法,因此它们可以直接在Jupyter notebook中呈现和显示。
The edge() and edges() methods use the colon-separated node[:port[:compass]] format for tail and head nodes.
This allows to specify an optional node port plus an optional compass point the edge should aim at
for the given tail or head node
由于冒号用于表示边的port和compass, 因此当前不支持包含一个或多个文字冒号的节点名称。
label参数没有这样的限制,因此您可以通过选择无冒号name 和想要的label来解决。
Graphviz布局引擎支持许多 转义序列,例如\n, \l(\r 用于放置多行标签: 居中、左对齐、右对齐)
和\N, \G(\L 扩展为当前节点名称、图形名称、对象标签) .
为了能够从这个库中使用它们(例如用于标签),字符串中的反斜杠(大部分)按原样传递。
这意味着用户需要对文字反斜杠进行转义(加倍)。
由于反斜杠在 Python string文字中也很特殊,因此需要第二级加倍。例如label=‘\\’,对于呈现为单个文字反冲的标签:.
要禁用字符串中的任何特殊字符含义(例如,从字面上呈现的用户输入),请使用graphviz.escape()函数(类似于re.escape()函数)
为了防止破坏内部引用机制,“作为反斜杠转义的引号的特殊含义自此0.14库的版本以来已被禁用。
例如,两者label='”‘和label=’\“’ 现在都产生相同的 DOT 源[label=”“”] (呈现为文字引用的标签)。
unflatten()提高具有许多叶子或断开节点的图的纵横比。
dot2 = dot1.unflatten(stagger=3)
You can use the tempfile.mktemp() function from the stdlib tempfile module to render to a different file for each invocation调用.
This avoids needing to close the viewer查看器 window each time within such an incremental workflow增量工作流
(and also serves to preserves the intermediate steps并且还用于保留中间步骤).
API Reference
‘’’
graphviz.Graph
Graph source code in the DOT language.
graphviz.Digraph
Directed graph source code in the DOT language.
graphviz.Source
Verbatim DOT source code string to be rendered by Graphviz.
verbatim adj./adv.逐字的(地); 一字不差的(地);
#[例句]It was nothing but a verbatim translation. 这只不过是逐字的直译罢了。
graphviz.escape
Return string disabling special meaning of backslashes and ‘<…>’.
graphviz.nohtml
Return string not treating ‘<…>’ as DOT HTML string in quoting.
graphviz.ExecutableNotFound
RuntimeError raised if the Graphviz executable is not found.
graphviz.CalledProcessError
CalledProcessError raised if a subprocess returncode is not 0.
graphviz.RequiredArgumentError
TypeError raised if a required argument is missing.
graphviz.render
Render file with engine into format and return result filename.
graphviz.pipe
Return data (bytes) piped through engine into format as bytes.
graphviz.pipe_string
Return input_string piped through engine into format as string.
graphviz.unflatten
Return DOT source piped through unflatten preprocessor as string.
graphviz.view
Open filepath with its default viewing application (platform-specific).
graphviz.version
Return the upstream version number tuple from stderr of dot -V.
The two main classes Graph and Digraph (creating undirected vs. directed graphs) have exactly the same API.
Their division reflects the fact that both graph syntaxes cannot be mixed.
它们的划分反映了两种图形语法不能混合的事实。
Graph
class graphviz.Graph(name=None, comment=None, filename=None, directory=None, format=None,
engine=None, encoding=‘utf-8’, graph_attr=None, node_attr=None,
edge_attr=None, body=None, strict=False, *, renderer=None, formatter=None)
Graph source code in the DOT language.DOT 语言的图形源代码
Parameters
name (Optional[str]) – Graph name used in the source code.
comment (Optional[str]) – Comment added to the first line of the source.添加到源代码第一行的注释。
filename – Filename for saving the source (defaults to name + ‘.gv’).
directory – (Sub)directory for source saving and rendering.
format (Optional[str]) – Rendering output format (‘pdf’, ‘png’, …).
engine (Optional[str]) – Layout command used (‘dot’, ‘neato’, …).
renderer (Optional[str]) – Output renderer used (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter used (‘cairo’, ‘gd’, …).使用的输出格式化程序
encoding (Optional[str]) – Encoding for saving the source.
graph_attr – Mapping of (attribute, value) pairs for the graph.
node_attr – Mapping of (attribute, value) pairs set for all nodes.
edge_attr – Mapping of (attribute, value) pairs set for all edges.
body – Iterable of verbatim lines (including their final newline) to add to the graph body.
可迭代的逐字行(包括最后的换行符)添加到图的body中
strict (bool) – Rendering should merge multi-edges.
All parameters are optional and can be changed under their corresponding attribute name after instance creation.
iter(subgraph=False)
Yield the DOT source code line by line (as graph or subgraph).
Yields: Line ending with a newline (‘\n’).
Return type Iterator[str]
repr_mimebundle(include=None, exclude=None, **_)
Return the rendered graph as IPython mimebundle.
Parameters
include (Optional[Iterable[str]]) – Iterable of mimetypes to include in the result. If not given or None: [‘image/sxg+xml’].
exclude (Optional[Iterable[str]]) – Iterable of minetypes to exclude from the result. Overrides include.
Return type Dict[str, Union[bytes, str]]
Returns Mapping from mimetypes to data.从 MIME 类型映射到数据。
Example
import graphviz
dot = graphviz.Graph()
dot.repr_mimebundle()
{‘image/svg+xml’: ‘<?xml version=…
dot.repr_mimebundle(include=[‘image/png’])
{‘image/png’: b’\x89PNG…
dot.repr_mimebundle(include=[])
{}
dot.repr_mimebundle(include=[‘image/svg+xml’, ‘image/jpeg’],
exclude=[‘image/svg+xml’])
{‘image/jpeg’: b’\xff…
list(dot.repr_mimebundle(include=[‘image/png’, ‘image/jpeg’]))
[‘image/jpeg’, ‘image/png’]
attr(kw=None, _attributes=None, **attrs)
Add a general or graph/node/edge attribute statement.
Parameters
kw (Optional[str]) – Attributes target (None or ‘graph’, ‘node’, ‘edge’).
attrs – Attributes to be set (must be strings, may be empty).
Return type None
body
Verbatim DOT source lines including final newline.
Type List[str]
clear(keep_attrs=False)
Reset content to an empty body, clear graph/node/egde_attr mappings.
Parameters
keep_attrs (bool) – preserve graph/node/egde_attr mappings
Return type None
comment
DOT source comment for the first source line.
Type str
copy()
Return a copied instance of the object.
Returns An independent copy of the current object.
property directed: bool
False
Return type bool
edge(tail_name, head_name, label=None, _attributes=None, **attrs)
Create an edge between two nodes.
Parameters
tail_name (str) – Start node identifier (format: node[:port[:compass]]).
head_name (str) – End node identifier (format: node[:port[:compass]]).
label (Optional[str]) – Caption to be displayed near the edge.
attrs – Any additional edge attributes (must be strings). ## 可以增加自定义的属性
The tail_name and head_name strings are separated by (optional) colon(s) into node name, port name, and compass (e.g. sw).
See details in the User Guide .
Return type None
edge_attr
Attribute-value pairs applying to all edges.##注意是所有边的共有属性
Type Dict[str, str]
edges(tail_head_iter)
Create a bunch of edges.
Parameters
tail_head_iter – Iterable of (tail_name, head_name) pairs (format:node[:port[:compass]]).
The tail_name and head_name strings are separated by (optional) colon(s) into node name, port name, and compass (e.g. sw).
Return type None
property encoding: str
The encoding for the saved source file.
Return type str
property engine: str
The layout engine used for rendering (‘dot’, ‘neato’, …).
Return type str
filename
Target file name for saving the DOT source file.
Type str
property filepath: str
The target path for saving the DOT source file.
Return type str
property format: str
The output format used for rendering (‘pdf’, ‘png’, …).
Return type str
property formatter: Optional[str]
The output formatter used for rendering (‘cairo’, ‘gd’, …).
Return type Optional[str]
graph_attr
Attribute-value pairs applying to the graph.
Type Dict[str, str]
name
DOT source identifier for the graph or digraph statement.
Type str
node(name, label=None, _attributes=None, **attrs)
Create a node.
Parameters
name (str) – Unique identifier for the node inside the source.
label (Optional[str]) – Caption to be displayed (defaults to the node name).
attrs – Any additional node attributes (must be strings).
Return type None
node_attr
Attribute-value pairs applying to all nodes.##注意是所有节点的共有属性
Type Dict[str, str]
pipe(format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, *, engine=None, encoding=None)
Return the source piped through the Graphviz layout command.
Parameters
format (Optional[str]) – The output format used for rendering (‘pdf’, ‘png’, etc.).
renderer (Optional[str]) – The output renderer used for rendering (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – The output formatter used for rendering (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
engine (Optional[str]) – Layout engine for rendering (‘dot’, ‘neato’, …).
encoding (Optional[str]) – Encoding for decoding the stdout.
Return type Union[bytes, str]
Returns Bytes or if encoding is given decoded string(stdout of the layout command).
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
Example
source = ‘graph { spam }’
graphviz.Source(source, format=‘svg’).pipe()[:14]
b’<?xml version=’
graphviz.Source(source, format=‘svg’).pipe(encoding=‘ascii’)[:14]
‘<?xml version=’
graphviz.Source(source, format=‘svg’).pipe(encoding=‘utf-8’)[:14]
‘<?xml version=’
render(filename=None, directory=None, view=False, cleanup=False, format=None, renderer=None,
formatter=None, neato_no_op=None, quiet=False, quiet_view=False, *, outfile=None,
engine=None, raise_if_result_exists=False, overwrite_source=False)
Save the source to file and render with the Graphviz engine.
Parameters
filename (Union[PathLike, str, None]) – Filename for saving the source (defaults to name + ‘.gv’).s
directory (Union[PathLike, str, None]) – (Sub)directory for source saving and rendering.
view (bool) – Open the rendered result with the default application.
cleanup (bool) – Delete the source file after successful rendering.
format (Optional[str]) – The output format used for rendering (‘pdf’, ‘png’, etc.).
renderer (Optional[str]) – The output renderer used for rendering (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – The output formatter used for rendering (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
quiet_view (bool) – Suppress stderr output from the viewer process (implies view=True, ineffective on Windows platform).
outfile (Union[PathLike, str, None]) – Path for the rendered output file.
engine (Optional[str]) – Layout engine for rendering (‘dot’, ‘neato’, …).
raise_if_result_exits – Raise graphviz.FileExistsError if the result file exists.
overwrite_source (bool) – Allow dot to write to the file it reads from. Incompatible with raise_if_result_exists.
Return type str
Returns The (possibly relative) path of the rendered file.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
ValueError – If outfile is the same file as the source file unless overwite_source=True.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
RuntimeError – If viewer opening is requested but not supported.
Example
dot = graphviz.Graph(name=‘spam’, directory=‘doctest-output’)
dot.render(format=‘png’).replace(‘\’, ‘/’)
‘doctest-output/spam.gv.png’
dot.render(outfile=‘spam.svg’).replace(‘\’, ‘/’)
‘doctest-output/spam.svg’
The layout command is started from the directory of filepath,
so that references to external files (e.g. [image=images/camelot.png]) can be given
as paths relative to the DOT source file.
布局命令从filepath的目录开始,因此对外部文件(例如[image=images/camelot.png])的引用可以作为相对于 DOT 源文件的路径给出。
哇塞!!!
property renderer: Optional[str]
The output renderer used for rendering (‘cairo’, ‘gd’, …).
Return type Optional[str]
save(filename=None, directory=None, *, skip_existing=False)
Save the DOT source to file. Ensure the file ends with a newline.
Parameters
filename (Union[PathLike, str, None]) – Filename for saving the source (defaults to name + ‘.gv’)
directory (Union[PathLike, str, None]) – (Sub)directory for source saving and rendering.
skip_existing (Optional[bool]) – Skip write if file exists (default: False).
Return type str
Returns The (possibly relative) path of the saved source file.
property source: str
The generated DOT source code as string.
Return type str
strict
Rendering should merge multi-edges.
Type bool
subgraph(graph=None, name=None, comment=None, graph_attr=None, node_attr=None, edge_attr=None, body=None)
Add the current content of the given sole graph argument
as subgraph or return a context manager returning a new graph instance created with the given (name, comment, etc.)
arguments whose content is added as subgraph when leaving the context manager’s with-block.
Parameters
graph – An instance of the same kind (Graph, Digraph) as the current graph (sole argument in non-with-block use).
name (Optional[str]) – Subgraph name (with-block use).
comment (Optional[str]) – Subgraph comment (with-block use).
graph_attr – Subgraph-level attribute-value mapping (with-block use).
node_attr – Node-level attribute-value mapping (with-block use).
edge_attr – Edge-level attribute-value mapping (with-block use).
body – Verbatim lines to add to the subgraph body (with-block use).
See the usage examples in the User Guide .
When used as a context manager, the returned new graph instance uses strict=None and
the parent graph’s values for directory, format, engine, and encoding by default.
If the name of the subgraph begins with ‘cluster’ (all lowercase) the layout engine will treat it as a special cluster subgraph.
unflatten(stagger=None, fanout=False, chain=None)
Return a new Source instance with the source
piped through the Graphviz unflatten preprocessor.
Parameters
stagger (Optional[int]) – Stagger the minimum length of leaf edges between 1 and this small integer.
fanout (bool) – Fanout nodes with indegree = outdegree = 1 when staggering (requires stagger).
chain (Optional[int]) – Form disconnected nodes into chains of up to this many nodes.
Return type Source
Returns Prepocessed DOT source code (improved layout aspect ratio).
Raises
graphviz.RequiredArgumentError – If fanout is given but stagger is None.
graphviz.ExecutableNotFound – If the Graphviz unflatten executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
view(filename=None, directory=None, cleanup=False, quiet=False, quiet_view=False)
Save the source to file, open the rendered result in a viewer.
Convenience short-cut for running .render(view=True).
Parameters
filename (Union[PathLike, str, None]) – Filename for saving the source (defaults to name + ‘.gv’).
directory (Union[PathLike, str, None]) – (Sub)directory for source saving and rendering.
cleanup (bool) – Delete the source file after successful rendering.
quiet (bool) – Suppress stderr output from the layout subprocess.
quiet_view (bool) – Suppress stderr output from the viewer process (ineffective on Windows).
Return type str
Returns The (possibly relative) path of the rendered file.
Raises
graphviz.ExecutableNotFound – If the Graphviz executable is not found.
graphviz.CalledProcessError – If the exit status is non-zero.
RuntimeError – If opening the viewer is not supported.
Short-cut method for calling render() with view=True.
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
没有等待应用程序关闭的选项,也没有办法检索应用程序的退出状态。
Digraph
class graphviz.Digraph(name=None, comment=None, filename=None, directory=None, format=None,
engine=None, encoding=‘utf-8’, graph_attr=None, node_attr=None,
edge_attr=None, body=None, strict=False, *, renderer=None, formatter=None)
Directed graph source code in the DOT language.
Parameters
name (Optional[str]) – Graph name used in the source code.
comment (Optional[str]) – Comment added to the first line of the source.
filename – Filename for saving the source (defaults to name + ‘.gv’).
directory – (Sub)directory for source saving and rendering.
format (Optional[str]) – Rendering output format (‘pdf’, ‘png’, …).
engine (Optional[str]) – Layout command used (‘dot’, ‘neato’, …).
renderer (Optional[str]) – Output renderer used (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter used (‘cairo’, ‘gd’, …).
encoding (Optional[str]) – Encoding for saving the source.
graph_attr – Mapping of (attribute, value) pairs for the graph.
node_attr – Mapping of (attribute, value) pairs set for all nodes.
edge_attr – Mapping of (attribute, value) pairs set for all edges.
body – Iterable of verbatim lines (including their final newline) to add to the graph body.
strict (bool) – Rendering should merge multi-edges.
All parameters are optional and can be changed under their corresponding attribute name after instance creation.
Exceptions
exception graphviz.ExecutableNotFound(args)
RuntimeError raised if the Graphviz executable is not found.
exception graphviz.CalledProcessError(returncode, cmd, output=None, stderr=None)
CalledProcessError raised if a subprocess returncode is not 0.
exception graphviz.RequiredArgumentError
TypeError raised if a required argument is missing.
exception graphviz.FileExistsError
FileExistsError raised with raise_if_exists=True.
Warnings
exception graphviz.UnknownSuffixWarning
RuntimeWarning raised if the suffix of outfile is unknown and the given format is used instead.
exception graphviz.FormatSuffixMismatchWarning
UserWarning raised if the suffix outfile does not match the given format.
exception graphviz.DotSyntaxWarning
RuntimeWarning raised if a quoted string is expected to cause a CalledProcessError from rendering.
Low-level functions
The functions in this section are provided to work directly with existing files and strings
instead of using the object-oriented DOT creation methods documented above.
graphviz.render(engine: str, format: str, filepath: Union[os.PathLike, str], renderer: Optional[str] = None,
formatter: Optional[str] = None, neato_no_op: Optional[Union[bool, int]] = None,
quiet: bool = False, *, outfile: Optional[Union[os.PathLike, str]] = None,
raise_if_result_exists: bool = False, overwrite_filepath: bool = False)-> str
graphviz.render(engine: str, format: Optional[str] = None, filepath: Optional[Union[os.PathLike, str]] = None,
renderer: Optional[str] = None, formatter: Optional[str] = None,
neato_no_op: Optional[Union[bool, int]] = None, quiet: bool = False,
*, outfile: Optional[Union[os.PathLike, str]] = None, raise_if_result_exists: bool = False,
overwrite_filepath: bool = False)-> str
graphviz.render(engine: str, format: Optional[str] = None, filepath: Optional[Union[os.PathLike, str]] = None,
renderer: Optional[str] = None, formatter: Optional[str] = None,
neato_no_op: Optional[Union[bool, int]] = None, quiet: bool = False,
*, outfile: Optional[Union[os.PathLike, str]] = None, raise_if_result_exists: bool = False,
overwrite_filepath: bool = False)-> str
Render file with engine into format and return result filename.
Parameters
engine (str) – Layout engine for rendering (‘dot’, ‘neato’, …).
format (Optional[str]) – Output format for rendering (‘pdf’, ‘png’, …).
Can be omitted if an outfile with a known format is given, i.e. if outfile ends with a known .{format} suffix.
filepath (Union[PathLike, str, None]) – Path to the DOT source file to render.
Can be omitted if outfile is given, in which case it defaults to outfile.with_suffix(‘.gv’).
renderer (Optional[str]) – Output renderer (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag. Neato布局引擎无操作标志。
quiet (bool) – Suppress stderr output from the layout subprocess.
outfile (Union[PathLike, str, None]) – Path for the rendered output file.
raise_if_result_exits – Raise graphviz.FileExistsError if the result file exists.
overwrite_filepath (bool) – Allow dot to write to the file it reads from. Incompatible with raise_if_result_exists.
Return type str
Returns The (possibly relative) path of the rendered file.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If format or filepath are None unless outfile is given.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
ValueError – If outfile and filename are the same file unless overwite_filepath=True.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
graphviz.FileExistsError – If raise_if_exists and the result file exists.
Warns
graphviz.UnknownSuffixWarning – If the suffix of outfile is empty or unknown.
graphviz.FormatSuffixMismatchWarning – If the suffix of outfile does not match the given format.
Example
import pathlib
import graphviz
assert pathlib.Path(‘doctest-output/spam.gv’).write_text(‘graph { spam }’) == 14
graphviz.render(‘dot’, ‘png’, ‘doctest-output/spam.gv’).replace(‘\’, ‘/’)
‘doctest-output/spam.gv.png’
graphviz.render(‘dot’, filepath=‘doctest-output/spam.gv’,
outfile=‘doctest-output/spam.png’).replace(‘\’, ‘/’)
‘doctest-output/spam.png’
graphviz.render(‘dot’, outfile=‘doctest-output/spam.pdf’).replace(‘\’, ‘/’)
‘doctest-output/spam.pdf’
Note
The layout command is started from the directory of filepath, so that references to external files
(e.g. [image=images/camelot.png]) can be given as paths relative to the DOT source file.
See also
Upstream docs: https://www.graphviz.org/doc/info/command.html
graphviz.pipe(engine, format, data, renderer=None, formatter=None, neato_no_op=None, quiet=False)
Return data (bytes) piped through engine into format as bytes.
Parameters
engine (str) – Layout engine for rendering (‘dot’, ‘neato’, …).
format (str) – Output format for rendering (‘pdf’, ‘png’, …).
data (bytes) – Binary (encoded) DOT source bytes to render.
renderer (Optional[str]) – Output renderer (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
Return type bytes
Returns Binary (encoded) stdout of the layout command.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
Example
graphviz.pipe(‘dot’, ‘svg’, b’graph { hello – world }‘)[:14]
b’<?xml version=’
Note
The layout command is started from the current directory.
graphviz.pipe_string(engine, format, input_string, *, encoding, renderer=None, formatter=None, neato_no_op=None, quiet=False)
Return input_string piped through engine into format as string.
Parameters
engine (str) – Layout engine for rendering (‘dot’, ‘neato’, …).
format (str) – Output format for rendering (‘pdf’, ‘png’, …).
input_string (str) – Binary (encoded) DOT source bytes to render.
encoding (str) – Encoding to en/decode subprocess stdin and stdout (required).
renderer (Optional[str]) – Output renderer (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
Return type str
Returns Decoded stdout of the layout command.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
Example
graphviz.pipe_string(‘dot’, ‘svg’, ‘graph { spam }’,
encoding=‘ascii’)[:14]
‘<?xml version=’
Note
The layout command is started from the current directory.
graphviz.pipe_lines(engine, format, input_lines, *, input_encoding, renderer=None, formatter=None,
neato_no_op=None, quiet=False)
Return input_lines piped through engine into format as bytes.
Parameters
engine (str) – Layout engine for rendering (‘dot’, ‘neato’, …).
format (str) – Output format for rendering (‘pdf’, ‘png’, …).
input_lines (Iterator[str]) – DOT source lines to render (including final newline).
input_encoding (str) – Encode input_lines for subprocess stdin (required).
renderer (Optional[str]) – Output renderer (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
Return type bytes
Returns Binary stdout of the layout command.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
Example
graphviz.pipe_lines(‘dot’, ‘svg’, iter([‘graph { spam }\n’]),
input_encoding=‘ascii’)[:14]
b’<?xml version=’
Note
The layout command is started from the current directory.
graphviz.pipe_lines_string(engine, format, input_lines, *, encoding, renderer=None,
formatter=None, neato_no_op=None, quiet=False)
Return input_lines piped through engine into format as string.
Parameters
engine (str) – Layout engine for rendering (‘dot’, ‘neato’, …).
format (str) – Output format for rendering (‘pdf’, ‘png’, …).
input_lines (Iterator[str]) – DOT source lines to render (including final newline).
encoding (str) – Encoding to en/decode subprocess stdin and stdout (required).
renderer (Optional[str]) – Output renderer (‘cairo’, ‘gd’, …).
formatter (Optional[str]) – Output formatter (‘cairo’, ‘gd’, …).
neato_no_op (Union[bool, int, None]) – Neato layout engine no-op flag.
quiet (bool) – Suppress stderr output from the layout subprocess.
Return type str
Returns Decoded stdout of the layout command.
Raises
ValueError – If engine, format, renderer, or formatter are unknown.
graphviz.RequiredArgumentError – If formatter is given but renderer is None.
graphviz.ExecutableNotFound – If the Graphviz dot executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the rendering dot subprocess is non-zero.
Example
doctest_mark_exe()
import graphviz
graphviz.pipe_lines_string(‘dot’, ‘svg’, iter([‘graph { spam }\n’]),
encoding=‘ascii’)[:14]
‘<?xml version=’
Note
The layout command is started from the current directory.
graphviz.unflatten(source, stagger=None, fanout=False, chain=None, encoding=‘utf-8’)
Return DOT source piped through unflatten preprocessor as string.
Parameters
source (str) – DOT source to process (improve layout aspect ratio).
stagger (Optional[int]) – Stagger the minimum length of leaf edges between 1 and this small integer.
fanout (bool) – Fanout nodes with indegree = outdegree = 1 when staggering (requires stagger).
chain (Optional[int]) – Form disconnected nodes into chains of up to this many nodes.
encoding (str) – Encoding to encode unflatten stdin and decode its stdout.
Return type str
Returns Decoded stdout of the Graphviz unflatten command.
Raises
graphviz.RequiredArgumentError – If fanout is given but no stagger.
graphviz.ExecutableNotFound – If the Graphviz ‘unflatten’ executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
graphviz.view(filepath, quiet=False)[source]
Open filepath with its default viewing application (platform-specific).
Parameters
filepath (Union[PathLike, str]) – Path to the file to open in viewer.
quiet (bool) – Suppress stderr output from the viewer process (ineffective on Windows).
Raises
RuntimeError – If the current platform is not supported.
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
Return type None
Constants
Manually maintained allowlists for Graphviz parameters (cf. man dot, outputs, and dot -T: output):
graphviz.ENGINES
set of known layout commands used for rendering (‘dot’, ‘neato’, …).
graphviz.FORMATS
set of known output formats for rendering (‘pdf’, ‘png’, …).
graphviz.RENDERERS
set of known output renderers for rendering (‘cairo’, ‘gd’, …).
graphviz.FORMATTERS
set of known output formatters for rendering (‘cairo’, ‘gd’, …).
Supported IPython/Jupyter display formats:
graphviz.SUPPORTED_JUPYTER_FORMATS
set of supported formats for repr_mimebundle() (‘svg’, ‘png’, …).
Names of upstream binaries:
graphviz.DOT_BINARY
pathlib.Path of rendering command (Path(‘dot’)).
graphviz.UNFLATTEN_BINARY
pathlib.Path of unflatten command (Path(‘unflatten’)).
Defaults
Functions for setting package-wide defaults for engine and format:
Attention
These functions are provided mainly to simplify testing but may also be used by end-users for convenience in scripts.
They should be avoided in library code. Prefer passing or setting engine and format explicitly
if you create a library that depends on this package.
graphviz.set_default_engine(engine)
Change the default engine and return the old default value.
Parameters
engine (str) – new default engine used by all present and newly created instances without explicitly set engine (‘dot’, ‘neato’, …).
Return type str
Returns The old default value used for engine.
graphviz.set_default_format(format)
Change the default format and return the old default value.
Parameters
format (str) – new default format used by all present and newly created instances without explicitly set format (‘pdf’, ‘png’, …).
Return type str
Returns The old default value used for format.
Function for setting the package-wide default for IPython/Jupyter display format:
Attention
This function is provided for end-users. Prefer IPython.display functions in library code.
graphviz.set_jupyter_format(jupyter_format)
Change the default mimetype format for repr_mimebundle() and return the old value.
Parameters
jupyter_format (str) – new default IPython/Jupyter display format used by all present and newly created instances (‘svg’, ‘png’, …).
Return type str
Returns The old default value used for IPython/Jupyter display format.
‘’’
有用属性:
decorate=true装饰
dim Set the number of dimensions used for the layout.
dir Edge type for drawing arrowheads.
fixedsize
If false, the size of a node is determined by smallest width and height needed to contain its label and image,
if any, with a margin specified by the margin attribute.
gradientangle
如果正在使用渐变填充,这将确定填充的角度。
对于线性填充,颜色沿由对象的角度和中心指定的线变换。
对于径向填充,零值会导致颜色从中心径向变换;
对于非零值,颜色从该值指定的对象外围附近的点变换。
如果未设置,则默认角度为 0。
group 如果边的端点属于同一组,即具有相同的group属性,则设置参数以避免交叉并保持边笔直。适用于:节点
height 类型:double,节点的高度,以英寸为单位。
labelangle 与labeldistance一起确定headlabel/taillabel在极坐标中相对于头/尾的位置。
坐标系中的原点是边缘与节点接触的点。0 度的光线从原点沿边缘返回,与原点处的边缘平行。
角度(以度为单位)指定从 0 度射线开始的旋转,正角度逆时针移动,负角度顺时针移动。适用于:边缘
labeljust 图和集群标签的对齐。
如果labeljust=r,则标签在边界矩形内右对齐
如果labeljust=l, 左对齐
否则标签居中。
请注意,子图从其父图继承属性。因此,如果根图设置labeljust=l,则子图继承此值。
labelloc
类型:字符串,默认值:("t"集群),“b”(根图),“c”(节点)
节点、根图和集群的标签垂直放置。
对于图形和集群,仅允许labelloc=t和labelloc=b,分别对应于顶部和底部的放置。
默认情况下,根图标签位于底部,集群标签位于顶部。
请注意,子图从其父图继承属性。因此,如果根图设置labelloc=b,则子图继承此值。
对于节点,该属性仅在节点高度大于其标签高度时使用。
如果labelloc=t, labelloc=c, labelloc=b,则标签分别与节点的顶部对齐、居中或底部对齐。
layer层 指定节点、边缘或集群所在的层。
layers 类型:layerList,默认值:“”
指定附加到图形的图层名称的线性排序列表,然后在单独的层中输出该图。只有属于当前输出层的那些组件才会出现。
‘’’
digraph G {
layers=“local:pvt:test🆕ofc”;
node1 [layer=“pvt”];
node2 [layer=“all”];
node3 [layer=“pvt:ofc”]; /* pvt, test, new, and ofc /
node2 -> node3 [layer=“pvt:all”]; / same as pvt:ofc /
node2 -> node4 [layer=3]; / same as test */
}
‘’’
layout
指定要使用的布局引擎的名称,例如dot或neato。
通常,图表应该独立于某种布局。然而,在某些情况下,在图表中嵌入所需的布局类型会很方便。
例如,包含来自布局的位置信息的图形可能想要记录关联的布局引擎是什么。
此属性优先于使用的-K标志或实际命令名称。
len
type: double, default: 1.0 (neato) , 0.3 (fdp)
Preferred edge length, in inches.
Note: neato, fdp only
lhead
Logical head of an edge.
When compound is true, if lhead is defined and is the name of a cluster containing the real head,
the edge is clipped to the boundary of the cluster.
当compound为真时,如果lhead已定义并且是包含真实头部的集群的名称,则边缘被裁剪到集群的边界。
ltail
Logical tail of an edge.
When compound=true, if ltail is defined and is the name of a cluster containing the real tail,
the edge is clipped to the boundary of the cluster.
margin
类型:双| 点,默认:
对于图形,这将设置画布的 x 和 y 边距,以英寸为单位。
如果边距是单个双精度,则两个边距都设置为等于给定值。
请注意,边距不是绘图的一部分,而只是绘图周围的空白区域。
边距基本上对应于绘图的翻译,这对于将绘图在页面上居中是必需的。
边缘实际上没有绘制任何内容。要实际扩展绘图的背景,请参见pad属性。
对于集群,margin指定集群中的节点与集群边界框之间的空间。默认情况下,这是 8 个点。
对于节点,此属性指定节点标签周围的空间。默认情况下,该值为0.11,0.055。
root 根
类型:字符串| bool , 默认值: (graphs) , false(nodes)
指定要用作布局中心的节点和生成的生成树的根。
作为图形属性,这给出了节点的名称。
作为节点属性,它指定该节点应用作中心节点。
在twopi中,root实际上将是中心节点。在circo中,包含该节点的块将在其连接组件的绘图中处于中心位置。
如果未定义,twopi将选择一个最中心的节点,circo 并将选择一个随机节点。
如果根属性定义为空字符串,twopi将其重置为选择为根节点的节点的名称。
对于twopi,可能有多个根,可能每个分量都有一个根。如果一个组件中有多个节点被标记为root, twopi将选择一个。
适用于:图表 节点
注意:twopi,仅 circo
sep
类型:addDouble | addPoint,默认值:+4
删除节点重叠时在节点周围留出的边距。这保证了节点之间的最小非零距离。
如果属性以加号开头,'+'则指定附加边距。也就是说,"+w,h"使节点的边界框在 w左右两侧增加h点,在顶部和底部增加点。
如果没有加号,则节点1 + w在 x 坐标和 1 + hy 坐标中按比例缩放。
如果只给出一个数字,则这将用于两个维度。
如果未设置但esep已定义,则这些sep值将设置为 esep除以 的值0.8。如果esep未设置,则使用默认值。
适用于:图表
tail_lp
类型:点
边缘尾部标签的位置,以点为单位。该位置表示标签的中心。
适用于:边缘 注意:只写
weight
类型:整数| 双倍,默认值:1,最小值:0(dot,twopi),1(neato,fdp)
边缘的重量。
在dot中,重量越重,边缘越短、越直、越垂直。
对于twopi,weight=0表示边不应用于从根构造生成树。
对于其他布局,较大的权重会鼓励布局使边长更接近len属性指定的边长。
权重dot必须是整数。
xlabel
类型:lblString,默认值:“”
节点或边的外部标签。
对于节点,标签将放置在节点之外但靠近它。
对于边缘,标签将放置在边缘中心附近。这在 dot 中很有用,可以避免使用边缘标签扭曲布局时偶尔出现的问题。
对于其他布局,可以将 xlabel 属性视为该label 属性的同义词。
在放置所有节点和边之后添加这些标签。
将放置标签,使其不与任何节点或标签重叠。这意味着可能无法将它们全部放置。要强制放置所有这些,请设置forcelabels=true.
xlp
类型:点
外部标签的位置,以磅为单位。
该位置表示标签的中心。
适用于:边缘 节点 注意:只写
distortion 失真
参考网页:
https://www.likecs.com/show-161666.html
https://graphviz.org/doc/info/shapes.html
https://www2.graphviz.org/Packages/stable/windows/
https://gitlab.com/graphviz/graphviz/-/releases
http://www.graphviz.org/doc/info/attrs.html
https://graphviz.gitlab.io/doc/info/attrs.html