本文整理汇总了Python中graphviz.Graph方法的典型用法代码示例。如果您正苦于以下问题:Python graphviz.Graph方法的具体用法?Python graphviz.Graph怎么用?Python graphviz.Graph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graphviz
的用法示例。
在下文中一共展示了graphviz.Graph方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bipartite_as_graph
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def bipartite_as_graph(self) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in self.bipartite._edges.items():
if left not in nodes_left:
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
label = str(self.subjects_by_id[left])
graph.node(name, label=label)
node_id += 1
if right not in nodes_right:
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
label = str(self.automaton.patterns[right][0])
graph.node(name, label=label)
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
示例2: as_graph
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def as_graph(self) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in self._edges.items():
if left not in nodes_left:
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
graph.node(name, label=str(left))
node_id += 1
if right not in nodes_right:
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
graph.node(name, label=str(right))
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
示例3: gen_graph_from_nodes
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def gen_graph_from_nodes(nodes, type_fail=None):
graph = Graph(format='png', strict=True)
graph.node_attr['fontname'] = 'Courier New'
graph.edge_attr['fontname'] = 'Courier New'
for node in nodes:
graph.node(_type_str(node.type),
'{type: %s|ast_node: %s|parent\'s type: %s}' %
(_type_str(node.type),
node.ast_node.as_string().replace('<', '\\<').replace('>', '\\>')
if node.ast_node else 'None',
_type_str(node.parent.type) if node.parent else 'NA'),
shape='record', style='rounded')
for neighb, ctx_node in node.adj_list:
graph.edge(_type_str(node.type), _type_str(neighb.type),
label=(f' {ctx_node.as_string()}' if ctx_node else ''))
if type_fail:
graph.node('tf',
'{TypeFail|src_node: %s}' %
(type_fail.src_node.as_string().replace('<', '\\<').replace('>', '\\>')
if type_fail.src_node else 'None'), shape='record')
graph.edge('tf', _type_str(type_fail.tnode1.type), style='dashed')
graph.edge('tf', _type_str(type_fail.tnode2.type), style='dashed')
graph.view('tnode_graph')
示例4: concrete_bipartite_as_graph
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
bipartite = self._build_bipartite(subjects, patterns)
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in bipartite._edges.items():
if left not in nodes_left:
subject_id, i = left
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
label = '{}, {}'.format(i, self.subjects_by_id[subject_id])
graph.node(name, label=label)
node_id += 1
if right not in nodes_right:
pattern, i = right
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
label = '{}, {}'.format(i, self.automaton.patterns[pattern][0])
graph.node(name, label=label)
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
示例5: __init__
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def __init__(self, id, vizformat='svg'):
self.id = id
# Config
# self.base_path = "./"
self.base_path = os.path.join(os.path.dirname(__file__), '')
self.dep_dir = "data/dependencies/"
self.out_dir = ""
self.log_dir = "./"
# graphviz image format
self.vizformat = vizformat
self.width = 2.5
self.height = 2.5
self.graph = functools.partial(gv.Graph, format=self.vizformat)
self.digraph = functools.partial(gv.Digraph, format=self.vizformat)
# Change these for a given run
self.input_path = self.base_path + self.dep_dir
self.output_path = self.base_path + self.out_dir
# load graph
self.dep_dict = self._load_graph_from_dependency_files()
# load other
self.resolved = []
self.nodes = []
self.edges = []
# resolve precursors
self.precursor_list(self.dep_dict, self.id, self.nodes)
self.precursor_controls = self.nodes
示例6: test_sanity_check
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def test_sanity_check():
a = Node(np.eye(2), backend="tensorflow")
b = Node(np.eye(2), backend="tensorflow")
connect(a[0], b[0])
g = to_graphviz([a, b])
#pylint: disable=no-member
assert isinstance(g, graphviz.Graph)
示例7: export_expression_tree
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def export_expression_tree(genome, label_renaming_map=None, file='tree.png'):
"""
Construct the graph of a *genome* and then export it to a *file*.
:param genome: :class:`~geppy.core.entity.KExpression`, :class:`~geppy.core.entity.Gene`, or
:class:`~geppy.core.entity.Chromosome`, the genotype of an individual
:param label_renaming_map: dict, which maps the old name of a primitive (or a linking function)
to a new one for better visualization. The default label for each node is just the name of the primitive
placed on this node. For example, you may provide ``renamed_labels={'and_': 'and'}``.
:param file: str, the file path to draw the expression tree, which may be a relative or absolute one.
If no extension is included in *file*, then the default extension 'png' is used.
.. note::
This function currently depends on the :mod:`graphviz` module to render the tree. Please first install the
`graphviz <https://pypi.org/project/graphviz/>`_ module before using this function.
Alternatively, you can always obtain the raw graph data with the :func:`graph` function, then postprocess the
data and render them with other tools as you want.
"""
import graphviz as gv
import os.path
nodes, edges, labels = graph(genome, label_renaming_map)
file_name, ext = os.path.splitext(file)
ext = ext.lstrip('.')
g = gv.Graph(format=ext)
for name, label in labels.items():
g.node(str(name), str(label)) # add node
for name1, name2 in edges:
g.edge(str(name1), str(name2)) # add edge
g.render(file_name)
示例8: convert_networkx_graph_to_graphiz
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def convert_networkx_graph_to_graphiz(graph, directed=False):
"""
Convert a networkx Multigraph to a graphviz.dot.Graph
This allows us to modify the graphviz graph programmatically in Python before we dump to dot format and plot.
Note the Graphviz plot is created sequentially... It is hard to edit it after the edges and node attrs are written.
Args:
graph (networkx graph): networkx graph to be converted to dot notation
directed (boolean): is `graph` directed... more specifically, do we want the returned graph to be directed?
Returns:
graphviz.dot.Graph: conversion of `graph` to a graphviz dot object.
"""
if directed:
G = gv.Digraph()
else:
G = gv.Graph()
# add nodes and their attributes to graphviz object
for n in graph.nodes():
n_attr = {k: str(v) for k, v in graph.node[n].items()}
G.attr('node', n_attr)
G.node(str(n), str(n))
# add edges and their attributes to graphviz object
for e in graph.edges(keys=True):
e_attr = {k: str(v) for k, v in graph[e[0]][e[1]][e[2]].items()}
G.edge(str(e[0]), str(e[1]), **e_attr)
return G
示例9: plot_circuit_graphviz
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def plot_circuit_graphviz(circuit, graph, filename=None, format='svg', engine='dot', edge_label_attr=None,
graph_attr={'strict': 'false', 'forcelabels': 'true'}, node_attr=None, edge_attr=None):
"""
Builds single graphviz graph with CPP solution.
Wrapper around functions:
- circuit specific formatter: prepare_networkx_graph_circuit_for_transformation_to_graphviz
- general purpose plotter: plot_graphviz
Args:
circuit (list[tuple]): solution of the CPP (result from graph.cpp function
graph (networkx graph): original graph augmented with ``
filename (str): filename of viz output (leave off the file extension... this is appended from `format`)
format (str): 'svg', 'png`, etc
engine (str) : which graphviz engine to use: 'dot', 'neato'. 'circo', etc
edge_label_attr (str) optional name of graph edge attribute to use for label. Default None uses index from circuit.
graph_attr (dict): of graphviz graph level attributes.
node_attr (dict): of graphviz node attributes to pass to each node
edge_attr (dict): of graphviz edge attributes to pass to each edge.
Returns:
graphviz.Graph or graphviz.DirectedGraph with enriched route and plotting data.
Writes a visualization to disk if filename is provided.
"""
graph_gv = prepare_networkx_graph_circuit_for_transformation_to_graphviz(circuit, graph, edge_label_attr)
return plot_graphviz(graph_gv, filename, format, engine, edge_label_attr, graph_attr, node_attr, edge_attr)
示例10: to_graphviz
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def to_graphviz(nodes: Iterable[AbstractNode],
graph: Optional[graphviz.Graph] = None,
include_all_names: bool = False,
engine: Text = "neato") -> graphviz.Graph:
"""Create a graphviz Graph that is isomorphic to the given TensorNetwork.
Args:
nodes: a collection of nodes
graph: An optional `graphviz.Graph` object to write to. Use this only
if you wish to set custom attributes for the graph.
include_all_names: Whether to include all of the names in the graph.
If False, all names starting with '__' (which are almost always just
the default generated names) will be dropped to reduce clutter.
engine: The graphviz engine to use. Only applicable if `graph` is None.
Returns:
The `graphviz.Graph` object.
"""
if graph is None:
#pylint: disable=no-member
graph = graphviz.Graph('G', engine=engine)
for node in nodes:
if not node.name.startswith("__") or include_all_names:
label = node.name
else:
label = ""
graph.node(str(id(node)), label=label)
seen_edges = set()
for node in nodes:
for i, edge in enumerate(node.edges):
if edge in seen_edges:
continue
seen_edges.add(edge)
if not edge.name.startswith("__") or include_all_names:
edge_label = edge.name
else:
edge_label = ""
if edge.is_dangling():
# We need to create an invisible node for the dangling edge
# to connect to.
graph.node(
"{}_{}".format(id(node), i),
label="",
_attributes={"style": "invis"})
graph.edge("{}_{}".format(id(node), i), str(id(node)), label=edge_label)
else:
graph.edge(str(id(edge.node1)), str(id(edge.node2)), label=edge_label)
return graph
示例11: plot_graphviz
# 需要导入模块: import graphviz [as 别名]
# 或者: from graphviz import Graph [as 别名]
def plot_graphviz(graph, filename=None, format='svg', engine='dot', edge_label_attr=None,
graph_attr={'strict': 'false', 'forcelabels': 'true'}, node_attr=None, edge_attr=None):
"""
Creates a dot (graphviz) representation of a networkx graph and saves a visualization.
Args:
graph (networkx graph): original graph augmented with ``
filename (str): filename of viz output (leave off the file extension... this is appended from `format`)
format (str): 'svg', 'png`, etc
engine (str) : which graphviz engine to use: 'dot', 'neato'. 'circo', etc
edge_label_attr (str) optional name of graph edge attribute to use for label. Default None uses index from circuit.
graph_attr (dict): of graphviz graph level attributes.
node_attr (dict): of graphviz node attributes to pass to each node
edge_attr (dict): of graphviz edge attributes to pass to each edge.
Returns:
graphviz.Graph or graphviz.DirectedGraph with
Writes a visualization to disk if filename is provided.
"""
if edge_label_attr:
for i, e in enumerate(graph.edges(data=True, keys=True)):
key = e[2]
graph[e[0]][e[1]][key]['label'] = str(graph[e[0]][e[1]][key][edge_label_attr])
# convert networkx object to graphviz object
graph_gv = convert_networkx_graph_to_graphiz(graph, directed=False)
graph_gv.engine = engine
graph_gv.format = format
# setting graph options.
if graph_attr:
for k, v in graph_attr.items():
graph_gv.graph_attr[k] = v
# setting node options (these will override graph attributes if there is overlap)
if node_attr:
for k, v in node_attr.items():
graph_gv.node_attr[k] = v
# setting edge options (these will override graph attributes if there is overlap)
if edge_attr:
for k, v in edge_attr.items():
graph_gv.edge_attr[k] = v
# write to disk
if filename:
graph_gv.render(filename=filename, view=False)
return "Plot written to {}".format(filename)