• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python networkx.to_agraph函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.to_agraph函数的典型用法代码示例。如果您正苦于以下问题:Python to_agraph函数的具体用法?Python to_agraph怎么用?Python to_agraph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了to_agraph函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:asa88,项目名称:Evaluation_of_Topic_Models,代码行数:31,代码来源:MineFeatures.py


示例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)
开发者ID:shuge,项目名称:linesman,代码行数:11,代码来源:__init__.py


示例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)
开发者ID:ScientistJeff,项目名称:pagekicker-community,代码行数:60,代码来源:PKgraph.py


示例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')
开发者ID:gmroldan,项目名称:universitary_advisor,代码行数:16,代码来源:asistente.py


示例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')
开发者ID:RaulMira0812,项目名称:IA-final-project,代码行数:7,代码来源:Graph.py


示例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
开发者ID:tsujamin,项目名称:digi-approval,代码行数:31,代码来源:views.py


示例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
开发者ID:skonina,项目名称:KTH_Java,代码行数:29,代码来源:graph.py


示例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)
开发者ID:CEPBEP,项目名称:neurokernel,代码行数:26,代码来源:plot.py


示例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
开发者ID:ryavorsky,项目名称:RPyAppl1,代码行数:31,代码来源:BuildGraphs_Test.py


示例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)
开发者ID:WenchaoLin,项目名称:goenrich,代码行数:33,代码来源:export.py


示例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')
开发者ID:heiko114514,项目名称:popupcad,代码行数:7,代码来源:design_file_connections.py


示例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")
开发者ID:ae14gotou,项目名称:tokuken2,代码行数:35,代码来源:network_Ant.py


示例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)
开发者ID:bsmith89,项目名称:seq-div,代码行数:30,代码来源:clean_makefile_graph.py


示例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
开发者ID:firebaugh,项目名称:partybot,代码行数:28,代码来源:earworm_support.py


示例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')
开发者ID:ddbourgin,项目名称:hobbit_orc,代码行数:27,代码来源:hobbit_orcs.py


示例16: graphviz_layout_with_rank

def graphviz_layout_with_rank(G, prog = "neato", root = None, sameRank = [], args = ""):
    ## See original import of pygraphviz in try-except block
    ## See original identification of root through command line
    try:
        import pygraphviz
    except ImportError:
        raise ImportError('requires pygraphviz ',
                          'http://networkx.lanl.gov/pygraphviz ',
                          '(not available for Python3)')
    if root is not None:
        args+="-Groot=%s"%root
    args+="-Eweight=10000"
    A = nx.to_agraph(G)
    for sameNodeHeight in sameRank:
        if type(sameNodeHeight) == str:
            print("node \"%s\" has no peers in its rank group" %sameNodeHeight)
        A.add_subgraph(sameNodeHeight, rank="same")
    A.layout(prog=prog, args=args)
    ## See original saving of each node location to node_pos
    node_pos={}
    for n in G:
        node=pygraphviz.Node(A,n)
        try:
            xx,yy=node.attr["pos"].split(',')
            node_pos[n]=(float(xx),float(yy))
        except:
            print("no position for node",n)
            node_pos[n]=(0.0,0.0)
    return node_pos
开发者ID:hongyi-zhang,项目名称:custom-mh,代码行数:29,代码来源:subsampled_mh.py


示例17: aGraphObject

def aGraphObject(G_in, types = [], color = 'black', layout = 'neato') :

    G0 = nx.DiGraph()

    for node in G_in.nodes() :
        lbl = G_in.node[node]['number']
        G0.add_node(node, number = lbl, fontsize = 32, fixedsize='true') # , shape='circle'
    
    for (u,v) in G_in.edges() :
        type = int(G_in[u][v]['type'])
        if  types.count(type) > 0:
            G0.add_edge(u,v, style = 'bold', color = color, minlen='3')

    G = nx.to_agraph(G0)
    G.graph_attr.update(splines='true', overlap='false', ratio='fill', size='21,21')

    for node in G.nodes() :
        size = 0.7 + 0.1*(G.in_degree(node))
        node.attr['width'] = size
        node.attr['height'] = size

    G = makeLayout(G, layout)

    for node in G.nodes() :
        node.attr['label'] = node.attr['number']
        if node.attr['number'] == '1' :
            node.attr['style'] = 'filled'
            node.attr['fillcolor'] = '#FFFAAA'

    return G
开发者ID:vlasova-evgeniya,项目名称:RPyAppl1,代码行数:30,代码来源:BuildGraphs.py


示例18: convert_graph

    def convert_graph(graph):
        """
        Convert graph to graphviz format.

        :param `DiGraph` graph: the graph
        :returns: a graphviz graph

        Designate its general layout and mark or rearrange nodes as appropriate.
        """
        dot_graph = networkx.to_agraph(graph) # pylint: disable=no-member
        dot_graph.graph_attr.update(rankdir="LR")
        dot_graph.layout(prog="dot")

        xformers = [
           _display.SpindleTransformer,
           _display.PartitionTransformer,
           _display.PartitionEdgeTransformer,
           _display.CongruenceEdgeTransformer,
           _display.EnclosureBayTransformer,
           _display.EnclosureTransformer,
           _display.AddedNodeTransformer,
           _display.RemovedNodeTransformer,
           _display.AddedEdgeTransformer,
           _display.RemovedEdgeTransformer
        ]

        _display.GraphTransformers.xform(dot_graph, xformers)
        return dot_graph
开发者ID:mulkieran,项目名称:juststorage,代码行数:28,代码来源:_graphs.py


示例19: draw

 def draw(self, name = None):
     if not name:
         name = "ast"
     name = "%s.png"%name
     A = nx.to_agraph(self.net)
     A.layout(prog = 'dot')
     print "drawing ..."
     A.draw(name)
开发者ID:xingzhong,项目名称:SSP-Analyzer,代码行数:8,代码来源:libgraph.py


示例20: drawNeato

def drawNeato(sim,media):
	# http://www.graphviz.org/pdf/neatoguide.pdf
	G = nx.from_numpy_matrix(sim)
	G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),media)))
	G = nx.to_agraph(G)
	G.node_attr.update(shape="plaintext",width=.5)
	G.graph_attr.update(splines=None,overlap="scale")
	G.draw('out.png', format='png', prog='neato',args='-Gepsilon=0.001')
开发者ID:oztalha,项目名称:MPP-TR,代码行数:8,代码来源:media2014.py



注:本文中的networkx.to_agraph函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.to_networkx_graph函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.subgraph函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap