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

Python networkx.draw_networkx_nodes函数代码示例

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

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



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

示例1: 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


示例2: plot

    def plot(self):
        """
        Plots an entity relation diagram (ERD) among all nodes that is part
        of the current graph.
        """
        if not self.nodes(): # There is nothing to plot
            logger.warning('Nothing to plot')
            return
        if pygraphviz_layout is None:
            logger.warning('Failed to load Pygraphviz - plotting not supported at this time')
            return

        pos = pygraphviz_layout(self, prog='dot')
        fig = plt.figure(figsize=[10, 7])
        ax = fig.add_subplot(111)
        nx.draw_networkx_nodes(self, pos, node_size=200, node_color='g')
        text_dict = nx.draw_networkx_labels(self, pos, self.node_labels)
        trans = ax.transData + \
            transforms.ScaledTranslation(12/72, 0, fig.dpi_scale_trans)
        for text in text_dict.values():
            text.set_horizontalalignment('left')
            text.set_transform(trans)
        # draw primary key relations
        nx.draw_networkx_edges(self, pos, self.pk_edges, arrows=False)
        # draw non-primary key relations
        nx.draw_networkx_edges(self, pos, self.non_pk_edges, style='dashed', arrows=False)
        apos = np.array(list(pos.values()))
        xmax = apos[:, 0].max() + 200  # TODO: use something more sensible than hard fixed number
        xmin = apos[:, 0].min() - 100
        ax.set_xlim(xmin, xmax)
        ax.axis('off')  # hide axis
开发者ID:modeSolver300,项目名称:datajoint-python,代码行数:31,代码来源:erd.py


示例3: test_labels_and_colors

 def test_labels_and_colors(self):
     G = nx.cubical_graph()
     pos = nx.spring_layout(G)  # positions for all nodes
     # nodes
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[0, 1, 2, 3],
                            node_color='r',
                            node_size=500,
                            alpha=0.8)
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[4, 5, 6, 7],
                            node_color='b',
                            node_size=500,
                            alpha=0.8)
     # edges
     nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
                            width=8, alpha=0.5, edge_color='r')
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
                            width=8, alpha=0.5, edge_color='b')
     # some math labels
     labels = {}
     labels[0] = r'$a$'
     labels[1] = r'$b$'
     labels[2] = r'$c$'
     labels[3] = r'$d$'
     labels[4] = r'$\alpha$'
     labels[5] = r'$\beta$'
     labels[6] = r'$\gamma$'
     labels[7] = r'$\delta$'
     nx.draw_networkx_labels(G, pos, labels, font_size=16)
     plt.show()
开发者ID:ProgVal,项目名称:networkx,代码行数:34,代码来源:test_pylab.py


示例4: calcMetrics

def calcMetrics():
    print('\nTrips:')
    for trip in trips:
        trip.display()
    print('\nPairs:')
    for a, b in itertools.combinations(trips, 2):
        # if isTimeTestFail(): continue
        bestDist = getBestDist(a, b)
        sumDist = a.dist + b.dist
        if bestDist > sumDist: continue
        minDist = min(a.dist, b.dist)
        maxDist = max(a.dist, b.dist)
        delta = sumDist - bestDist
        coPathCoeff = maxDist / bestDist
        effect = delta / bestDist
        weight = effect * coPathCoeff
        G.add_edge(a, b, weight=weight)
        print('edge is added', weight)

    pos = nx.random_layout(G)
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_edges(G, pos, width=weight,)
    plt.axis('off')
    plt.savefig("weighted_graph.png")  # save as png
    plt.show()  # display
开发者ID:LukeSkypewalker,项目名称:Python,代码行数:25,代码来源:metrica.py


示例5: display_retweet_network

def display_retweet_network(network, outfile=None, show=False):
    """
    Take a DiGraph (retweet network?) and display+/save it to file.
    Nodes must have a 'color' property, represented literally and indicating their type
    Edges must have a 'weight' property, represented as edge width
    """
    import networkx as nx
    import matplotlib.pyplot as plt

    # Create a color list corresponding to nodes.
    node_colors = [ n[1]["color"] for n in network.nodes(data=True) ]

    # Get edge weights from graph
    edge_weights = [ e[2]["weight"] for e in network.edges(data=True) ]

    # Build up graph figure
    #pos = nx.random_layout(network)
    pos = nx.spring_layout(network)
    nx.draw_networkx_edges(network, pos, alpha=0.3 , width=edge_weights, edge_color='m')
    nx.draw_networkx_nodes(network, pos, node_size=400, node_color=node_colors, alpha=0.4)
    nx.draw_networkx_labels(network, pos, fontsize=6)

    plt.title("Retweet Network", { 'fontsize': 12 })
    plt.axis('off')

    if outfile:
        print "Saving network to file: {0}".format(outfile)
        plt.savefig(outfile)

    if show:
        print "Displaying graph. Close graph window to resume python execution"
        plt.show()
开发者ID:SMAPPNYU,项目名称:ProgrammerGroup,代码行数:32,代码来源:network_util.py


示例6: draw

  def draw(self, layout_type='spring_layout'):
      '''
      Draw the graph
      
      layout_type = The type of layout algorithm (Default = 'spring_layout')
      '''
  
      import matplotlib.pyplot as plt
      
      try:
          pos = getattr(nx, layout_type)(self.G)
      except:
          raise Exception('layout_type of %s is not valid' % layout_type)
 
  
      nx.draw_networkx_nodes(self.G,pos,
                             nodelist=self.species,
                             node_color=self.options['species']['color'],
                             node_size=self.options['species']['size'],
                             alpha=self.options['species']['alpha'])
      nx.draw_networkx_edges(self.G, pos, edgelist=self.product_edges)
      nx.draw_networkx_edges(self.G, pos, edgelist=self.reactant_edges, arrows=False)
      nx.draw_networkx_edges(self.G, pos, edgelist=self.modifier_edges, style='dashed')
      
      labels = {}
      for n in self.G.nodes():
          if n in self.species:
              labels[n] = n
      nx.draw_networkx_labels(self.G,pos,labels,font_size=self.options['species']['label_size'])
      plt.axis('off')
      plt.show()
开发者ID:stanleygu,项目名称:ipython-notebook-tools,代码行数:31,代码来源:_graph.py


示例7: plotsolution

def plotsolution(numnodes,coordinates,routes):
   plt.ion() # interactive mode on
   G=nx.Graph()
   
   nodes = range(1,numnodes+1)
   nodedict = {}
   for i in nodes:
     nodedict[i] = i
   
   nodecolorlist = ['b' for i in nodes]
   nodecolorlist[0] = 'r'
     
   # nodes  
   nx.draw_networkx_nodes(G, coordinates, node_color=nodecolorlist, nodelist=nodes)
   # labels
   nx.draw_networkx_labels(G,coordinates,font_size=9,font_family='sans-serif',labels = nodedict)
   
   edgelist = defaultdict(list)
   
   colors = ['Navy','PaleVioletRed','Yellow','Darkorange','Chartreuse','CadetBlue','Tomato','Turquoise','Teal','Violet','Silver','LightSeaGreen','DeepPink', 'FireBrick','Blue','Green']
   
   for i in (routes):
     edge1 = 1
     for j in routes[i][1:]:
       edge2 = j
       edgelist[i].append((edge1,edge2))
       edge1 = edge2
       nx.draw_networkx_edges(G,coordinates,edgelist=edgelist[i],
                        width=6,alpha=0.5,edge_color=colors[i]) #,style='dashed'
   
   plt.savefig("path.png")

   plt.show()
开发者ID:adity,项目名称:Vehicle-Routing,代码行数:33,代码来源:plotsolution.py


示例8: draw_graph

def draw_graph(edges, up_words, down_words, node_size, node_color='blue', node_alpha=0.3,
               node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=2,
               text_font='sans-serif', file_name="graph"):
    plt.clf()
    g = nx.Graph()

    for edge in edges:
        g.add_edge(edge[0], edge[1])

    graph_pos = nx.shell_layout(g)  # layout for the network

    # up_words = map(lambda x: translate_node(x), up_words)
    # down_words = map(lambda x: x + "(" + translate_node(x) + ")", down_words)  # add translated nodes to graph

    try:
        nx.draw_networkx_nodes(g, graph_pos, nodelist=up_words, node_size=node_size,
                               alpha=node_alpha, node_color='red')
        nx.draw_networkx_nodes(g, graph_pos, nodelist=down_words, node_size=node_size,
                               alpha=node_alpha, node_color=node_color)
        nx.draw_networkx_edges(g, graph_pos, width=edge_tickness,
                               alpha=edge_alpha, edge_color=edge_color)
        nx.draw_networkx_labels(g, graph_pos, font_size=node_text_size,
                                font_family=text_font)
    except:
        print 'draw error'

    plt.savefig(result_path + file_name, format="PNG")
开发者ID:runninghack,项目名称:draw_detected_graph,代码行数:27,代码来源:plot_single.py


示例9: plot

    def plot(self, show_labels=False):
        nodes = nx.draw_networkx_nodes(self,
                                       self.pos,
                                       node_size=NODE_SIZE_NORMAL,
                                       node_color=NODE_COLOR_NORMAL,
                                       linewidths=NODE_LINEWIDTH_NORMAL,
                                       alpha=NODE_ALPHA_NORMAL)
        if nodes != None:
            nodes.set_edgecolor(NODE_BORDER_COLOR_NORMAL)
        ws = nx.get_node_attributes(self, 'w')
        sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE
                 for v in self.photo_nodes()]
        nodes = nx.draw_networkx_nodes(self,
                                       self.pos,
                                       nodelist=self.photo_nodes(),
                                       node_shape=NODE_SHAPE_PHOTO,
                                       node_size=sizes,
                                       node_color=NODE_COLOR_PHOTO)

        if nodes != None:
            nodes.set_edgecolor(NODE_BORDER_COLOR_PHOTO)
        if show_labels:
            nx.draw_networkx_labels(self,
                                    self.pos,
                                    font_color=LABEL_COLOR_NORMAL,
                                    font_size=LABEL_FONT_SIZE_NORMAL)
        nx.draw_networkx_edges(self,
                               self.pos,
                               width=EDGE_WIDTH_NORMAL,
                               edge_color=EDGE_COLOR_NORMAL,
                               alpha=EDGE_ALPHA_NORMAL)
开发者ID:3lectrologos,项目名称:pyor,代码行数:31,代码来源:util.py


示例10: plot_co_x

def plot_co_x(cox, start, end, size = (20,20), title = '', weighted=False, weight_threshold=10):

        """ Plotting function for keyword graphs

        Parameters
        --------------------
        cox: the coword networkx graph; assumes that nodes have attribute 'topic'
        start: start year
        end: end year
        """

        plt.figure(figsize=size)
        plt.title(title +' %s - %s'%(start,end), fontsize=18)
        if weighted:
            elarge=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] >weight_threshold]
            esmall=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] <=weight_threshold]
            pos=nx.graphviz_layout(cox) # positions for all nodes
            nx.draw_networkx_nodes(cox,pos,
                node_color= [s*4500 for s in nx.eigenvector_centrality(cox).values()],
                node_size = [s*6+20  for s in nx.degree(cox).values()],
                alpha=0.7)
            # edges
            nx.draw_networkx_edges(cox,pos,edgelist=elarge,
                                width=1, alpha=0.5, edge_color='black') #, edge_cmap=plt.cm.Blues
            nx.draw_networkx_edges(cox,pos,edgelist=esmall,
                                width=0.3,alpha=0.5,edge_color='yellow',style='dotted')
            # labels
            nx.draw_networkx_labels(cox,pos,font_size=10,font_family='sans-serif')
            plt.axis('off')
        else:
            nx.draw_graphviz(cox, with_labels=True,
                         alpha = 0.8, width=0.1,
                         fontsize=9,
                         node_color = [s*4 for s in nx.eigenvector_centrality(cox).values()],
                         node_size = [s*6+20 for s in nx.degree(cox).values()])
开发者ID:datapractice,项目名称:machinelearning,代码行数:35,代码来源:net_lit_anal.py


示例11: report_ctg

def report_ctg(ctg, filename):
    """
    Reports Clustered Task Graph in the Console and draws CTG in file
    :param ctg: clustered task graph
    :param filename: drawing file name
    :return: None
    """
    print "==========================================="
    print "      REPORTING CLUSTERED TASK GRAPH"
    print "==========================================="
    cluster_task_list_dict = {}
    cluster_weight_dict = {}
    for node in ctg.nodes():
        print ("\tCLUSTER #: "+str(node)+"\tTASKS:"+str(ctg.node[node]['TaskList'])+"\tUTILIZATION: " +
               str(ctg.node[node]['Utilization']))
        cluster_task_list_dict[node] = ctg.node[node]['TaskList']
    for edge in ctg.edges():
        print ("\tEDGE #: "+str(edge)+"\tWEIGHT: "+str(ctg.edge[edge[0]][edge[1]]['Weight']))
        cluster_weight_dict[edge] = ctg.edge[edge[0]][edge[1]]['Weight']
    print ("PREPARING GRAPH DRAWINGS...")
    pos = networkx.shell_layout(ctg)
    networkx.draw_networkx_nodes(ctg, pos, node_size=2200, node_color='#FAA5A5')
    networkx.draw_networkx_edges(ctg, pos)
    networkx.draw_networkx_edge_labels(ctg, pos, edge_labels=cluster_weight_dict)
    networkx.draw_networkx_labels(ctg, pos, labels=cluster_task_list_dict)
    plt.savefig("GraphDrawings/"+filename)
    plt.clf()
    print ("\033[35m* VIZ::\033[0mGRAPH DRAWINGS DONE, CHECK \"GraphDrawings/"+filename+"\"")
    return None
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:29,代码来源:Clustering_Reports.py


示例12: draw_graph

def draw_graph(G):
	# an example using Graph as a weighted network.
	# __author__ = """Aric Hagberg ([email protected])"""
	try:
	    import matplotlib.pyplot as plt
	except:
	    raise

	elarge = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] > 0.5]
	esmall = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] <= 0.5]

	pos = nx.spring_layout(G) # positions for all nodes

	# nodes
	nx.draw_networkx_nodes(G, pos, node_size = 200)

	# edges
	nx.draw_networkx_edges(G, pos, edgelist = elarge, width = 0.4)
	nx.draw_networkx_edges(G, pos, edgelist = esmall, width = 0.4, alpha = 0.6, style = 'dashed')

	# labels
	nx.draw_networkx_labels(G, pos, font_size = 6, font_family = 'sans-serif')

	print 'number of cliques/clusters:', nx.graph_number_of_cliques(G)
	print 'time:', time.time() - start
	plt.show()
开发者ID:danielgribel,项目名称:clustering,代码行数:26,代码来源:grasp.py


示例13: drawgraph

def drawgraph(graph,fixed):
	pos=nx.spring_layout(graph)
	nx.draw_networkx_nodes(graph,pos,with_labels=True,node_size=100)
	nx.draw_networkx_nodes(graph,pos,with_labels=True,nodelist=fixed,node_size=100,node_color="yellow")
	nx.draw_networkx_edges(graph,pos,with_labels=True,width=0.3)
	nx.draw_networkx_labels(graph,pos,fontsize=10)
	plt.show()
开发者ID:girolamogiudice,项目名称:nbea,代码行数:7,代码来源:filterlib6.py


示例14: visualize_rbn

def visualize_rbn(rbn):
    internal_edges = []
    for i, neighbors in enumerate(rbn.connections):
        internal_edges += zip(repeat(i), neighbors)

    input_edges = zip(repeat('input_node'), rbn.input_connections)

    print input_edges
    print internal_edges

    G = nx.MultiGraph()
    pos = nx.spring_layout(G)

    #G.add_edges_from(internal_edges, node_color='r', node_size=10)
    #G.add_edges_from(input_edges, node_color='b', node_size=3)

    nx.draw_networkx_nodes(G, pos,
                           nodelist=range(rbn.n_nodes),
                           node_color='b',
                           node_size=500,
                           alpha=0.8)

    nx.draw_networkx_edges(G, pos,
                           edgelist=internal_edges)
                           #width=3,
                           #edge_color='r')

#nx.draw_networkx_edges(G,pos,
            #edgelist=[(0,1),(1,2),(2,3),(3,0)],
            #width=8,alpha=0.5,edge_color='r')
    #nx.draw(G, pos)

    plt.show()
开发者ID:aleksanb,项目名称:RBN-Reservoir-Code,代码行数:33,代码来源:visualize_rbn.py


示例15: plot_networkx_topology_graph

def plot_networkx_topology_graph(topology):
    import matplotlib.pyplot as plt
    import networkx as nx

    G = nx.Graph()
    top_graph = topology.get_graph()
    labels = {}
    types = {}
    n_types = 0
    colors = []
    for v in top_graph.get_vertices():
        G.add_node(v.particle_index)
        labels[v.particle_index] = v.label
        if not v.particle_type() in types:
            types[v.particle_type()] = n_types
            n_types += 1
        colors.append(types[v.particle_type()])
    for v in top_graph.get_vertices():
        for vv in v:
            G.add_edge(v.particle_index, vv.get().particle_index)

    pos = nx.spring_layout(G)  # positions for all nodes

    nx.draw_networkx_nodes(G, pos, node_size=700, node_color=colors, cmap=plt.cm.summer)
    nx.draw_networkx_edges(G, pos, width=3)
    nx.draw_networkx_labels(G, pos, font_size=20, labels=labels, font_family='sans-serif')
    plt.show()
开发者ID:readdy,项目名称:readdy,代码行数:27,代码来源:topology_utils.py


示例16: plot_path

 def plot_path(self, path):
     if path == None:
         edgelist = []
     else:
         edgelist = zip(path[:-1], path[1:])
     if edgelist == []:
         return
     nodes = nx.draw_networkx_nodes(self,
                                    self.pos,
                                    nodelist=path,
                                    node_size=NODE_SIZE_PATH,
                                    node_color=NODE_COLOR_PATH)
     if nodes != None:
         nodes.set_edgecolor(NODE_BORDER_COLOR_PATH)
     ws = nx.get_node_attributes(self, 'w')
     photo_path_nodes = self.photo_nodes(path)
     if photo_path_nodes != []:
         sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE
                  for v in photo_path_nodes]
         nodes = nx.draw_networkx_nodes(self,
                                        self.pos,
                                        nodelist=photo_path_nodes,
                                        node_shape=NODE_SHAPE_PHOTO,
                                        node_size=sizes,
                                        node_color=NODE_COLOR_PHOTO_PATH)
     if nodes != None:
         nodes.set_edgecolor(NODE_BORDER_COLOR_PATH)
     nx.draw_networkx_edges(self,
                            self.pos,
                            edgelist=edgelist,
                            width=EDGE_WIDTH_PATH,
                            edge_color=EDGE_COLOR_PATH)
开发者ID:3lectrologos,项目名称:pyor,代码行数:32,代码来源:util.py


示例17: draw_graphs

def draw_graphs(G,edge_pro_dict,Gmp,Ggp,Gadr,Gabm):
  plt.figure(1)
  pos=nx.spring_layout(G) # positions for all nodes
  nx.draw_networkx_nodes(G,pos,noG=800)
  nx.draw_networkx_edges(G,pos)
  nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif')
  nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_pro_dict)

  plt.figure(2)
  nx.draw_networkx_nodes(Gmp,pos,noG=800)
  nx.draw_networkx_edges(Gmp,pos)
  nx.draw_networkx_labels(Gmp,pos,font_size=10,font_family='sans-serif')

  plt.figure(3)
  nx.draw_networkx_nodes(Ggp,pos,noG=800)
  nx.draw_networkx_edges(Ggp,pos)
  nx.draw_networkx_labels(Ggp,pos,font_size=10,font_family='sans-serif')

  plt.figure(4)
  nx.draw_networkx_nodes(Gadr,pos,noG=800)
  nx.draw_networkx_edges(Gadr,pos)
  nx.draw_networkx_labels(Gadr,pos,font_size=10,font_family='sans-serif')

  plt.figure(5)
  nx.draw_networkx_nodes(Gabm,pos,noG=800)
  nx.draw_networkx_edges(Gabm,pos)
  nx.draw_networkx_labels(Gabm,pos,font_size=10,font_family='sans-serif')

  plt.show()
开发者ID:sun9700,项目名称:GA4UG,代码行数:29,代码来源:draw_graph_basic.py


示例18: draw_graph

def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):
    """Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net"""
    print "Generating graph..."
    try:
        with open(filename, 'r') as f:
            G = p.load(f)
    except:
        G = getgraph(username, password)
        with open(filename, 'w') as f:
            p.dump(G, f)
    #nx.draw(G)
    # Judge whether remove the isolated point from graph
    if remove_isolated is True:
        H = nx.empty_graph()
        for SG in nx.connected_component_subgraphs(G):
            if SG.number_of_nodes() > iso_level:
                H = nx.union(SG, H)
        G = H
    # Ajust graph for better presentation
    if different_size is True:
        L = nx.degree(G)
        G.dot_size = {}
        for k, v in L.items():
            G.dot_size[k] = v
        node_size = [G.dot_size[v] * 10 for v in G]
    pos = nx.spring_layout(G, iterations=50)
    nx.draw_networkx_edges(G, pos, alpha=0.2)
    nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3)
    # Judge whether shows label
    if label_flag is True:
        nx.draw_networkx_labels(G, pos, alpha=0.5)
    #nx.draw_graphviz(G)
    plt.show()

    return G
开发者ID:DAWN0226,项目名称:scripts,代码行数:35,代码来源:renren.py


示例19: _graph_intelligence_nx

 def _graph_intelligence_nx(bot, file_path):
     # TODO: Make BehaviorGraph track the launch node and mark it in the graph output
     print("Saving Champion Intelligence Graph...")
     behavior_nodes = bot.behavior.behavior_nodes
     network = nx.DiGraph()
     network.add_nodes_from(behavior_nodes)
     # Add the behavior nodes to the network and link them together
     for node in behavior_nodes:
         if node.node_type == NodeRegister.statement:
             network.add_edge(node, node.next_node, label='')
         elif node.node_type == NodeRegister.conditional:
             network.add_edge(node, node.true_node, label='1')
             network.add_edge(node, node.false_node, label='0')
     # Draw the network
     layout = nx.shell_layout(network, scale=3)
     plt.figure(figsize=(10, 10))
     plt.axis('equal')
     plt.title("%s: Born:%s, Age:%s, Peak Energy:%s, Children:%s" %
               (str(bot), str(bot.birthday), str(bot.age), str(bot.peak_energy), str(bot.number_children)))
     nx.draw_networkx_edges(network, layout, width=0.5, alpha=0.75, edge_color='black', arrows=True)
     statement_color = '#D7E7F7'
     conditional_color = '#F7D7DA'
     colors = [statement_color if node.node_type == NodeRegister.statement else conditional_color
               for node in network.nodes()]
     nx.draw_networkx_nodes(network, layout, node_size=1800, node_color=colors, alpha=1)
     # Reformat node names to make them easier to read
     names = [(node, str(node.function.__name__).replace('_', '\n')) for node in behavior_nodes]
     labels = {key: value for (key, value) in names}
     nx.draw_networkx_labels(network, layout, labels, font_size=10, font_family='sans-serif')
     edge_names = nx.get_edge_attributes(network, 'label')
     nx.draw_networkx_edge_labels(network, layout, edge_labels=edge_names, label_pos=0.7)
     plt.axis('off')
     plt.savefig(file_path + '.png', dpi=80, pad_inches=0.0, bbox_inches='tight')
开发者ID:sjirjies,项目名称:nss,代码行数:33,代码来源:world.py


示例20: draw_graph

    def draw_graph(self):
        import matplotlib.pyplot as plt

        elarge = [(u, v) for (u, v, d) in self._graph.edges(data=True)
                  if d['type'] == 'audio_source']
        esmall = [(u, v) for (u, v, d) in self._graph.edges(data=True)
                  if d['type'] == 'data_source']

        pos = nx.shell_layout(self._graph)  # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(self._graph, pos, node_size=700)

        # edges
        nx.draw_networkx_edges(self._graph, pos, edgelist=elarge,
                               arrows=True)
        nx.draw_networkx_edges(self._graph, pos, edgelist=esmall,
                               alpha=0.5, edge_color='b',
                               style='dashed', arrows=True)

        # labels
        labels = {node: repr(self._graph.node[node]['processor']) for node in self._graph.nodes()}
        nx.draw_networkx_labels(self._graph, pos, labels, font_size=20,
                                font_family='sans-serif')

        plt.axis('off')
        plt.show()  # display
开发者ID:MikeLevine,项目名称:speaky,代码行数:27,代码来源:core.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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