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

Python networkx.draw_networkx函数代码示例

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

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



在下文中一共展示了draw_networkx函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: initialize

def initialize():

    G.add_node("A")
    G.add_node("B")
    G.add_node("C")
    G.add_node("D")
    G.add_node("E")
    G.add_node("F")

    labels = {k: k for k in G.nodes()}

    G.add_edge("A", "F", weight=1)
    G.add_edge("A", "E", weight=3)
    G.add_edge("A", "C", weight=4)
    G.add_edge("F", "B", weight=3)
    G.add_edge("F", "E", weight=2)
    G.add_edge("B", "D", weight=3)
    G.add_edge("B", "E", weight=2)
    G.add_edge("E", "D", weight=4)
    G.add_edge("E", "C", weight=2)
    G.add_edge("C", "D", weight=1)

    labels = nx.get_edge_attributes(G, "weight")
    plt.title("Single-Router Network")
    nx.draw(G, pos=nx.spectral_layout(G))
    nx.draw_networkx(G, with_labels=True, pos=nx.spectral_layout(G))
    nx.draw_networkx_edge_labels(G, pos=nx.spectral_layout(G), edge_labels=labels)
    plt.show()
开发者ID:stillbreeze,项目名称:fake-routes,代码行数:28,代码来源:route.py


示例2: reactionCenter

def reactionCenter(filename):
	# in this method, g2 do not need to be subgraph of g1
	mcs = fmcsWithPath(filename=filename)
	# print(mcs['content1'])
	# print(mcs['content2'])
	# print(mcs['contentmcs'])

	# g1 = input_chem_content(mcs['content1'], 'g1')
	g1 = graphFromSDF(StringIO(mcs['content1']))[0]
	print g1.node
	# nx.draw_networkx(g1)
	# pyplot.show( )

	# g2 = input_chem_content( mcs['content2'], 'g2' )
	g2 = graphFromSDF( StringIO( mcs['content2'] ) )[0]
	print g2.node
	# nx.draw_networkx( g2)
	# pyplot.show( )

	# gmcs = input_chem_content(mcs['contentmcs'], 'g2')
	gmcs = graphFromSDF( StringIO( mcs['contentmcs'] ) )[0]
	nx.draw_networkx(gmcs)
	pyplot.show()

	print getReactionCenter(g1, gmcs)
开发者ID:fycisc,项目名称:ADS,代码行数:25,代码来源:generate_MCS.py


示例3: draw

def draw(inF):
    G = nx.Graph()

    inFile = open(inF)
    S = set()
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for item in fields:
            S.add(item)
    inFile.close()

    L = list(S)
    G.add_nodes_from(L)

    LC = []
    for x in L:
        if x == 'EGR1' or x == 'RBM20':
            LC.append('r')
        else:
            LC.append('w')

    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for i in range(len(fields)-1):
            G.add_edge(fields[i], fields[i+1])
    inFile.close()
    nx.draw_networkx(G,pos=nx.spring_layout(G), node_size=800, font_size=6, node_color=LC)
    limits=plt.axis('off')
    plt.savefig(inF + '.pdf')
开发者ID:chw333,项目名称:StanfordSGTC,代码行数:32,代码来源:03-network-draw.py


示例4: graph_show

def graph_show(graph, font_size=12):
    pylab.rcParams['figure.figsize'] = (16.0, 12.0)
    try:
        nx.draw_networkx(graph,pos=nx.spring_layout(graph), node_size=6, alpha=0.1, font_size=font_size)
    except:
        print 'umm'
    pylab.rcParams['figure.figsize'] = (10.0, 4.0)
开发者ID:catawbasam,项目名称:asias_fds_profiles,代码行数:7,代码来源:notebook_utils.py


示例5: draw_graph

    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
开发者ID:cjforman,项目名称:pele,代码行数:33,代码来源:molecule.py


示例6: create_simple_graph

    def create_simple_graph(self,name):
        import networkx as nx
        G=nx.Graph()
        for i,r in enumerate(self.reslist):
            G.add_node(i+1,name=r.name)
        print G.nodes()

        
        h = self.hbond_matrix()
        nr = numpy.size(h,0)
        for i in range(nr):
            for j in range(i+1,nr):
                if GenericResidue.touching(self.reslist[i], self.reslist[j],2.8):
                    print 'adding edge',i+1,j+1
                    G.add_edge(i+1,j+1,name="special")                     
 
#        pos0=nx.spectral_layout(G)
#        pos=nx.spring_layout(G,iterations=500,pos=pos0)

#        pos=nx.spring_layout(G,iterations=500)
        
#        nx.draw_shell(G)

        pos0=nx.spectral_layout(G)
        pos=nx.spring_layout(G,iterations=500,pos=pos0)
#        pos=nx.graphviz_layout(G,root=1,prog='dot')
#        nx.draw(G)
        nx.draw_networkx(G,pos)
                     
        plt.axis('off')
        plt.savefig(name)       
开发者ID:jeffhammond,项目名称:nwchem,代码行数:31,代码来源:my_system.py


示例7: observe

def observe():
    global initialConditions
    global g,estado,f,numNodos,numTipoNodos
    estado=[]
    contadorAgregado=[]
    cla()
    node_labels={}
    cmapMio=creaCmap(4)
    for i in g.nodes_iter():
        node_labels[i]=g.node[i]['tipo']    
    nx.draw_networkx (g, k=0.8,node_color = [g.node[i]['tipo'] for i in g.nodes_iter()],
            pos = g.pos,cmap=cmapMio, labels=node_labels)
    for i in g.nodes_iter():
        estado.append(g.node[i]['tipo'])
    contador=collections.Counter(estado)
    contadorAgregado=contador.values()
    wr.writerow(contadorAgregado)
    print contadorAgregado
    if initialConditions == 0:
        # Saving data used in simulation, using f of file defined in initialize()
        f.write('GRID de ')
        f.write(str(numNodos)+"\n y tipos de nodos: ")
        f.write(str(numTipoNodos)+"\n")
        f.write(str(contadorAgregado) +"\n")
        f.write('Matrix'+"\n")
        initialConditions=1       
        np.savetxt(f,betaMatrix, fmt='%.4e') 
        f.close()
开发者ID:falevian,项目名称:Bacterias-PrimerosPasos,代码行数:28,代码来源:00+Un+bacteria+contra+5+tres+estructura-grid-SinSimulador.py


示例8: draw_graph

def draw_graph(graph):

    # extract nodes from graph
    nodes = set([n1 for n1, n2 in graph] + [n2 for n1, n2 in graph])

    # create networkx graph
    G=nx.Graph()
    #G=nx.cubical_graph()

    # add nodes
    for node in nodes:
        G.add_node(node)

    # add edges
    for edge in graph:
        G.add_edge(edge[0], edge[1])

    # draw graph
    #pos = nx.shell_layout(G)
    #pos = nx.spectral_layout(G)
    pos = nx.random_layout(G) # Funciona melhor
    #pos = nx.circular_layout(G) # Mais ou menos
    #pos = nx.fruchterman_reingold_layout(G) # Funciona melhor

    #nx.draw(G, pos)
    nx.draw_networkx(G)

    # show graph
    plt.axis('off')
    plt.show()
开发者ID:AnaSLCaldeira,项目名称:EADW,代码行数:30,代码来源:graph_functions.py


示例9: draw_basic_network

def draw_basic_network(G,src_list):
  slpos = nx.spring_layout(G) # see this for a great grid layout [1]
  nx.draw_networkx(G, pos=slpos, node_color='b', nodelist=src_list, with_labels=False,node_size=20, \
                   edge_color='#7146CC')
  nx.draw_networkx_nodes(G, pos=slpos, node_color='r', nodelist=[x for x in G.nodes() if x not in src_list], \
                         alpha=0.8, with_labels=False,node_size=20)
  plt.savefig('figures/basicfig', bbox_inches='tight', pad_inches=0)
开发者ID:abitofalchemy,项目名称:ScientificImpactPrediction,代码行数:7,代码来源:procjson_tograph.py


示例10: draw

 def draw(self):
     """
     Draw a network graph of the employee relationship.
     """
     if self.graph is not None:
         nx.draw_networkx(self.graph)
         plt.show()
开发者ID:gcallah,项目名称:Indra,代码行数:7,代码来源:emp_model.py


示例11: tree_width

def tree_width(nxg,i):
	maxsize=1000000000
	junction_tree=nx.Graph()
	max_junction_tree_node=junction_tree
	all_subgraphs=create_all_subgraphs(nxg.edges(),i)
	print "All subgraphs:",all_subgraphs
	print "============================================"
	for k0 in all_subgraphs:
		for k1 in all_subgraphs:
			hash_graph_k0 = hash_graph(k0)
			hash_graph_k1 = hash_graph(k1)
			if (hash_graph_k0 != hash_graph_k1) and len(set(k0).intersection(set(k1))) > 0:
				junction_tree.add_edge(hash_graph_k0,hash_graph_k1)
				if len(k0) < maxsize:
					max_junction_tree_node=k0
					maxsize = len(k0)
				if len(k1) < maxsize:
					max_junction_tree_node=k1
					maxsize = len(k1)
	print "============================================"
	print "Junction Tree (with subgraphs of size less than",i,") :"
	nx.draw_networkx(junction_tree)
	plt.show()
	print "============================================"
	print "Junction Tree Width for subgraphs of size less than ",i," - size of largest node set:",maxsize
开发者ID:shrinivaasanka,项目名称:asfer-github-code,代码行数:25,代码来源:TreeWidth.py


示例12: create_networkx

def create_networkx(node_list, edge_list, args):
    graph = nx.Graph()
    print 'Initializing'
    size_list = []
    clean_node_list = []
    for item in node_list:
        nodesize = 300
        for edge in edge_list:
            if item == edge[1]:
                nodesize += 100
        size_list.append(nodesize)
        clean_node_list.append(os.path.basename(item))
    graph.add_nodes_from(clean_node_list)
    print 'Nodes set'
    for item in edge_list:
        from_node = os.path.basename(item[1])
        to_node = os.path.basename(item[0])
        graph.add_edge(from_node, to_node)
    print 'Edges set'
    print 'Creating Graph'
    position = nx.spring_layout(graph)
    for item in position:
        position[item] *= 10
    nx.draw_networkx(graph,
                     pos=position,
                     font_size=10,
                     node_size=size_list)
    print 'Drawing Graph'
    plt.show()
    print 'DONE'
开发者ID:willzfarmer,项目名称:datagraph,代码行数:30,代码来源:graph.py


示例13: plot_osm_network

def plot_osm_network(G,node_size=10,with_labels=False,ax=None):
    plt.figure()
    pos = {}
    for n in G.nodes():
        pos[n] = (G.node[n].lon, G.node[n].lat)
    nx.draw_networkx(G,pos,node_size=node_size,with_labels=with_labels,ax=ax)
    plt.show()
开发者ID:ikivimak,项目名称:RSP-betweenness,代码行数:7,代码来源:osm2nx.py


示例14: draw_geograph

def draw_geograph(g, node_color='r', edge_color='b', node_label_field=None,
                  edge_label_field=None, node_size=200, node_label_x_offset=0, 
                  node_label_y_offset=0, node_label_font_size=12, 
                  node_label_font_color='k'):
    """
    Simple function to draw a geograph via matplotlib/networkx
    Uses geograph coords (projects if needed) as node positions
    """

    # transform to projected if not done so
    flat_coords = g.transform_coords(gm.PROJ4_FLAT_EARTH)

    node_pos = {nd: flat_coords[nd] for nd in g.nodes()}
    label_pos = {nd: [flat_coords[nd][0] + node_label_x_offset, 
                      flat_coords[nd][1] + node_label_y_offset] 
                      for nd in g.nodes()}

    # Draw nodes
    nx.draw_networkx(g, pos=node_pos, node_color=node_color,
        with_labels=False, edge_color=edge_color, node_size=node_size)

    if node_label_field:
        if node_label_field != 'ix':
            label_vals = nx.get_node_attributes(g, node_label_field)
            nx.draw_networkx_labels(g, label_pos, labels=label_vals, 
                font_size=node_label_font_size, font_color=node_label_font_color)

        else: # label via ids
            nx.draw_networkx_labels(g, label_pos, labels=g.nodes(), 
                font_size=node_label_font_size, font_color=node_label_font_color)

    # handle edge labels if needed
    if edge_label_field:
        edge_labels = nx.get_edge_attributes(g, edge_label_field)
        nx.draw_networkx_edge_labels(g, pos=node_pos, edge_labels=edge_labels)
开发者ID:SEL-Columbia,项目名称:networker,代码行数:35,代码来源:utils.py


示例15: drawgraph

    def drawgraph(self,path,nodelist):
        color = {}
        graph = nx.Graph()
        for item in nodelist:
            graph.add_node(item.key.decode('utf-8'))
            if item.key in path.split('->'):
                color[item.key.decode('utf-8')] = 'green'

        for item in nodelist:
            if item.path == '':
                continue
            s = item.path.split('->')
            for i in range(0,len(s) - 1):
                if i == 0:
                    continue
                graph.add_edge(s[i].decode('utf-8'),s[i+1].decode('utf-8'))
        values = [color.get(node,'red') for node in graph.nodes() ]
        pos = nx.spring_layout(graph)
        if len(nodelist) > 500:
            nx.draw_networkx(graph,font_family='SimHei', node_size=50,node_color=values, font_size = 5)
        else:
            nx.draw_networkx(graph,font_family='SimHei', node_size=1000,node_color=values, font_size = 10)
        plt.savefig('HSearch.png')
        plt.close()
        return None
开发者ID:laosiaudi,项目名称:Wiki-search,代码行数:25,代码来源:heuristic_search.py


示例16: main

def main():

    G_igraph, G_nx, nodes_vector = generate_data()

    aca0, aca1 = separate_data_by_academy(nodes_vector, G_nx)

    print aca0.nodes()
    print aca1.nodes()

    plt.subplot(121)
    nx.draw_networkx(
        G=aca0,
        pos=nx.spring_layout(aca0),
        with_labels=True,
        node_color='g',
        edge_color='b',
        alpha=1)

    plt.axis('off')

    plt.subplot(122)
    nx.draw_networkx(
        G=aca1,
        pos=nx.spring_layout(aca1),
        with_labels=True,
        node_color='g',
        edge_color='b',
        alpha=1)

    plt.axis('off')
    plt.show()
开发者ID:NSSimacer,项目名称:SNA,代码行数:31,代码来源:DataProcess.py


示例17: plot

	def plot(self,figure):		
		changed	= False
		for ip in self.stats:
			if ip is not "127.0.0.1" and not self.graph.has_node(ip):
				self.graph.add_node(ip,node_size=4000,node_shape="s")
				self.graph.add_edge(ip,"127.0.0.1",attr_dict={"label":"N/A"})
				changed = True
			for port in self.stats[ip]:
				#pnode = ip + ":" + port
				pnode = port
				if not self.graph.has_node(pnode):
					statName = ip + ":" + port
					self.graph.add_node(pnode,attr_dict={"node_size":700,"node_shape":"o","font_size":8})
					self.graph.add_edge(pnode ,ip, attr_dict={"label":"N/A"})
					changed = True
		if changed:
			figure.clf()
			pos = nx.spring_layout(self.graph, weight=None, iterations=100, scale = 2)
			#draw ip nodes
			ipNodeList = list(self.stats)
			#print(ipNodeList)
			try:
				nx.draw_networkx(self.graph, 
							nodelist = ipNodeList, 
							pos = pos, 
							with_labels = True,
							node_size = 4000 , 
							node_shape = "p", 
							font_size = 8
						)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			#draw port nodes
			portList = list(self.stats.values())
			portNodesList = [ item for sublist in (list(e) for e in portList) for item in sublist ]
			try:
				nx.draw_networkx_nodes(self.graph, 
							nodelist = portNodesList, 
							pos = pos ,
							with_labels = True,
							node_size = 700 , 
							node_shape = "o", 
							font_size=8
						)
				edges = self.graph.edges(data=True)
				labels = {}
				for (a, b, *c) in edges:
					stats = "N/A"
					if a in self.stats:
						if b in self.stats[a]:
							labels[a,b] = self.stats[a][b]
					else:
						if a in self.stats[b]:
							labels[b,a] = self.stats[b][a]
				nx.draw_networkx_edge_labels(self.graph, pos = pos, edge_labels=labels,ax=None)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			# draw connStats
			statNodesList = list(self.statNodes)
			figure.canvas.draw()
开发者ID:psychophoniac,项目名称:staplab,代码行数:60,代码来源:stapLabModuleIPconnGraph.py


示例18: doGraph

 def doGraph(self,G,labels):
     pos = Plotter.hierarchical_layout(G)
     xs = map(lambda x:pos[x][0],pos)
     ys = map(lambda x:pos[x][0],pos)
     P.axis([min(xs)-0.1,
             max(xs)+0.1,
             min(ys)-0.1,
             max(ys)+0.1])
     P.subplots_adjust(left=0,
                       right=1,
                       bottom=0,
                       top=0.9)
         
     NX.draw_networkx(G, pos, font_size=8, labels=labels, edge_color='g')
     if labels:
         for (a,b,c) in G.edges():
             # the shorter line, the closer to lower node
             ax,ay=pos[a]
             bx,by=pos[b]
             l = ((ax-bx)**2+(ay-by)**2)**0.5
             ra = 1/(l+1)
             rb = l/(l+1)
             x=(ra*ax+rb*bx)
             y=(ra*ay+rb*by)
             P.text(x,y,c.type,
                    size=8,
                    horizontalalignment='center',
                    verticalalignment='center',
                    multialignment='left')
开发者ID:jbjorne,项目名称:CVSTransferTest,代码行数:29,代码来源:plotter.py


示例19: laucher

def laucher(graph, mininet_config, draw_mpl=False, write_gexf=False):
    """
    Launch the miniCPS SWaT simulation

    :graph: networkx graph
    :mininet_config: function pointer to the mininet configuration
    :draw_mpl: flag to draw and save the graph using matplotlib
    """

    # TODO: use different color for plcs, switch and attacker
    if draw_mpl:
        nx.draw_networkx(graph)
        plt.axis('off')
        # plt.show()
        plt.savefig("examples/swat/%s.pdf" % graph.name)

    if write_gexf:
        g_gexf = nx.write_gexf(graph, "examples/swat/l1_gexf.xml")
        # g2 = nx.read_gexf("examples/swat/g_gexf.xml")

    # Build miniCPS topo
    topo = TopoFromNxGraph(graph)
    controller = POXSwat
    net = Mininet(
        topo=topo,
        controller=controller,
        link=TCLink,
        listenPort=6634)

    mininet_config(net)
开发者ID:LubuntuFu,项目名称:minicps,代码行数:30,代码来源:run.py


示例20: savefig

    def savefig(col):
        global idx
        pylab.clf()
        #from pcd.support.matplotlibutil import get_axes, save_axes
        #ax, extra = get_axes('/home/darstr1/proj/tmp-img/%05d.png'%0)
        #print ax
        nx.draw_networkx(g, pos=pos,
                         node_list=g.nodes(),
                         node_color=[col[n] for n in g.nodes()],
                         with_labels=False)
        #save_axes(ax, extra)

        fig = pylab.gcf()
        ax = pylab.gca()
        dpi = fig.dpi
        bbox = ax.collections[0].get_window_extent(fig)
        from matplotlib.transforms import TransformedBbox, Affine2D
        bbox2 = TransformedBbox(bbox, Affine2D().scale(1. / dpi))
        bbox._points[0] -= .15 * dpi
        bbox._points[1] += .15 * dpi

        ax = pylab.gca()
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        pylab.savefig('/home/darstr1/proj/tmp-imgs/%05d.png'%idx,
                      bbox_inches=bbox2)
        idx += 1
开发者ID:rkdarst,项目名称:pcd,代码行数:27,代码来源:lfm.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python networkx.draw_networkx_edge_labels函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.draw_graphviz函数代码示例发布时间: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