本文整理汇总了Python中graphviz.Graph类的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visual_decoding
def visual_decoding(sent, saveto='tmp'):
"""
Visualize multiple translation from machine translation.
Example:
>>> sentence = ['I have a apple',
'I have a dream',
'H have an egg']
>>> visual_decoding(sent=sentence, saveto='demo')
Args:
sent: a list of str
Multiple translations.
saveto: str
Graph will be saved as 'saveto.png'.
Returns:
None
"""
graph = Graph(format='png',
node_attr={'shape':'box'},
graph_attr={'splines':'polyline'},
edge_attr={'dir':'forward'})
graph.body.extend(['rankdir=LR'])
for i,s in enumerate(sent):
graph = _plot_sent(graph, s, flag=str(i))
graph.render(filename=saveto, view=True)
示例2: graph_data
def graph_data(pkg_name):
if not pkg_name:
abort(404)
filepath = os.path.join(cache_dir, pkg_name.lower())
if not os.path.exists(filepath + '.png'):
nodes, edges = reqs_graph(pkg_name)
if not nodes:
return redirect(url_for('static', filename='img/blank.png'))
dot = Graph()
dot.format = 'png'
dot.node('0', nodes[0], fillcolor='#fbb4ae', style='filled', shape='box')
for i, pkg_name in enumerate(nodes[1:]):
dot.node(str(i+1), pkg_name, fillcolor='#ccebc5', style='filled')
dot.edges([
[str(i[0]), str(i[1])]
for i in edges
])
dot.render(filepath)
return send_file(filepath + '.png')
示例3: __str__
def __str__(self):
A = Graph()
for vertice in self.meuGrafo.nodes_iter(data=False):
A.node(vertice.encode("utf8"))
for aresta_A, aresta_B, dados_aresta in self.meuGrafo.edges_iter(data=True):
peso_aresta = dict((chave, str(valor)) for chave, valor in dados_aresta.items())
peso_aresta['label'] = peso_aresta['weight']
del peso_aresta['weight']
A.edge(aresta_A.encode("utf8"), aresta_B.encode("utf8"), **peso_aresta)
return A.source
示例4: model_to_dot
def model_to_dot(model):
g = Graph(name=model.name)
for comp in model.compartments:
gcomp = compartment_to_dot(comp)
gcomp.subgraph = True
gcomp.tag('::'+comp.id)
g.add(gcomp)
if model.get_param('FORCE_LABELS'):
g.add(AttrStmt('graph',forcelabels="true"))
return g
示例5: graphUpdate
def graphUpdate(self):
if self.aType == "tw":
self.graph = Digraph()
elif self.aType == "fb":
self.graph = Graph()
else:
exit("Invalid Analyze Type")
for key in self.nameIndex.keys():
self.graph.node(self.nameIndex[key], key)
for key in self.network.keys():
for friend in self.network[key]:
if friend != "":
self.graph.edge(self.nameIndex[key],self.nameIndex[friend])
示例6: subsystem_to_dot
def subsystem_to_dot(subsystem):
clone_links = clone_mets(subsystem)
g = Graph(name=subsystem.id)
if subsystem.get_param('CLUSTER_SUBSYSTEMS'):
g.cluster = True
style = subsystem.get_param('SUBSYSTEM_BORDER_STYLE')
g.add(AttrStmt('graph',style=style))
for rxn in subsystem.reactions:
g.add(reaction_to_dot(rxn))
g.add(AttrStmt('graph',label=subsystem.name,
fontsize=subsystem.get_param('SUBSYSTEM_FONTSIZE')))
if clone_links:
g.add(clone_links)
return g
示例7: visualize_countries_together_in_item
def visualize_countries_together_in_item(data, start_time_str=None, end_time_str=None, newspaper_str='*'):
countries_together_dict = _get_countries_together_in_items(data)
# print 'countries_together_dict:', countries_together_dict
dot = Graph(comment='Countries together in item graph', engine='sfdp')
seen_countries = set()
edges_between_countries = defaultdict(int)
## Building the graph
for ID_and_feed, countries in countries_together_dict.iteritems():
countries_list = list(countries)
for country in countries_list:
if country != '' and country not in seen_countries:
dot.node(country, label=country)
seen_countries.add(country)
for i in xrange(len(countries)):
for j in xrange(i+1, len(countries)):
fst = min(countries_list[i], countries_list[j])
snd = max(countries_list[i], countries_list[j])
edges_between_countries[(fst, snd)] += 1
for edge_endpoints, edge_weight in edges_between_countries.iteritems():
dot.edge(edge_endpoints[0], edge_endpoints[1], weight=str(edge_weight))
print 'seen_countries:', seen_countries
print 'edges_between_countries:', edges_between_countries
dot = _apply_styles(dot, styles)
# print dot.source
out_dirname = newspaper_str.replace('*', '').replace('!', '').replace('[', '').replace(']', '')
out_filename = ('countries_together_in_item_%s_%s.gv' % (start_time_str, end_time_str)).replace(':', '-')
dot.render(os.path.join('images', out_dirname, out_filename), view=False)
示例8: create_interactions_graph
def create_interactions_graph(clauses, f):
dot = GGraph(comment='Interactions graph', engine='sfdp')
seen_vars = set()
edges_between_vars = defaultdict(int)
for clause in clauses:
for lit in clause:
var = f(lit)
if var not in seen_vars:
seen_vars.add(var)
dot.node(str(var), label=str(var))
for clause in clauses:
l = len(clause)
for i in xrange(l):
for j in xrange(i+1, l):
edges_between_vars[(str(f(clause[i])), str(f(clause[j])))] += 1
for interacting_vars, weight in edges_between_vars.iteritems():
dot.edge(interacting_vars[0], interacting_vars[1], weight=str(weight))
print edges_between_vars
dot = _apply_styles(dot, styles)
# print dot.source
dot.render(os.path.join('images', 'interactions_graph.gv'), view=True)
示例9: visualize
def visualize(self):
l = len(self.top_result)
connections = dict()
tags = dict()
for i in range(l - 1):
for j in range(1, l):
if i != j:
key = (i, j)
message_list = self.get_message_list_between(self.top_result[i], self.top_result[j])
tag_cloud = self.subject.calculate_tag_cloud(message_list)
tags[key] = self.get_top_tag_cloud(tag_cloud, 5)
# DOT language
dot = GraphV(comment = "Information Flow - Enron")
for i in range(l):
dot.node(str(i), self.top_result[i] + " - " + self.company.get_role(self.top_result[i]))
for (edge, tag) in tags.iteritems():
node_1 = edge[0]
node_2 = edge[1]
note = ", ".join(tag)
print note
dot.edge(str(node_1), str(node_2), label=note)
dot.render('test-output/round-table.gv', view=False)
示例10: draw_graph
def draw_graph(self, form, name='sample'):
"""the method for drawing a graph of the tree, name is the file
name under which we want to save it"""
self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form')
self.edges = []
self.comp = 0
self._create_graph(form)
namefile='drawing/'+name+'.gv'
self.dot.render(namefile, view=True)
示例11: __init__
def __init__(self):
self.handler_dict = {Form.OperatorForm:(self.func_op_fo,{Form.D: (self.diff, {})\
, Form.Wedge: (self.wed, {}), Form.Add: (self.add,{}), \
Form.Hodge: (self.hod, {}),Form.Pullback: (self.pull, {}) }),\
Form.TerminalForm:(self.func_term_fo,{})}
self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form') #to store the dot for vizgraph
self.edges = [] #to store the edge for the graph
self.post = [] #to store the post order traversal
self.pre = [] # to store the pre order traversal
self.comp = 0 #to differentiate the edge
示例12: graph_draw
def graph_draw(nodes, edges, name):
g = Graph(name, format="png")
for node in nodes:
g.node(str(node))
for edge in edges:
x = edge.split(' ')[0]
y = edge.split(' ')[1]
g.edge(x, y)
g.view()
示例13: plot
def plot(graph, engine='dot', filename='output/test'):
"""Possible engines: dot, neato, fdp, sfdp, twopi, circo"""
g = Graph(format='png', engine=engine)
for v in graph:
g.node(str(index(v)))
for v, w in graph.edges:
g.edge(str(index(v)), str(index(w)))
g.render(filename)
示例14: renderiza_grafo
def renderiza_grafo(self, lugar_para_gerar, nome_grafo):
A = Graph(comment=nome_grafo, filename=(lugar_para_gerar + '/Grafo.gv'), engine='dot')
for vertice in self.meuGrafo.nodes_iter(data=False):
A.node(vertice.encode("utf8"))
for aresta_A, aresta_B, dados_aresta in self.meuGrafo.edges_iter(data=True):
peso_aresta = dict((chave, str(valor)) for chave, valor in dados_aresta.items())
peso_aresta['label'] = peso_aresta['weight']
del peso_aresta['weight']
A.edge(aresta_A, aresta_B, **peso_aresta)
A.view()
示例15: __init__
class render:
def __init__(self,our_graph,wt_dist,colour_list,tup=[-1,-1]):
self.G = Graph(format='png')
self.edgeList = []
#i=0
for vertex in our_graph.vertList:
self.G.node(str(vertex),label='INF' if wt_dist[vertex]==10000000 else str(wt_dist[vertex]),color='red' if colour_list[vertex] else 'black')
for adjvertices in our_graph.vertList[vertex].connectedTo:
if tup==[vertex,adjvertices] or tup==[adjvertices,vertex]:
cl='green'
else:
cl='black'
#print vertex.connectedTo[adjvertices]
if our_graph.vertList[vertex].connectedTo[adjvertices][1] in self.edgeList:
pass
else:
self.G.edge(str(vertex),str(adjvertices),str(our_graph.vertList[vertex].connectedTo[adjvertices][0]),color=cl)
self.edgeList.append(our_graph.vertList[vertex].connectedTo[adjvertices][1])
#self.G.edge(str(vertex),str((vertex+1)%10),label='edge',color='green')
self.G.view()