当前位置: 首页 > 工具软件 > PyGraphviz > 使用案例 >

pygraphviz 学习笔记

伍皓
2023-12-01

pygraphviz 学习笔记
个人认为python第三方库中 graphviz比 pygraphviz好,以下是之前学习pygraphviz的笔记:
G.add_path(nlist)
按nlist增加路径
G.clear() Remove all nodes, edges, and attributes from the graph.
G.degree(nbunch=None, with_labels=False)
Return the degree of nodes given in nbunch container. 这里的degree指点的连接数量。
Using optional with_labels=True returns a dictionary keyed by node with value set to the degree.

degree_iter(nbunch=None, indeg=True, outdeg=True)
Return an iterator over the degree of the nodes given in nbunch container.
Returns pairs of (node,degree).

delete_edge(u, v=None, key=None)
Remove edge between nodes u and v from the graph.
With optional key argument will only remove an edge matching (u,v,key).
delete_edges_from(ebunch)
Remove edges from ebunch (a container of edges).
delete_node(n)
Remove the single node n.
Attempting to remove a node that isn’t in the graph will produce an error.

delete_subgraph(name) Remove subgraph with given name.
property directed G.directed Return True if graph is directed or False if not.
draw(path=None, format=None, prog=None, args=‘’)
Output graph to path in specified format.
An attempt will be made to guess the output format based on the file extension of path. If that fails, then the format parameter will be used.
Note, if path is a file object returned by a call to os.fdopen(), then the method for discovering the
format will not work. In such cases, one should explicitly set the format parameter; otherwise, it will default to ‘dot’.
If path is None, the result is returned as a Bytes object.
Formats (not all may be available on every system depending on how Graphviz was built)
‘canon’, ‘cmap’, ‘cmapx’, ‘cmapx_np’, ‘dia’, ‘dot’, ‘fig’, ‘gd’, ‘gd2’, ‘gif’, ‘hpgl’, ‘imap’,
‘imap_np’, ‘ismap’, ‘jpe’, ‘jpeg’, ‘jpg’, ‘mif’, ‘mp’, ‘pcl’, ‘pdf’, ‘pic’, ‘plain’, ‘plain-ext’,
‘png’, ‘ps’, ‘ps2’, ‘svg’, ‘svgz’, ‘vml’, ‘vmlz’, ‘vrml’, ‘vtx’, ‘wbmp’, ‘xdot’, ‘xlib’
If prog is not specified and the graph has positions (see layout()) then no additional graph positioning will be performed.
Optional prog=[‘neato’|’dot’|’twopi’|’circo’|’fdp’|’nop’] will use specified graphviz layout method.

adjacent adj.相邻; 邻近的; 与…毗连的;
[例句]The house adjacent to ours is under repairs. 与我家相邻的房子正在修缮。

from_string(string)
Load a graph from a string in dot format.
Overwrites any existing graph.
To make a new graph from a string use

get_edge(u, v, key=None) Return an edge object (Edge) corresponding to edge (u,v).
get_node(n) Return a node object (Node) corresponding to node n.

get_subgraph(name) Return existing subgraph with specified name or None if it doesn’t exist.
has_edge(u, v=None, key=None) Return True an edge u-v is in the graph or False if not.

has_neighbor(u, v, key=None) Return True if u has an edge to v or False if not.
has_node(n) Return True if n is in the graph or False if not.

in_degree(nbunch=None, with_labels=False) 入度数
Return the in-degree of nodes given in nbunch container.
Using optional with_labels=True returns a dictionary keyed by node with value set to the degree.

in_degree_iter(nbunch=None)
Return an iterator over the in-degree of the nodes given in nbunch container.
Returns pairs of (node,degree).

in_edges(nbunch=None, keys=False)
Return list of in edges in the graph. If the optional nbunch (container of nodes) only in edges
adjacent to nodes in nbunch will be returned.

in_edges_iter(nbunch=None, keys=False)
Return iterator over out edges in the graph.
If the optional nbunch (container of nodes) only out edges adjacent to nodes in nbunch will be returned.
Note: modifying the graph structure while iterating over edges may produce unpredictable results. Use in_edges() as an alternative.

in_neighbors(n) Return list of predecessor nodes of n.
is_directed() Return True if graph is directed or False if not.
is_strict() Return True if graph is strict or False if not.Strict graphs do not allow parallel edges or self loops.
is_undirected() Return True if graph is undirected or False if not.
iterdegree(nbunch=None, indeg=True, outdeg=True) Return an iterator over the degree of the nodes given in nbunch container.Returns pairs of (node,degree).
iteredges(nbunch=None, keys=False)
Return iterator over edges in the graph.
If the optional nbunch (container of nodes) only edges adjacent to nodes in nbunch will be returned.
Note: modifying the graph structure while iterating over edges may produce unpredictable results. Use edges() as an alternative.

iterindegree(nbunch=None)
Return an iterator over the in-degree of the nodes given in nbunch container.
Returns pairs of (node,degree).

iterinedges(nbunch=None, keys=False)
Return iterator over out edges in the graph.
If the optional nbunch (container of nodes) only out edges adjacent to nodes in nbunch will be returned.
Note: modifying the graph structure while iterating over edges may produce unpredictable results. Use in_edges() as an alternative.

iterneighbors(n)
Return iterator over the nodes attached to n.
Note: modifying the graph structure while iterating over node neighbors may produce unpredictable results.
Use neighbors() as an alternative.

iternodes()
Return an iterator over all the nodes in the graph.
Note: modifying the graph structure while iterating over the nodes may produce unpredictable results. Use nodes() as an alternative.

iteroutdegree(nbunch=None)
Return an iterator over the out-degree of the nodes given in nbunch container.
Returns pairs of (node,degree).

iteroutedges(nbunch=None, keys=False)
Return iterator over out edges in the graph.
If the optional nbunch (container of nodes) only out edges adjacent to nodes in nbunch will be returned.
Note: modifying the graph structure while iterating over edges may produce unpredictable results.
Use out_edges() as an alternative.

iterpred(n)
Return iterator over predecessor nodes of n.
Note: modifying the graph structure while iterating over node predecessors may produce unpredictable results.
Use predecessors() as an alternative.

itersucc(n)
Return iterator over successor nodes of n.
Note: modifying the graph structure while iterating over node successors may produce unpredictable results.
Use successors() as an alternative.

layout(prog=‘neato’, args=‘’)
Assign positions to nodes in graph.
Optional prog=[‘neato’|’dot’|’twopi’|’circo’|’fdp’|’nop’] will use specified graphviz layout method.

number_of_edges() Return the number of edges in the graph.
number_of_nodes() Return the number of nodes in the graph.
order() Return the number of nodes in the graph.

out_degree(nbunch=None, with_labels=False) Return the out-degree of nodes given in nbunch container.
Using optional with_labels=True returns a dictionary keyed by node with value set to the degree.

out_degree_iter(nbunch=None)
Return an iterator over the out-degree of the nodes given in nbunch container. Returns pairs of (node,degree).

out_edges(nbunch=None, keys=False) Return list of out edges in the graph.
If the optional nbunch (container of nodes) only out edges adjacent to nodes in nbunch will be returned.

out_edges_iter(nbunch=None, keys=False) Return iterator over out edges in the graph.
If the optional nbunch (container of nodes) only out edges adjacent to nodes in nbunch will be returned.
Note: modifying the graph structure while iterating over edges may produce unpredictable results.
Use out_edges() as an alternative.

out_neighbors(n) Return list of successor nodes of n.
predecessors(n) Return list of predecessor nodes of n.

predecessors_iter(n) Return iterator over predecessor nodes of n.
Note: modifying the graph structure while iterating over node predecessors may produce unpredictable results.
Use predecessors() as an alternative.

read(path) Read graph from dot format file on path. path can be a file name or file handle
use: G.read(‘file.dot’)

remove_edge(u, v=None, key=None) Remove edge between nodes u and v from the graph.
With optional key argument will only remove an edge matching (u,v,key).

remove_edges_from(ebunch) Remove edges from ebunch (a container of edges).
remove_node(n) Remove the single node n. Attempting to remove a node that isn’t in the graph will produce an error

remove_subgraph(name) Remove subgraph with given name.
reverse() Return copy of directed graph with edge directions reversed.
property strict Return True if graph is strict or False if not. Strict graphs do not allow parallel edges or self loops.
G.directed
string() Return a string (unicode) representation of graph in dot format.

string_nop() Return a string (unicode) representation of graph in dot format.
subgraph(nbunch=None, name=None, **attr) Return subgraph induced by nodes in nbunch.
subgraph_parent(nbunch=None, name=None) Return parent graph of subgraph or None if graph is root graph.
subgraph_root(nbunch=None, name=None) Return root graph of subgraph or None if graph is root graph.
subgraphs() Return a list of all subgraphs in the graph.
subgraphs_iter() Iterator over subgraphs.
successors(n) Return list of successor nodes of n.
successors_iter(n) Return iterator over successor nodes of n.
Note: modifying the graph structure while iterating over node successors may produce unpredictable results.
Use successors() as an alternative.

to_directed(**kwds) Return directed copy of graph. Each undirected edge u-v is represented as two directed edges u->v and v->u.

to_string() Return a string representation of graph in dot format.
to_string() uses “agwrite” to produce “dot” format w/o rendering. The function string_nop() layouts with “nop” and renders to “dot”.
to_undirected() Return undirected copy of graph.

tred(args=‘’, copy=False)
Transitive reduction of graph. Modifies existing graph. To create a new graph use
图的传递约简。修改现有图表。
创建一个新的图表使用
import pygraphviz as pgv
A = pgv.AGraph(directed=True)
B = A.tred(copy=True)
有关算法的详细信息,请参阅 graphviz“ tred ”程序。

def tred(self, args=“”, copy=False):
“”“Transitive reduction of graph. Modifies existing graph.To create a new graph use
>>> import pygraphviz as pgv
>>> A = pgv.AGraph(directed=True)
>>> B = A.tred(copy=True) # doctest: +SKIP
See the graphviz “tred” program for details of the algorithm.
“””
if not self.directed:
raise TypeError(“tred requires a directed graph”)

data = self._run_prog("tred", args)
if copy:
    return self.__class__(string=data.decode(self.encoding))
else:
    return self.from_string(data)

unflatten(args=‘’) Adjust directed graphs to improve layout aspect ratio.

write(path=None) Write graph in dot format to file on path. path can be a file name or file handle
use: G.write(‘file.dot’)

创建边时,可以将属性添加到边: A.add_edge(‘Alice’, ‘Emma’, weight=5)
或者您可以稍后设置它们:
edge = A.get_edge(‘Alice’, ‘Emma’)
edge.attr[‘weight’] = 5
要向边添加文本信息,请改为给它们一个label属性:
edge = A.get_edge(‘Alice’, ‘Emma’)
edge.attr[‘label’] = ‘5’
所有属性都在内部存储为字符串,但GraphViz将这些属性解释为特定类型

创建图形
G = pgv.AGraph(directed=True, strict=False, nodesep=0, ranksep=1.2, rankdir=“TB”,
splines=“none”, concentrate=True, bgcolor=“white”,
compound=True, normalize=False, encoding=‘UTF-8’)
directed -> False | True:有向图
strict -> True | False:简单图
nodesep:同级节点最小间距
ranksep:不同级节点最小间距
rankdir:绘图方向,可选 TB (从上到下), LR (从左到右), BT (从下到上), RL (从右到左)
splines:线条类型,可选 ortho (直角), polyline (折线), spline (曲线), line (线条), none (无)
concentrate -> True | False:合并线条 (双向箭头)
bgcolor:背景颜色
compound -> True | False:多子图时,不允许子图相互覆盖
normalize -> False | True:以第一个节点作为顶节点

添加节点
G.add_node(name, label=None, fontname=“Times-Roman”, fontsize=14,
shape=“ellipse”, style=“rounded”, color=“black”, fontcolor=“black”,
pos=“x,y(!)”, fixedsize=False, width=1, height=1)

G.add_nodes_from(names, **attr) # 批量添加点,参数同上
name -> str:节点名。
label 为节点标签,未指定时显示 name
fontname:字体名称,常用:Microsoft YaHei, SimHei, KaiTi, SimSun, FangSong, Times-Roman, Helvetica, Courier。
可以使用 “times bold italic” 表示字体类型、粗细、倾斜
fixedsize -> Flase | True | “shape”`:固定大小,默认随文本长度变化。
设置为 True 时,width 和 height 参数共同控制点大小。设置为 “shape” 时,将取标签文本和设置值的较大者
shape:节点形状
style:节点线样式
color:设置线条颜色 (style=“filled” 时,设置填充颜色)
pos -> str:点的初始位置。使用 “x,y!” 时,可以强制固定点的位置

添加边
G.add_edge(origin, target, color=“black”, style=“solid”, penwidth=1,
label=“”, fontname=“Times-Roman”, fontsize=14, fontcolor=“black”,
arrowsize=1, arrowhead=“normal”, arrowtail=“normal”, dir=“forward”)

G.add_nodes_from([[origin_1, target_1],
[origin_2, target_2],…], **attr) # 批量添加线,参数同上
label -> str:边标签,未指定时不显示
penwidth:线条粗细
arrowsize:箭头大小
arrowhead:箭头类型,可选 normal, vee
dir:箭头方向,可选 both, forward, back, none。只有在无向图中才起作用!

导出图形
G.layout()
G.draw(file_name, prog=“neato”)
prog:布局算法,可选 neato, dot (推荐), twopi, circo, fdp
众多的布局器:
dot 主要用于有向图
neato 基于spring-model(又称force-based)算法
twopi 径向布局
circo 圆环布局
fdp 用于无向图

例子:

G = pgv.AGraph() # 使用 AGraph 类制作一个空的 pygraphviz 图
# pgv.AGraph()的参数:
# name:    Name for the graph
# strict: True|False (True for simple graphs) 
# 默认是创建一个严格的图(没有平行边或自循环)。要创建具有可能平行边和自环的有向图,请使用pgv.AGraph(strict=False, directed=True)
# 图也可以描述为严格的。这禁止了多边的创建,
# 即在有向情况下,最多可以有一个边具有给定的尾节点和头节点。对于无向图,最多可以有一条边连接到相同的两个节点。
# directed: True|False   默认为False,当为True时为有向图
# data: Dictionary of dictionaries or dictionary of lists; representing nodes or edges to load into initial graph
# 使用字典的字典,d = {"1": {"2": None}, "2": {"1": None, "3": None}, "3": {"2": None}};A = pgv.AGraph(d)
# string:  String containing a dot format graph ,初始化图形的其他选项是使用字符串,pgv.AGraph("graph {1 -- 2}")
# handle:  Swig pointer to an agraph_t data structure
# 使用指向 AGraph 数据结构的 SWIG 指针,
# swig可以将c/c++编写的code生成其他语言(python / js / java / c# / perl / lisp / ….)的接口,本质是一个代码生成工具.
# h = A.handle
# C = pgv.AGraph(h)
# ranksep  ???ranksep="0.1"
G.add_node(u"小兵", color="red", fontname="SimSun", shape="rect", style="rounded", fontsize=18) # 
# 在 PyGraphviz 使用中文要注意使用 unicode ,例如:u"汉字";添加节点时必须指定中文的字体,例如 fontname=SimSun
# style 的取值:filled,rounded,invis透明
# color 是设置框的颜色,而非字体,取值 有:"#feb64d"   "#CFDBF6"   "#B4E7B7"
# fontname 的取值有 SimHei黑体,SimSun宋体,FangSong仿宋,KaiTi楷体,Microsoft YaHei微软雅黑体
# shape的取值有rect,box3d,circle,polygon
G.add_node(u"小卒", fontname="SimHei", style="filled") # 
G.add_node('a')
G.add_edge(u"小兵", u"小卒",color="#CFDBF6",style="dashed",penwidth=1.5) # 连线
G.add_edge('a', u"小兵")
# G.add_edges_from() 可增加多条边
# nodelist = ["f", "g", "h"]
# G.add_nodes_from(nodelist)
# 如果节点不是字符串,则会尝试将其转换为字符串
# G.add_node(1)  # adds node '1'
G1 = G.add_subgraph([2, 3, 'B'],name="s1",rank = 'same') # 添加子图
# 子图在 Graphviz 中扮演三个角色。
# 首先,子图可以用来表示图结构;还可以为边缘提供方便的简写。
# 在第二个角色中,子图可以提供设置属性的上下文。
# 子图的第三个角色直接涉及某些布局引擎将如何布局图。

G1.add_edge( 2 , 'B' ,style = 'dashed')
G1.add_edge( 'B' , 3 ,style = 'dashed')
G1.add_edge( 'B' , 'a' ,style = 'dashed')

G.graph_attr[ 'epsilon' ] = '0.001'  # 增加图属性

# 要设置图、节点和边的默认属性,请使用 graph_attr、node_attr 和 edge_attr 字典
# G.graph_attr["label"] = "Name of graph"
# G.node_attr["shape"] = "circle"
# G.edge_attr["color"] = "red"

# 通过节点或边属性字典,
n = G.get_node(2)
n.attr["shape"] = "box"
e = G.get_edge("B", "a")
e.attr["color"] = "green"

print(G.nodes()) # 查看个节点
print(G.string()) # 打印图的dot表达式
G.write('test000.dot') # 将图写入 test000.dot
G.draw('test_pygraphviz000.png', format='png', prog='neato')

G2=pgv.AGraph('test000.dot') # 读取test000.dot 创建新图
G2.layout() # layout with default (neato)   or  G2.layout('dot')
# prog=[‘neato’|’dot’|’twopi’|’circo’|’fdp’|’nop’]
# layout n.布局; 布置; 设计; 安排;
#[例句]This boat has a good deck layout making everything easy to operate.
# 这艘船的甲板布局合理,使得所有操控都很方便。
G2.draw('test222.png') # draw png
#G2.draw("test222.ps", prog="circo")  # use circo to position, write PS file

参考文献:
https://pygraphviz.github.io/
https://www.wenjiangs.com/doc/vo4aseck
http://www.graphviz.org/

 类似资料: