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

Python networkx.draw函数代码示例

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

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



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

示例1: draw_difference

 def draw_difference(self, path_old, path_new):
     self.draw_path(path_old)
     H = self.G.copy()
     H.add_edges_from(path_edges(path_new.path))
     H_ = nx.difference(self.G, H)
     nx.draw(self.G, self.pos)
     nx.draw(H_, self.pos, edge_color='blue')
开发者ID:abrady,项目名称:discreteopt,代码行数:7,代码来源:solver.py


示例2: plot_neighbourhood

def plot_neighbourhood(ax,G,direction_colors={},node_color='white',alpha=0.8,labels=True,node_size=300,font_size=12):
    """
    Plots the Graph using networkx' draw method.
    Each edge should have an direction assigned to it; with the direction_colors 
    parameter you can assign different directions different colors for plotting.
    @param ax Axis-object.
    @param G Graph-object.
    @param direction_colors Dictionary with directions as keys and colors as values.
    """

    pos_dict={}

    for i in G.node:
        pos_dict[i]=np.array([G.node[i]['phi'],G.node[i]['theta']])


    edge_colors='black'

    if len(direction_colors.keys())>0:
        edge_colors=[]
        for edge_origin in G.edge.keys():
            for edge_target in G.edge[edge_origin].keys():
                if direction_colors.keys().count(G.edge[edge_origin][edge_target]['direction']):
                    edge_colors.append(direction_colors[G.edge[edge_origin][edge_target]['direction']])
                else:
                    edge_target.append('black')
                                


    nx.draw(G,pos_dict,ax,with_labels=labels,edge_color=edge_colors,node_color=node_color,alpha=alpha,node_size=node_size,font_size=font_size)
    
    return G
开发者ID:ilyasku,项目名称:CompoundPye,代码行数:32,代码来源:sensors.py


示例3: display_graph_by_specific_mac

    def display_graph_by_specific_mac(self, mac_address):

        G = nx.Graph()

        count = 0
        edges = set()
        edges_list = []


        for pkt in self.pcap_file:

            src = pkt[Dot11].addr1
            dst = pkt[Dot11].addr2

            if mac_address in [src, dst]:
                edges_list.append((src, dst))
                edges.add(src)
                edges.add(dst)

        plt.clf()
        plt.suptitle('Communicating with ' + str(mac_address), fontsize=14, fontweight='bold')
        plt.title("\n Number of Communicating Users: " + str(int(len(edges))))
        plt.rcParams.update({'font.size': 10})
        G.add_edges_from(edges_list)
        nx.draw(G, with_labels=True, node_color=MY_COLORS)
        plt.show()
开发者ID:yarongoldshtein,项目名称:Wifi_Parser,代码行数:26,代码来源:ex3.py


示例4: draw_graph

def draw_graph(G):
    pos = nx.spring_layout(G)
    
    nx.draw(G, pos)  # networkx draw()
    #P.draw()    # pylab draw()
    
    plt.show() # display
开发者ID:hiepbkhn,项目名称:itce2011,代码行数:7,代码来源:dual_simulation_matching.py


示例5: plot_graph

def plot_graph(graph, protein, Tc, nodecolor, nodesymbol):

    fig = plt.figure(figsize=(20,20))
    ax = fig.add_subplot(111)
    
    drawkwargs = {'font_size': 10,\
                  'linewidths': 1,\
                  'width': 2,\
                  'with_labels': True,\
                  'node_size': 700,\
                  'node_color':nodecolor,\
                  'node_shape':'o',\
                  'style':'solid',\
                  'alpha':1,\
                  'cmap': mpl.cm.jet}

    pos=nx.spring_layout(graph, iterations=200)
    nx.draw(graph, pos, **drawkwargs )

    if protein in Tc:
        string = "Protein: %i  Cancer"
        string_s = (protein)
        title=string%string_s
    else:
        string = "Protein: %i  Non-Cancer"
        string_s = (protein)
        title=string%string_s
    
    ax.set_title(title)
    filepath = 'images'+'/'+zeros(protein, padlength=4)+'.jpg'
    plt.savefig(filepath,  bbox_inches='tight')
    print 'Written to: '+filepath
    fig.clf()
    plt.close()
    del fig
开发者ID:iambernie,项目名称:ppi,代码行数:35,代码来源:plotting.py


示例6: plot_func

def plot_func(play, stats):
    generation = stats["generation"]
    best = stats["generation_best"]
    every = play.config["live_plot"].get("every", 100)

    if generation == 0:
        plt.figure(figsize=(10, 8))

    if (generation % every) == 0:
        plt.clf()

        # create graph
        graph = nx.DiGraph()
        traverse_tree(best.root, graph)
        labels = dict((n, d["label"]) for n, d in graph.nodes(data=True))

        pos = nx.graphviz_layout(graph, prog='dot')
        nx.draw(
            graph,
            pos,
            with_labels=True,
            labels=labels,
            arrows=False,
            node_shape=None
        )

        # plot graph
        plt.draw()
        plt.pause(0.0001)  # very important else plot won't be displayed
开发者ID:leizhang,项目名称:playground,代码行数:29,代码来源:classifier_evaluation.py


示例7: plot

def plot(graph, **kwargs):
    pos=kwargs.get('pos', nx.spring_layout(graph))
    if kwargs.get('draw_edge_labels', False): edge_labels=nx.draw_networkx_edge_labels(graph,pos)
    else: edge_labels=[]
    nx.draw(graph, pos, edge_labels=edge_labels, **kwargs)
#    plt.savefig('plot.pdf')
    plt.show()
开发者ID:Nishchita,项目名称:library,代码行数:7,代码来源:__init__.py


示例8: display

def display(g, title):
    """Displays a graph with the given title."""
    pos = nx.circular_layout(g)
    plt.figure()
    plt.title(title)
    nx.draw(g, pos)
    nx.draw_networkx_edge_labels(g, pos, font_size=20)
开发者ID:AbdealiJK,项目名称:scikit-image,代码行数:7,代码来源:plot_rag.py


示例9: add_switch

    def add_switch(self):
        """Add switches to the topology graph
        Extracts switches information stored in switch_list dictionary

        important fields:
        switch.dp.id """
        print('self.sw_list_body {}'.format(self.sw_list_body))
 


        
        for index,switch in enumerate( self.switch_list):
#            dpid = format_dpid_str(dpid_to_str(switch.dp.id))
            self.graph.add_node(switch.dp.id)
            dpid=switch.dp.id
  
 
#            dpid = hex2decimal(switch['ports']['dpid'])            
#            self.graph.add_node(switch['ports']['dpid'])
        
#            for node in switch["ports"]:
#                dpid = hex2decimal(node['dpid'])
#               self.graph.add_node(dpid)
        print(self.graph.nodes())
        nx.draw(self.graph)
        plt.show()
开发者ID:zubair1234,项目名称:Assignment,代码行数:26,代码来源:rr.py


示例10: plot_graph

def plot_graph(graph, ax=None, cmap='Spectral', **kwargs):
    """

    Parameters
    ----------
    graph : object
            A networkX or derived graph object

    ax : objext
         A MatPlotLib axes object

    cmap : str
           A MatPlotLib color map string. Default 'Spectral'

    Returns
    -------
    ax : object
         A MatPlotLib axes object. Either the argument passed in
         or a new object
    """
    if ax is None:
        ax = plt.gca()

    cmap = matplotlib.cm.get_cmap(cmap)

    # Setup edge color based on the health metric
    colors = []
    for s, d, e in graph.edges_iter(data=True):
        if hasattr(e, 'health'):
            colors.append(cmap(e.health)[0])
        else:
            colors.append(cmap(0)[0])

    nx.draw(graph, ax=ax, edge_color=colors)
    return ax
开发者ID:jlaura,项目名称:autocnet,代码行数:35,代码来源:graph_view.py


示例11: main

def main():
	base_layout = [("value", 32)]
	packed_layout = structuring.pack_layout(base_layout, pack_factor)
	rawbits_layout = [("value", 32*pack_factor)]
	
	source = SimActor(source_gen(), ("source", Source, base_layout))
	sink = SimActor(sink_gen(), ("sink", Sink, base_layout))
	
	# A tortuous way of passing integer tokens.
	packer = structuring.Pack(base_layout, pack_factor)
	to_raw = structuring.Cast(packed_layout, rawbits_layout)
	from_raw = structuring.Cast(rawbits_layout, packed_layout)
	unpacker = structuring.Unpack(pack_factor, base_layout)
	
	g = DataFlowGraph()
	g.add_connection(source, packer)
	g.add_connection(packer, to_raw)
	g.add_connection(to_raw, from_raw)
	g.add_connection(from_raw, unpacker)
	g.add_connection(unpacker, sink)
	comp = CompositeActor(g)
	reporter = perftools.DFGReporter(g)
	
	fragment = comp.get_fragment() + reporter.get_fragment()
	sim = Simulator(fragment, Runner())
	sim.run(1000)
	
	g_layout = nx.spectral_layout(g)
	nx.draw(g, g_layout)
	nx.draw_networkx_edge_labels(g, g_layout, reporter.get_edge_labels())
	plt.show()
开发者ID:Jwomers,项目名称:migen,代码行数:31,代码来源:structuring.py


示例12: draw_related_mashup

    def draw_related_mashup(self, mashups, current_mashup=None, highlight_mashup=None):
        """
        Draw the realated mashup graph
        """
        self.ax.clear()
        layout = {}
        g = nx.Graph()
        node_size = {}
        node_color = {}
        node_map = {}
        node_id = 0

        for mashup in mashups:
            if node_map.get(mashup["id"]) == None:
                node_map[mashup["id"]] = node_id
                g.add_node(node_id)
                node_size[node_id] = 20
                if current_mashup and mashup["id"] == current_mashup["id"]:
                    node_color[node_id] = 0.7
                    node_size[node_id] = 180
                    layout[node_id] = (random.random() , random.random())
                else:
                    node_color[node_id] = 0.5
                    layout[node_id] = (random.random() , random.random())
                node_id = node_id + 1
        for i in range(0, len(mashups)):
            node_id_start = node_map.get(mashups[i]["id"])
            node_id_end = node_map.get(current_mashup["id"])
            g.add_edge(node_id_start, node_id_end)
        try:
            nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False)
        except Exception, e:
            print e
开发者ID:CMUSV-VisTrails,项目名称:WorkflowRecommendation,代码行数:33,代码来源:networkx_graph.py


示例13: draw

    def draw(self):
        """
        Canvas for draw the relationship between apis
        """
        mashup_map = data_source.mashup_with_apis()
        layout = {}
        g = nx.Graph()

        node_size = {}
        node_color = {}
        node_map = {}
        node_id = 0
        for key in mashup_map:
            if len(mashup_map[key]) == 20:
                for api in mashup_map[key]:
                    if node_map.get(api) == None:
                        node_map[api] = node_id
                        g.add_node(node_id)
                        node_size[node_id] = 50
                        node_color[node_id] = 0.5
                        layout[node_id] = (random.random() , random.random())
                        node_id = node_id + 1
                for i in range(0, len(mashup_map[key])):
                    for j in range(0, len(mashup_map[key])):
                        node_id_start = node_map.get(mashup_map[key][i])
                        node_id_end = node_map.get(mashup_map[key][j])
                        g.add_edge(node_id_start, node_id_end)
                        node_size[node_id_start] = node_size[node_id_start] + 5
                        node_size[node_id_end] = node_size[node_id_end] + 5

        try:
            nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False)
        except Exception, e:
            print e
开发者ID:CMUSV-VisTrails,项目名称:WorkflowRecommendation,代码行数:34,代码来源:networkx_graph.py


示例14: draw

def draw(graph):
       pos = nx.graphviz_layout(graph, prog='sfdp', args='')
       list_nodes = graph.nodes()
       plt.figure(figsize=(20,10))
       nx.draw(graph, pos, node_size=20, alpha=0.4, nodelist=list_nodes, node_color="blue", with_labels=False)
       plt.savefig('graphNX.png')
       plt.show()
开发者ID:RafaelRemondes,项目名称:DistributedAggregationAlgorithmsSM,代码行数:7,代码来源:graphTest.py


示例15: show_graph_with_labels

def show_graph_with_labels(adjacency_matrix, mylabels):
    rows, cols = np.where(adjacency_matrix == 1)
    edges = zip(rows.tolist(), cols.tolist())
    gr = nx.Graph()
    gr.add_edges_from(edges)
    nx.draw(gr, node_size=2000, labels=mylabels, with_labels=True)
    plt.show()
开发者ID:zero0nee,项目名称:UnspscClassifier,代码行数:7,代码来源:Taxanomy+graph.py


示例16: state_change_handler

    def state_change_handler(self, ev):                                 ## to do add flow in switch enter hander and switch leave handler
         """Update topology graph when a switch enters or leaves.
         ev -- datapath event and all of it's fields

         important fields:
         ev.dp.id: dpid that is joining or leaving
         ev.enter is true if the datapath is entering and false if it is leaving
         """

         
         dp=ev.datapath
#         ports = ev.datapath.ports
         ofproto = dp.ofproto
         parser = dp.ofproto_parser   


                          
         assert dp is not None
         if dp.id is None:
            return
 

         if ev.state == MAIN_DISPATCHER:

            match = parser.OFPMatch()
            switch_list = []
            for i in self.dpid_to_switch:
               switch_list.append(i)

            self.deploy_flow_entry(dp,switch_list,match)

            if not self.graph.has_node(dp.id):
#             dpid = format_dpid_str(dpid_to_str(dp.id))
              self.graph.add_node(dp.id)
              thread.start_new(getPeriodicStats, (dp,))
              self.logger.info('Switch %s added to the topology', str(dp.id))
#             for port in ev.datapath.ports: 
#                  ports = []
#                  ports=dp.ports
#                  out_port = ports[port][0] 
#                  print out_port
#                  print 'fuck'
#                  actions =[]
#              actions = [parser.OFPActionOutput(out_port)]
#              self.add_flow( dp ,0 ,match , actions)
                   

         elif ev.state == DEAD_DISPATCHER:
            if dp.id is None:
                return
            if self.graph.has_node(dp.id):
              self.graph.remove_node(dp.id)
              self.logger.info('Switch %s removed from the topology',
                              str(dp.id))

         nx.draw(self.graph)
         plt.show()


         LOG.debug(dp)         
开发者ID:zubair1234,项目名称:Assignment,代码行数:60,代码来源:rr.py


示例17: plot_graph_3D

def plot_graph_3D(graph, I_shape, plot_terminal=True, plot_weights=True, font_size=7):
    w_h = I_shape[1] * I_shape[2]
    X, Y = np.mgrid[:I_shape[1], :I_shape[2]]
    aux = np.array([Y.ravel(), X[::-1].ravel()]).T
    positions = {i: aux[i] for i in xrange(w_h)}

    for i in xrange(1, I_shape[0]):
        for j in xrange(w_h):
            positions[w_h * i + j] = [positions[j][0] + 0.3 * i, positions[j][1] + 0.2 * i]

    positions['s'] = np.array([-1, int(I_shape[1] / 2)])
    positions['t'] = np.array([I_shape[2] + 0.2 * I_shape[0], int(I_shape[1] / 2)])

    nxg = graph.get_nx_graph()
    if not plot_terminal:
        nxg.remove_nodes_from(['s', 't'])

    nx.draw(nxg, pos=positions)
    nx.draw_networkx_labels(nxg, pos=positions)
    if plot_weights:
        edge_labels = dict([((u, v,), d['weight'])
                     for u, v, d in nxg.edges(data=True)])
        nx.draw_networkx_edge_labels(nxg, pos=positions, edge_labels=edge_labels, label_pos=0.3, font_size=font_size)
    plt.axis('equal')
    plt.show()
开发者ID:PNProductions,项目名称:PyMaxflow,代码行数:25,代码来源:examples_utils.py


示例18: draw_fault_scenario

def draw_fault_scenario(title, fault_edge, pp, dp, fwp):
    nx.draw(G, pos, node_size=300, font_size=10, node_color='w', alpha=1, with_labels=True)

    if title is not None:
        plt.text(0.5, 0.5, title, fontsize=12)

    if pp is not None:
        draw_edge_node(pp, 0.8, 'b')
        # Source
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[pp[0]],
                               node_color='black',
                               node_size=500,
                               label='S',
                               font_size=10,
                               node_shape='s',
                               alpha=0.5)
    # Detour path
    if dp is not None:
        draw_edge_node(dp, 0.8, 'g')

    # Fault edge
    if fault_edge is not None:
        nx.draw_networkx_edges(G, pos,
                               edgelist=[fault_edge],
                               width=4, alpha=0.8,
                               edge_color='r')
    # FW Back path
    if fwp is not None:
        draw_edge_node(fwp, 0.8, 'y', 'dashed')
开发者ID:chenleji,项目名称:ryu-1,代码行数:30,代码来源:f_t_parser_ff.py


示例19: print_pdf_graph

def print_pdf_graph(file_f, regulon, conn):
  pdf = PdfPages(file_f)
  edgesLimits = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
  #CRP = regulon_set['LexA']
  for lim in edgesLimits:
    print lim
    g = buildSimilarityGraph_top_10_v2(conn, lim)

    # Here the node is motif, eg 87878787_1, the first 8 digits represent gi
    node_color = [ 1 if node[0:8] in regulon else 0 for node in g ]

    pos = nx.graphviz_layout(g, prog="neato")
    plt.figure(figsize=(10.0, 10.0))
    plt.axis("off")
    nx.draw(g,
        pos,
        node_color = node_color,
        node_size = 20,
        alpha=0.8,
        with_labels=False,
        cmap=plt.cm.jet,
        vmax=1.0,
        vmin=0.0
        )
    pdf.savefig()
    plt.close()

  pdf.close()
开发者ID:Chuan-Zh,项目名称:footprint,代码行数:28,代码来源:regulon_cluster_by_top_edges.py


示例20: draw_molecule

def draw_molecule(molecule):
    # Create a new NetworkX graph
    g = nx.Graph()
    # For each vertex and edge in molecule graph add node and edge in NetworkX graph
    for n in molecule.vertices():
        g.add_node(molecule.position_of_vertex(n), element=n.label)
    for e in molecule.edges():
        if e.single:
            g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='single')
        elif e.double:
            g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='double')
        elif e.triple:
            g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='triple')
        elif e.quadruple:
            g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='quadruple')
        elif e.aromatic:
            g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='aromatic')

    # Set the layout
    pos = nx.spring_layout(g, iterations=30)
    # Display the element type and edge type as labels
    labels = dict((n,d['element']) for n,d in g.nodes(data=True))
    edge_labels = dict(((u,v),d['type']) for u,v,d in g.edges(data=True))
    # Add the labels to the graph
    nx.draw(g, pos=pos, node_color='w')
    nx.draw_networkx_labels(g, pos=pos, labels=labels)
    nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=edge_labels)
    # Display the completed graph
    plt.show()
    return g
开发者ID:MSMcDowall,项目名称:CharacteristicSubstructure,代码行数:30,代码来源:draw_molecule.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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