本文整理汇总了Python中networkx.to_agraph函数的典型用法代码示例。如果您正苦于以下问题:Python to_agraph函数的具体用法?Python to_agraph怎么用?Python to_agraph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_agraph函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_graphs
def plot_graphs(self,path,count):
'''Save graphs'''
Gs=nx.to_agraph(self.gS)
Gm=nx.to_agraph(self.gM)
Gs_w=nx.to_agraph(self.gS_w)
#add color to main nodes
for node in self.gM.nodes():
n=Gs.get_node(node)
n.attr['shape']='box'
n.attr['style']='filled'
n.attr['fillcolor']='turquoise'
#add weight to edges
for edge in self.gS_w.edges(data=True):
ed=Gs_w.get_edge(edge[0],edge[1])
ed.attr['label']=edge[2]['weight']
loc= os.getcwd()+path+'/spanning/gS' + str(count)+'.png'
loc1= os.getcwd()+path+'/projection/gM' + str(count)+'.png'
loc2= os.getcwd()+path+'/spanning_w/gS_w' + str(count)+'.png'
Gs.layout(prog='dot') # use dot
Gm.layout(prog='dot') # use dot
Gs_w.layout(prog='dot')
Gs.draw(loc)
Gm.draw(loc1)
Gs_w.draw(loc2)
return
示例2: draw_graph
def draw_graph(graph, output_path):
"""
Draws a networkx graph to disk using the `dot` format.
``graph``:
networkx graph
``output_path``:
Location to store the rendered output.
"""
nx.to_agraph(graph).draw(output_path, prog="dot")
log.info("Wrote output to `%s'" % output_path)
示例3: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('path', help = "target file or directory for summarization")
parser.add_argument("--posseed", help="boosting seed for biased LexRank", default = None)
parser.add_argument("--negseed", help="blocking seed for biased LexRank", default = None)
parser.add_argument("--stopfile", help="file containing custom stopwords")
parser.add_argument("-o", "--output", help = "output file name")
parser.add_argument("-l", "--length", help = "summary length in lines", default = 10)
parser.add_argument("--seed_posweight", help = "Weight for positive seed", default = 3)
parser.add_argument("--seed_negweight", help = "Weight for negative seed", default = .0001)
parser.add_argument("--ngrams", help = "N-gram number", default = 1)
#normalization doesn't work due to being inherent within scoring method
parser.add_argument("-n", "--is_norm", help = "Boolean flag for normalization", default = True)
args = parser.parse_args()
input_text = args.path
pos_seed = args.posseed
neg_seed = args.negseed
stopfile = args.stopfile
out_file = args.output
sum_length = int(args.length)
norm_flag = args.is_norm
pos_weight = float(args.seed_posweight)
neg_weight = float(args.seed_negweight)
ngram = int(args.ngrams)
corpus = Corpus(input_text).documents
output_checker(out_file)
if pos_seed == None and neg_seed == None:
LR_method = 'unbiased'
print LR_method
[term_matrix, normalized] = TDM(corpus, pos_seed, neg_seed, stopfile, norm_flag, ngram).matrix
pos_seed_vector = []
neg_seed_vector = []
else:
LR_method = 'biased'
if pos_seed == None:
pos_seed = ''
if neg_seed == None:
neg_seed = ''
[term_matrix, normalized, pos_seed_vector, neg_seed_vector] = TDM(corpus, pos_seed, neg_seed, stopfile, norm_flag, ngram).matrix
corpus = corpus[2:]
[scores,graph] = Graph(normalized, LR_method, pos_seed_vector, neg_seed_vector, pos_weight, neg_weight).sim_scores
#embed()
largest = networkx.strongly_connected_component_subgraphs(graph)[0]
A = networkx.to_agraph(largest)
#A.node_attr.update(shape='point')
A.node_attr.update(overlap='voronoi')
A.layout(prog='sfdp')
networkx.write_dot(largest, 'testgraph.gv')
A.draw('butterflyv2.png')
print_summary(corpus, scores, out_file, sum_length)
示例4: __generar_imagenes
def __generar_imagenes(self):
A = nx.to_agraph(self.DRPC) # convert to a graphviz graph
A.layout(prog='dot') # neato layout
A.draw("DRPC.png", prog='dot')
A = nx.to_agraph(self.DAPC) # convert to a graphviz graph
A.layout()
A.draw("DAPC.png", prog='dot')
A = nx.to_agraph(self.DRPCP) # convert to a graphviz graph
A.layout(prog='dot') # neato layout
A.draw("DRPCP.png", prog='dot')
A = nx.to_agraph(self.DAPCP) # convert to a graphviz graph
A.layout()
A.draw("DAPCP.png", prog='dot')
示例5: draw
def draw(self):
A = nx.to_agraph(self.Graph)
A.add_subgraph([root],rank='same')
for level in self.levels:
A.add_subgraph(level,rank='same')
A.draw(self.filen, prog='dot')
示例6: view_spec_svg
def view_spec_svg(request, spec_id, fullsize=False):
spec = get_object_or_404(approval_models.WorkflowSpec,
id=spec_id)
graph = spec.to_coloured_graph()
agraph = nx.to_agraph(graph)
for nodename in agraph.nodes():
node = agraph.get_node(nodename)
if 'task_data' in node.attr['data']:
node.attr.update({
'URL': reverse('task_dict', kwargs={
'spec_id': spec.id,
'task_name': str(node)}),
'fontcolor': '#0000FF',
'target': '_parent',
})
del node.attr['data']
# IE9 (+others?) fix: they don't have "Times Roman", only "Times
# New Roman" TODO REFACTOR
agraph.node_attr['fontname'] = "Times New Roman"
agraph.edge_attr['fontname'] = "Times New Roman"
svg = agraph.draw(None, 'svg', 'dot')
# http://www.graphviz.org/content/percentage-size-svg-output
if not fullsize:
svg = re.sub(r'<svg width="[0-9]+pt" height="[0-9]+pt"',
r'<svg width="100%" height="100%"', svg)
response = HttpResponse(svg, content_type="image/svg+xml")
return response
示例7: Graph_draw
def Graph_draw (G_in, G_name):
default_attributes={'graph':{},'node':{},'edge':{}}
#default_attributes['graph']['label']='pygraphviz graph'
default_attributes['node']['shape']='box'
for u,v,d in G_in.edges(data=True):
d['label'] = d.get('weight','')
A = nx.to_agraph(G_in)
# A.edge_attr['constraint']='false'
# A.edge_attr['labeldistance']='1'
# A.edge_attr['forcelabels']='true'
#A.edge_attr['decorate']='true'
# A.graph_attr['ranksep']='equally'
A.graph_attr['rankdir']='LR'
# A.graph_attr['splines']='line'
# A.node_attr['shape']='oval'
A.add_subgraph(('X'), name = 'cluster_1',style='invis', rank=1)
A.add_subgraph((1,2,3), name = 'cluster_2',style='invis', rank =2)
A.add_subgraph((10,20,30,40), name = 'cluster_3',style='invis', rank=3)
A.add_subgraph(('Y'), name = 'cluster_4',style='invis', rank=4)
A.add_subgraph(('X',3,30,'Y'), name='path')
A.layout(prog='dot')
A.draw(G_name+'.png')
A.write('G1.dot')
return
示例8: show_pygraphviz
def show_pygraphviz(g, prog='dot', graph_attr={}, node_attr={}, edge_attr={}):
"""
Display a networkx graph using pygraphviz.
Parameters
----------
prog : str
Executable for generating the image.
graph_attr : dict
Global graph display attributes.
node_attr : dict
Global node display attributes.
edge_attr : dict
Global edge display attributes.
"""
fd = tempfile.NamedTemporaryFile(suffix='.jpg')
fd.close()
p = nx.to_agraph(g)
p.graph_attr.update(graph_attr)
p.node_attr.update(node_attr)
p.edge_attr.update(edge_attr)
p.draw(fd.name, prog=prog)
imdisp(fd.name)
os.remove(fd.name)
示例9: aSymGraphObject
def aSymGraphObject(G_in, types, color = 'black') :
G1 = symSubGraphFromTypes(G_in, types, color)
G = nx.to_agraph(G1)
G.graph_attr.update(splines='true', overlap='false', ratio='fill', size='15,15')
for node in G.nodes() :
w = 0.3*(G.in_degree(node) + G.out_degree(node))
w = 0.4 + int(w*10)/10.0
size = str(w)
print node, 'degrees', G.in_degree(node), G.out_degree(node),' width ', size
node.attr['width'] = size
node.attr['height'] = size
node.attr['fontsize'] = '32'
node.attr['fixedsize'] = 'true'
G = makeLayout(G)
for node in G.nodes() :
node.attr['label'] = node.attr['number']
if (G.out_degree(node) == 0) & (G.in_degree(node) == 0) :
G.remove_node(node)
if node.attr['number'] == '1' :
node.attr['style'] = 'filled'
node.attr['fillcolor'] = '#FFFAAA'
for node in G.nodes() :
print '(Sym. final) Degree of', node, '-', G.in_degree(node), G.out_degree(node), 'width', node.attr['width']
return G
示例10: to_graphviz
def to_graphviz(G, gvfile, graph_label='', **kwargs):
""" export graph of signifcant findings to dot file.
A png can be generated from the commandline using graphviz
>>> import subprocess
>>> subprocess.call(['dot', '-Tpng', 'filpath.dot', '>', 'filepath.png'])
:param G: the graph to be exported
:param gvfile: file or filepath
:param graph_label: For empty label pass graph_label=''.
"""
for n in G:
node = G.node[n]
attr = {}
attr['shape'] = 'record'
if not np.isnan(node.get('q', float('NaN'))):
attr['color'] = 'red' if node['significant'] else 'black'
attr['label'] = "{name}\\n{x} / {n} genes\\nq = {q:E}".format(name=node['name'],
q=node['q'], x=node['x'], n=node['n'])
else:
attr['color'] = 'black'
attr['label'] = """{name}""".format(name=node['name'])
G.node[n] = attr
A = nx.to_agraph(G)
A.graph_attr['label'] = graph_label
A.graph_attr['labelloc'] = 't'
if hasattr(gvfile, 'write'):
A.write(gvfile)
else:
with open(gvfile, 'w') as f:
A.write(f)
示例11: make_pdf
def make_pdf(dg):
agraph = networkx.to_agraph(dg)
agraph.graph_attr['overlap']='false'
agraph.graph_attr['splines']='true'
agraph.graph_attr['rankdir']='LR'
agraph.graph_attr['ranksep']='.1'
agraph.draw('test.pdf',prog='dot')
示例12: corner_network
def corner_network(ant, data):
#G = nx.cubical_graph()
G = nx.Graph() #無向グラフ
tmp1 = []
tmp2 = []
tmp3 = []
tmp4 = []
#for i in range(len(data)):
#if data[i][2] == 'lu':
#tmp1.append(str(i))
#elif data[i][2] == 'ld':
#tmp2.append(str(i))
#elif data[i][2] == 'ru':
#tmp3.append(str(i))
#elif data[i][2] == 'rd' :
#tmp4.append(str(i))
for i in range(len(data)):
if len(ant[i].parent) == 0 : pass
else :
dest = ant[i].parent[0]
G.add_edge(str(data[i]), str(data[dest]))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=tmp1, node_size=30, node_color="r")
#nx.draw_networkx_nodes(G, pos, nodelist=tmp2, node_size=30, node_color="b")
#nx.draw_networkx_nodes(G, pos, nodelist=tmp3, node_size=30, node_color="g")
#nx.draw_networkx_nodes(G, pos, nodelist=tmp4, node_size=30, node_color="y")
#nx.draw_networkx_nodes(G, pos, node_size=20, node_color="blue")
nx.draw_networkx_edges(G, pos, width=1)
A = nx.to_agraph(G)
A.layout()
A.draw("file.png")
示例13: main
def main():
args = parse_args(sys.argv)
graph = nx.read_dot(args.infile)
droppers = [re.compile(pattern) for pattern in args.drop]
keepers = [re.compile(pattern) for pattern in args.keep]
rm_nodes = []
num_parents = graph.out_degree()
degree = graph.degree()
for node in graph.nodes():
if matches_any(node, droppers) and not matches_any(node, keepers):
rm_nodes.append(node)
elif degree[node] == 0:
rm_nodes.append(node)
elif num_parents[node] == 0:
graph.node[node]['shape'] = 'hexagon'
else:
pass # Node will not be changed.
detours = get_detours(graph, rm_nodes)
graph.remove_nodes_from(rm_nodes)
graph.add_edges_from(detours, style='dashed')
graph.graph = {} # Clear all graph, edge, and node attributes
# nx.write_dot(graph) should work,
# but doesn't, because it calls nx.to_agraph(graph).clear()
a = nx.to_agraph(graph)
# print(graph.edge, file=sys.stderr)
a.write(sys.stdout)
示例14: save_plot
def save_plot(graph, track_a, track_b, name="graph.png"):
"""save plot with index numbers rather than timing"""
edges = graph.edges(data=True)
e = [edge[2]['source'] for edge in edges]
order = np.argsort(e)
edges = [edges[i] for i in order.tolist()]
nodes = graph.nodes(data=True)
DG = nx.DiGraph()
for edge in edges:
source = edge[2]['source']
target = edge[2]['target']
v = target-source-1
# A
if nodes[source][1]['song'] == 'a':
DG.add_node(source, color = 'red', song = 'a',
nearest = nodes[source][1]['nearest'],
dist = nodes[source][1]['dist'])
DG.add_edge(source, target)
# B
if nodes[source][1]['song'] == 'b':
DG.add_node(source, color = 'blue', song = 'b',
nearest = nodes[source][1]['nearest'],
dist = nodes[source][1]['dist'])
DG.add_edge(source, target)
A = nx.to_agraph(DG)
A.layout()
A.draw(name)
return DG
示例15: plot_graph
def plot_graph(self):
G = self.graph()
nstates = len(self.states)
path = nx.shortest_path(G, source=self.start, target=self.end)
tm, eigenvals = self.transition_matrix(end_links=True)
G1 = nx.to_agraph(G)
G1.graph_attr['label'] = str(self.totals) + \
' State Space\nNum. States = {}\n' \
'Shortest Path = {} steps\n2nd e.v. ' \
'of Transition Matrix = {}' \
.format(nstates, len(path)-1, np.round(eigenvals[1].real, 5))
for idx in xrange(len(path)-1):
edge = G1.get_edge(str(path[idx]), str(path[idx+1]))
edge.attr['color'] = 'red1'
start = G1.get_node(str(self.start))
start.attr['color'] = 'forestgreen'
start.attr['shape'] = 'box'
end = G1.get_node(str(self.end))
end.attr['color'] = 'red1'
end.attr['shape'] = 'box'
fileid = '-'.join([str(i) for i in self.totals]) + '.png'
G1.draw('./plots/state_spaces/' + fileid, prog='circo')