def test_scale_and_center_arg(self): G = nx.complete_graph(9) G.add_node(9) vpos = nx.random_layout(G, scale=2, center=(4,5)) self.check_scale_and_center(vpos, scale=2, center=(4,5)) vpos = nx.spring_layout(G, scale=2, center=(4,5)) self.check_scale_and_center(vpos, scale=2, center=(4,5)) vpos = nx.spectral_layout(G, scale=2, center=(4,5)) self.check_scale_and_center(vpos, scale=2, center=(4,5)) # circular can have twice as big length vpos = nx.circular_layout(G, scale=2, center=(4,5)) self.check_scale_and_center(vpos, scale=2*2, center=(4,5)) vpos = nx.shell_layout(G, scale=2, center=(4,5)) self.check_scale_and_center(vpos, scale=2*2, center=(4,5)) # check default center and scale vpos = nx.random_layout(G) self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5)) vpos = nx.spring_layout(G) self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5)) vpos = nx.spectral_layout(G) self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5)) vpos = nx.circular_layout(G) self.check_scale_and_center(vpos, scale=2, center=(0,0)) vpos = nx.shell_layout(G) self.check_scale_and_center(vpos, scale=2, center=(0,0))
def buildGraphFromTwitterFollowing(self): while True: twitter_id=self.userq.get() #print "======================================" twitter_id_dict=json.loads(twitter_id.AsJsonString()) #print twitter_id_dict["name"] #print i.AsJsonString() #pprint.pprint(i.GetCreatedAt()) #pprint.pprint(i.GetGeo()) #pprint.pprint(i.GetLocation()) #pprint.pprint(i.GetText()) for f in self.api.GetFollowers(twitter_id): try: follower_id_dict=json.loads(f.AsJsonString()) #print follower_id_dict["name"] self.tng.add_edge(twitter_id_dict["name"],follower_id_dict["name"]) self.userq.put(f) self.no_of_vertices+=1 except: pass if self.no_of_vertices > 50: break print "======================================" nx.shell_layout(self.tng) nx.draw_networkx(self.tng) print "===========================================================================================" print "Bonacich Power Centrality of the Social Network (Twitter) Crawled - computed using PageRank" print "(a degree centrality based on social prestige)" print "===========================================================================================" print sorted(nx.pagerank(self.tng).items(),key=operator.itemgetter(1),reverse=True) print "===========================================================================================" print "Eigen Vector Centrality" print "===========================================================================================" print nx.eigenvector_centrality(self.tng) plt.show()
def test_single_nodes(self): G = nx.path_graph(1) vpos = nx.shell_layout(G) assert(vpos[0].any() == False) G = nx.path_graph(3) vpos = nx.shell_layout(G, [[0], [1,2]]) assert(vpos[0].any() == False)
def test_shell_layout(self): G = nx.complete_graph(9) shells=[[0], [1,2,3,5], [4,6,7,8]] vpos = nx.shell_layout(G, nlist=shells) vpos = nx.shell_layout(G, nlist=shells, scale=2, center=(3,4)) shells=[[0,1,2,3,5], [4,6,7,8]] vpos = nx.shell_layout(G, nlist=shells) vpos = nx.shell_layout(G, nlist=shells, scale=2, center=(3,4))
def test_empty_graph(self): G=nx.Graph() vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.shell_layout(G) vpos = nx.spectral_layout(G) # center arg vpos = nx.random_layout(G, scale=2, center=(4,5)) vpos = nx.circular_layout(G, scale=2, center=(4,5)) vpos = nx.spring_layout(G, scale=2, center=(4,5)) vpos = nx.shell_layout(G, scale=2, center=(4,5)) vpos = nx.spectral_layout(G, scale=2, center=(4,5))
def test_single_node(self): G = nx.Graph() G.add_node(0) vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.shell_layout(G) vpos = nx.spectral_layout(G) # center arg vpos = nx.random_layout(G, scale=2, center=(4,5)) vpos = nx.circular_layout(G, scale=2, center=(4,5)) vpos = nx.spring_layout(G, scale=2, center=(4,5)) vpos = nx.shell_layout(G, scale=2, center=(4,5)) vpos = nx.spectral_layout(G, scale=2, center=(4,5))
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")
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
def get(self): G = nx.Graph() self.add_header("Access-Control-Allow-Origin", "*") n_name = self.get_argument('cnode') lt = list(one_x_extend(n_name)) rtid = {"nodes":[],"links":[]} for item in cast_path_2_node(lt): tmp = {"name":str(item)} rtid["nodes"].append(tmp) cdict = {} for item in enumerate(cast_path_2_node(lt)): cdict[str(item[1])] = item[0] for item in cast_path_2_link(lt): G.add_edge(item[0],item[1]) tmp = {"source":item[0],"target":item[1]} rtid["links"].append(tmp) co = choice('01') #pos = nx.spring_layout(G, scale=1.0) if co == '0': pos = nx.circular_layout(G) elif co == '1': pos = nx.spring_layout(G) else: pos = nx.shell_layout(G) text = ''.join(cast_dict_2_gexf(rtid,pos)) print text self.write(text)
def draw_graph(graph, labels=None, graph_layout='shell', node_size=120, node_color='blue', node_alpha=0.3, node_text_size=8, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # create networkx graph G=nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) print G.nodes() nodeColors = [] nodeClients = [] for node in G.nodes(): if is_number(node): nodeColors.append(0) else: nodeColors.append(1) nodeClients.append(node) edgeColors = [] for edge in G.edges(): if (edge[0] in nodeClients) or (edge[1] in nodeClients): edgeColors.append(1) else: edgeColors.append(0) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G,graph_pos,node_size=node_size, alpha=node_alpha, node_color=nodeColors) nx.draw_networkx_edges(G,graph_pos,width=edge_tickness, alpha=edge_alpha,edge_color=edgeColors) nx.draw_networkx_labels(G, graph_pos,font_size=node_text_size, font_family=text_font, font_weight='normal', alpha=1.0) # if labels is None: # labels = range(len(graph)) # edge_labels = dict(zip(graph, labels)) # nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, # label_pos=edge_text_pos) # show graph plt.show()
def simplePlot(graph, layout = "shell", nodeSize= 600, widthEdge=2): """ Plot a directed graph using igraph library. @type graph: graph @param graph: a graph to plot @type layout: string @param layout: node position method (shell, circular, random, spring, spectral) """ G=nx.DiGraph() for node in graph.keys(): G.add_node(node) #add edges for v1 in graph.keys(): for v2 in graph[v1]: G.add_edge(v1, v2) # draw graph if layout == 'circular': pos = nx.circular_layout(G) elif layout == 'random': pos = nx.random_layout(G) elif layout == 'spring': pos = nx.random_layout(G) elif layout == 'spectral': pos = nx.spectral_layout(G) else: pos = nx.shell_layout(G) nx.draw(G, pos, edge_color='#796d54', alpha=1, node_color='#4370D8',cmap=plt.cm.Blues, node_size=nodeSize, width=widthEdge) plt.show()
def drawGraph(graph): pos=nx.shell_layout(graph) redList = [] blackList = [] labels = {} edgeLabel = {} for x in graph.edges(): #edgeLabel[x]=str(G[x[0]][x[1]]['weight']) edgeLabel[x]=str(1) for x in xrange(graph.number_of_nodes()): labels[x]=x if graph.node[x]["color"] == 'R': redList.append(x) else: blackList.append(x) nx.draw_networkx_nodes(graph,pos, nodelist=redList, node_color='r', node_size=500, alpha=0.8) nx.draw_networkx_nodes(graph,pos, nodelist=blackList, node_color='b', node_size=500, alpha=0.8) nx.draw_networkx_labels(graph,pos,labels,font_size=16) nx.draw_networkx_edges(graph,pos,width=1.0,alpha=0.5) #nx.draw_networkx_edge_labels(G,pos, label=edgeLabel) plt.show() return edgeLabel
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')
def draw_graph(G, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G,graph_pos,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) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=labels, label_pos=edge_text_pos) # show graph frame = plt.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) plt.show()
def draw_graph(graph, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # create networkx graph G=nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) nx.draw(G) #nx.draw_random(G) #nx.draw_spectral(G) # show graph newFolder = graphPath if not os.path.exists(newFolder): os.makedirs(newFolder) plt.savefig(newFolder+anchor+"Network.png")
def draw(self): # node attrs node_size=1600 # 1-hop, 2-hop etc root_color = 'red' node_tiers = ['blue','green','yellow'] node_color='blue' node_alpha=0.3 node_text_size=12 # edge attrs edge_color='black' edge_alpha=0.3 edge_tickness=1 edge_text_pos=0.3 f = plt.figure() graph_pos = nx.shell_layout(self.G) # draw graph nx.draw_networkx_nodes(self.G, graph_pos, nodelist=[self.root], alpha=node_alpha, node_color=root_color) for hop, nodes in self.hops.iteritems(): if len(nodes) == 0: continue print hop nx.draw_networkx_nodes(self.G, graph_pos, nodelist=nodes, alpha=node_alpha, node_color=node_tiers[hop-1]) nx.draw_networkx_edges(self.G,graph_pos, edgelist=self.hops_edges[hop], width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) nx.draw_networkx_labels(self.G, graph_pos,font_size=node_text_size)
def saveImage( self, nrepr = "spring", ft = "png", filename = "", graph = None ): """store an image representation of the network""" if graph == None: if self.Graph == None: self._alert( "No network given, not drawing." ) return False else: graph = self.Graph if self._output_dir == "": self._extalert( "Target directory needs to be assigned with {!r} first!" ) return 1 if ft not in ( "png" ): ft = "png" if filename == "": filename = self.ModelName + "." + ft filename = os.path.join( self._output_dir, filename ) if nrepr == "shells": shells = [ [ key for key in graph.nodes_iter( ) if graph.node[ key ][ "shell" ] == s ] for s in xrange( graph[ "shell" ] + 1 ) ] pos = nx.shell_layout( graph, shells ) else: pos = nx.spring_layout( graph ) plt.figure( figsize = ( 8, 8 ) ) nx.draw( graph, pos ) plt.savefig( filename )
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() # 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) nx.draw(G, pos) # show graph plt.show()
def draw_graph(graph, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif', save=True, filename=None): edge_labels=dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(graph) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(graph) elif graph_layout == 'random': graph_pos=nx.random_layout(graph) elif graph_layout == 'circular': graph_pos=nx.circular_layout(graph) else: graph_pos=nx.shell_layout(graph) # draw graph nx.draw_networkx_nodes(graph, graph_pos, node_size=node_size, alpha=node_alpha, node_color=node_color) nx.draw_networkx_edges(graph, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) nx.draw_networkx_labels(graph, graph_pos, font_size=node_text_size, font_family=text_font) nx.draw_networkx_edge_labels(graph, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos) # show graph if save == True: plt.savefig(filename, dpi=1000) plt.show()
def draw_graph(G, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G,graph_pos,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) edge_labs=dict([((u,v,),d['label']) for u,v,d in G.edges(data=True)]) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labs, font_size=node_text_size, font_family=text_font) # show graph plt.show()
def __init__(self, gs): """ Stores the L{GraphStructure} object to visually display. @type gs: L{GraphStructure} object @param gs: L{GraphStructure} object to visually display. """ self.gs = gs self.g = self.gs.get_graph() # Sets up visual node properties self.node_size = 1600 self.node_color = 'blue' self.node_alpha = 0.3 self.node_text_size = 8 # Sets up visual edge properties self.edge_color = 'blue' self.edge_alpha = 0.3 self.edge_tickness = 1 self.edge_text_pos = 0.5 self.edge_text_size = 8 # Sets the text font for the graph to display self.text_font = 'sans-serif' # Uses a shell layout for the graph visualization self.graph_pos = nx.shell_layout(self.g)
def draw_graph(G, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G,graph_pos,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) if labels is None: labels = range(len(G)) edge_labels = dict(zip(G, labels)) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=labels, label_pos=edge_text_pos) # show graph plt.show()
def draw_simple(self,title,color): """ draws a simple graph without levels for an overview """ self.clean_edge() # make the succ minimal print(self.matrix) G=nx.DiGraph() # define a digraph for i in self.liste: G.add_node(i.name) # add all sits to graph as nodes for i in self.liste: for j in i.succ: G.add_edge(i.name,j.name) print() # fill the labels with default values labels={} for l in G.nodes(): labels[l]=str(l) # pos=nx.spring_layout(G) # pos=nx.spectral_layout(G) # pos=nx.random_layout(G) pos=nx.shell_layout(G) if(color==True): nx.draw_networkx_nodes(G,pos,node_color='g',node_size=800) else: nx.draw_networkx_nodes(G,pos,node_color='lightgray',node_size=800) nx.draw_networkx_edges(G,pos) nx.draw_networkx_labels(G,pos) plt.title('SIMPLE: '+title) plt.axis('on') plt.show()
def main(): """Display a graph with Matplotlib.""" G = nx.DiGraph() G.add_edge('賢者の石', '金塊', weight=1) G.add_edge('賢者の石', 'オリハルコン', weight=1) G.add_edge('賢者の石', 'せかいじゅのしずく', weight=1) G.reverse(False) pos = nx.shell_layout(G) # Draw edge labels. edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)} nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) # Draw the graph. nx.draw(G, pos, nodelist=[], node_color='w') # Draw node labels. text_items = nx.draw_networkx_labels(G, pos) # Change the font for node labels. font_prop = FontProperties(fname=r'C:\WINDOWS\Fonts\meiryo.ttc') for t in text_items.values(): t.set_fontproperties(font_prop) # Display with Matplotlib. plt.show()
def draw_graph(graph, labels=None, graph_layout='spring', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # create networkx graph G=nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) elif graph_layout == 'random': graph_pos=nx.random_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G,graph_pos,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) plt.show()
def draw_graph(self, graph): graph_layout = 'shell' node_size = 800 node_color = 'blue' node_alpha = 0.3 node_text_size = 12 edge_color = 'blue' edge_alpha = 0.3 edge_tickness = 1.5 nxGraph = nx.Graph() figure = Figure(figsize=(5, 4), dpi=100) plot_area = figure.add_subplot(111) for edge in graph: nxGraph.add_edge(edge[0], edge[1]) graph_pos = nx.shell_layout(nxGraph) nx.draw_networkx_nodes(nxGraph, graph_pos, ax = plot_area, node_size = node_size, alpha = node_alpha, node_color = node_color) nx.draw_networkx_edges(nxGraph, graph_pos, ax = plot_area, width = edge_tickness, alpha = edge_alpha, edge_color = edge_color) nx.draw_networkx_labels(nxGraph, graph_pos, ax = plot_area, font_size=node_text_size) self.canvas = FigureCanvasTkAgg(figure, master=self.parent) self.canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
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
def draw_graph(graph, matrix_topology, interfaces_names, color_vector, labels=None, graph_layout='spectral', node_size=600, node_color='blue', node_alpha=0.5,node_text_size=4, edge_color='blue', edge_alpha=0.9, edge_tickness=6, edge_text_pos=0.25, text_font='sans-serif'): # create networkx graph G=nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try # spectral seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(G) else: graph_pos=nx.shell_layout(G) # draw graph labels={} for idx, node in enumerate(G.nodes()): hostname='R'+str(idx+1) labels[idx]=hostname edge_labels=dict(zip(graph, interfaces_names)) nx.draw_networkx_nodes(G,graph_pos,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=color_vector) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos, bbox=dict(facecolor='none',edgecolor='none')) nx.draw_networkx_labels(G, graph_pos, labels, font_size=16) plt.axis('off') plt.title('Network topology') plt.show()
def draw_graph(graph): """ prepares the graph to be shown or exported """ G = nx.Graph() labels = {} for edge in graph.edges: G.add_edge(edge.nodeA.id_, edge.nodeB.id_) if "d" in sys.argv: print("duration") for edge in graph.edges: labels[(edge.nodeA.id_, edge.nodeB.id_)] = (edge.info.duration, edge.info.ti, edge.info.period, edge.info.tf, str(edge.info.transType)[:3]) elif "p" in sys.argv: print("price") for edge in graph.edges: labels[(edge.nodeA.id_, edge.nodeB.id_)] = (edge.info.price, str(edge.info.transType)[:3]) #pos = nx.circular_layout(G) #pos = nx.spring_layout(G) pos = nx.shell_layout(G) nx.draw_networkx_nodes(G, pos, node_color = "w") nx.draw_networkx_edges(G, pos, edge_color = "k") nx.draw_networkx_labels(G, pos) nx.draw_networkx_edge_labels(G, pos, edge_labels = labels)
def draw_graph(Actor, UseCase, node_pairs): u = [] d = [] G = nx.DiGraph() _g = nx.Graph(); _g.add_edges_from(node_pairs); nl = _g.nodes(); offset=0.1 for item in node_pairs: x = (item[1], item[0]) if(x in node_pairs): u.append(item) else: d.append(item) G.add_nodes_from(nl) pos = nx.shell_layout(G) # nx.draw(G, pos, font_size = 8, with_labels=False, node_color='m') # nx.draw_networkx_nodes(G, pos, nodelist = nl, node_color = 'm'); nx.draw_networkx_nodes(G, pos, nodelist = Actor.values(), node_color = 'm'); nx.draw_networkx_nodes(G, pos, nodelist = UseCase.values(), node_color = 'y'); nx.draw_networkx_edges(G, pos, edgelist = u, edge_color='r', arrows=False) nx.draw_networkx_edges(G, pos, edgelist = d, edge_color='g', arrows=True) for p in pos: pos[p][1] -= offset nx.draw_networkx_labels(G,pos,font_size=10,font_color='b' ) # un-comment the below line if you want to store the figure, other wise it can be stored from the figure generated by plt.show() also. # plt.savefig("figure_1.png") plt.show()
def test_scale_and_center_arg(self): sc = self.check_scale_and_center c = (4, 5) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5)) # rest can have 2*scale length: [-scale, scale] sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c) if self.scipy is not None: sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
def test_smoke_empty_graph(self): G = [] vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.planar_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.spectral_layout(G) vpos = nx.shell_layout(G) vpos = nx.bipartite_layout(G, G) vpos = nx.spiral_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
def test_default_scale_and_center(self): sc = self.check_scale_and_center c = (0, 0) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5)) sc(nx.spring_layout(G), scale=1, center=c) sc(nx.spectral_layout(G), scale=1, center=c) sc(nx.circular_layout(G), scale=1, center=c) sc(nx.shell_layout(G), scale=1, center=c) sc(nx.spiral_layout(G), scale=1, center=c) if self.scipy is not None: sc(nx.kamada_kawai_layout(G), scale=1, center=c)
def draw_graph(adjacency_matrix ): # a is adjacency matrix of network and n is size of network G = nx.Graph() number_of_nodes = len(adjacency_matrix) for i in range(0, number_of_nodes): G.add_node(i) for i in range(0, number_of_nodes): for j in range(0, i): if adjacency_matrix[i][j] == 1: G.add_edge(i, j) pos = nx.shell_layout(G) nx.draw(G, pos) plt.show()
def draw_graph(graph, labels_dict=None, graph_layout='spring', node_size=5, node_color='blue', node_alpha=0.3, node_text_size=11, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): import networkx as nx import matplotlib.pyplot as plt # create networkx graph G = nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos = nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos = nx.spectral_layout(G) elif graph_layout == 'random': graph_pos = nx.random_layout(G) else: graph_pos = nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G, graph_pos, 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, labels=labels_dict, font_size=node_text_size, font_family=text_font) plt.show()
def graph(self, keyword): d = self.d connections = {} for interest in d: connection = d[interest] for person1 in connection: for person2 in connection: if person1 == person2: continue else: if person1 not in connections: connections[person1] = { person2, } else: connections[person1].add(person2) fig, ax = plt.subplots() plt.title(keyword[0].upper() + keyword[1:].lower()) G = nx.Graph() for person in connections: network = connections[person] for p in network: G.add_edge(person, p, color='b') pos = nx.shell_layout(G) nx.draw(G, pos, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.07 nx.draw_networkx_labels(G, pos) def onclick(event): if event.xdata != None and event.ydata != None: for p in pos: x = pos[p][0] y = pos[p][1] r = 0.1 if x-r <= event.xdata and x+r >= event.xdata and \ y-r <= event.ydata and y+r >= event.ydata: self.showAuthor(p) return 42 cid = fig.canvas.mpl_connect('button_press_event', onclick) if pos != {}: plt.show() return 42 else: plt.close() return None
def from_parsed_input(cls, cu_dict: Dict[str, ObjectifiedElement], dependencies_list: List[DependenceItem], loop_data: Dict[str, int], reduction_vars: List[Dict[str, str]]): """Constructor for making a PETGraphX from the output of parser.parse_inputs()""" g = nx.MultiDiGraph() for id, node in cu_dict.items(): n = parse_cu(node) g.add_node(id, data=n) for node_id, node in cu_dict.items(): source = node_id if 'childrenNodes' in dir(node): for child in [n.text for n in node.childrenNodes]: if child not in g: print(f"WARNING: no child node {child} found") g.add_edge(source, child, data=Dependency(EdgeType.CHILD)) if 'successors' in dir(node) and 'CU' in dir(node.successors): for successor in [n.text for n in node.successors.CU]: if successor not in g: print(f"WARNING: no successor node {successor} found") g.add_edge(source, successor, data=Dependency(EdgeType.SUCCESSOR)) for _, node in g.nodes(data='data'): if node.type == NodeType.LOOP: node.loop_iterations = loop_data.get(node.start_position(), 0) # calculate position before dependencies affect them try: pos = nx.planar_layout(g) # good except nx.exception.NetworkXException: try: # fallback layouts pos = nx.shell_layout(g) # maybe # self.pos = nx.kamada_kawai_layout(self.graph) # maybe except nx.exception.NetworkXException: pos = nx.random_layout(g) for dep in dependencies_list: if dep.type == 'INIT': continue sink_cu_ids = readlineToCUIdMap[dep.sink] source_cu_ids = writelineToCUIdMap[dep.source] for sink_cu_id in sink_cu_ids: for source_cu_id in source_cu_ids: if sink_cu_id == source_cu_id and (dep.type == 'WAR' or dep.type == 'WAW'): continue elif sink_cu_id and source_cu_id: g.add_edge(sink_cu_id, source_cu_id, data=parse_dependency(dep)) return cls(g, reduction_vars, pos)
def draw_network(self,figname='test.svg'): #pos=nx.spring_layout(self.g) #pos=nx.circular_layout(self.g) ##pos=nx.kamada_kawai_layout(self.g) #pos=nx.planar_layout(self.g) #pos=nx.random_layout(self.g) ##pos=nx.rescale_layout(self.g) pos=nx.shell_layout(self.g) #pos=nx.spectral_layout(self.g) #pos=nx.spiral_layout(self.g) #node #node_shape s0^>V<dph8 node_colors=[self.g.nodes.get(w).get('nodecolor','blue') for w in self.g.nodes] node_size=[self.g.nodes.get(w).get('nodesize',1) for w in self.g.nodes] node_alpha=[self.g.nodes.get(w).get('nodealpha',0.5) for w in self.g.nodes] print(node_colors) print(node_size) print(node_alpha) nx.draw_networkx_nodes(self.g,pos,node_color=node_colors,node_size=node_size,alpha=node_alpha) #edge draw #style solid/dashed/dotted dashdot only edge_widths=[self.g.edges.get(w).get('edgewidth',1.0) for w in self.g.edges] edge_colors=[self.g.edges.get(w).get('edgecolor','black') for w in self.g.edges] nx.draw_networkx_edges(self.g,pos,width=edge_widths,edge_color=edge_colors,style='solid',alpha=0.3) #edge label #edgelabeldic={w:float(self.g.edges.get(w).get('width',1)) for w in self.g.edges} #nx.draw_networkx_edge_labels(self.g,pos,edge_labels=edgelabeldic,alpha=0.5) plt.xticks([]) plt.yticks([]) plt.savefig('draft_'+figname,dpi=1200) #node label #font_family font_color:string only // font_size int only #nx.draw_networkx_labels(self.g,pos,font_family=self.font_family,font_size=5,font_color='black',alpha=0.8) labeldic={w:i for i,w in enumerate(self.g.nodes)} nx.draw_networkx_labels(self.g,pos,labels=labeldic,font_family=self.font_family,font_size=5,font_color='black',style='bold',alpha=1.0) plt.xticks([]) plt.yticks([]) plt.savefig(figname,dpi=1200) self.revlabeldic={} self.labeldic=labeldic for k,v in labeldic.items(): print(k,v) self.revlabeldic[v]=k
def buildGraphFromTwitterFollowing(self): while True: twitter_id = self.userq.get() #print "======================================" twitter_id_dict = json.loads(twitter_id.AsJsonString()) #print twitter_id_dict["name"] #print i.AsJsonString() #pprint.pprint(i.GetCreatedAt()) #pprint.pprint(i.GetGeo()) #pprint.pprint(i.GetLocation()) #pprint.pprint(i.GetText()) for f in self.api.GetFollowers(twitter_id): try: follower_id_dict = json.loads(f.AsJsonString()) #print follower_id_dict["name"] self.tng.add_edge(twitter_id_dict["name"], follower_id_dict["name"]) self.userq.put(f) self.no_of_vertices += 1 except: pass if self.no_of_vertices > 50: break print "======================================" nx.shell_layout(self.tng) nx.draw_networkx(self.tng) print "===========================================================================================" print "Bonacich Power Centrality of the Social Network (Twitter) Crawled - computed using PageRank" print "(a degree centrality based on social prestige)" print "===========================================================================================" print sorted(nx.pagerank(self.tng).items(), key=operator.itemgetter(1), reverse=True) print "===========================================================================================" print "Eigen Vector Centrality" print "===========================================================================================" print nx.eigenvector_centrality(self.tng) plt.show()
def action(self): self.construir_arbol() print self.list_objetcs print self.is_related(self.list_objetcs, "author") print self.is_related(self.list_objetcs, "Rajsbaum, Sergio") print self.is_related(self.list_objetcs, "2011") print self.is_related(self.list_objetcs, "Urrutia, Jorge") print self.is_related(self.list_objetcs, "book") list_a = Set([]) lista = self.extension("author", list_a) print "extension author", lista list_a.clear() self.valido("author", list_a) print "valido author", list_a list_a.clear() self.extension("type", list_a) print "extension type", list_a list_a.clear() self.valido("type", list_a) print "valido type", list_a for item in self.G.nodes(data=True): print item #print self.G.edges(nbunch=None, data=True) count = 1 for item in self.list_objetcs: if item.title != "": print count, ") ", item.title, '\n', item.author, '\n', item.year, '\n', item.journal, '\n', item.idp, item.type, '\n\n' count = count + 1 list_a.clear() print "conceptos\n\n" for a in self.list_objetcs: list_a.add(a.idp) list_b = Set([]) self.set_conceptos(list_a, "publication", list_b) print list_b pos = nx.shell_layout(self.G) nx.draw(self.G, pos) plt.show()
def _set_node_positions(self, layout='shell'): if layout == 'spring': self.npositions = nx.spring_layout(self, k=0.75, iterations=500, scale=10) elif layout == 'shell': self.npositions = nx.shell_layout(self) elif layout == 'circular': self.npositions = nx.circular_layout(self) elif layout == 'graphviz': self.npositions = nx.nx_pydot.graphviz_layout(self, prog='neato') elif layout == 'pydot': self.npositions = nx.nx_pydot.pydot_layout(self, prog='dot')
def draw_retiming_graph(graph): """ Draws retiming graph alongside edges weights and node delay :param graph: graph to draw """ pos = nx.shell_layout(graph) delay = nx.get_node_attributes(graph, 'delay') weights = nx.get_edge_attributes(graph, 'weight') nx.draw_networkx_edge_labels(graph, pos, edge_labels=weights) nx.draw_shell(graph, labels=delay, with_labels=True, font_weight='bold') plt.show()
def plot_graph(graph, partition=None): if partition is not None: node_colors = get_node_colors(graph, partition) else: node_colors = None pos = nx.shell_layout(graph) nx.draw_networkx_nodes(graph, pos, node_color=node_colors) nx.draw_networkx_edges(graph, pos) nx.draw_networkx_edge_labels(graph, pos, edge_labels=nx.get_edge_attributes( graph, "weight"), font_size=10) nx.draw_networkx_labels(graph, pos)
def draw_graph(self, figure, source, only_tree=False): # draws a graph on the screen. if only_tree is True, only tree edges are drawn import networkx as nx import matplotlib.pyplot as plt # set things up for the graph to be drawn on screen G = nx.DiGraph() plt.figure(figure) G.add_edges_from(self.get_all_edges_as_couples(only_tree)) pos = nx.shell_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size = 500) nx.draw_networkx_edges(G, pos, edge_color='r', arrows=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=self.get_edge_costs(only_tree), ) nx.draw_networkx_labels(G, pos) plt.show()
def layout_dealer(graph, layout): if nx.is_directed(graph): print("Err, only graph undirected") return if layout == "spring": return nx.spring_layout(graph) elif layout == "circular": return nx.circular_layout(graph) elif layout == "spectral": return nx.spectral_layout(graph) elif layout == "shell": return nx.shell_layout(graph) elif layout == "random": return nx.random_layout(graph)
def draw_diffusion_tree(diffusive_arrival_times, type=0): Diffusion_Tree = nx.DiGraph() for node, value in diffusive_arrival_times.items(): for i in range(0, len(value) - 1): Diffusion_Tree.add_weighted_edges_from([[value[i], value[i + 1], 0]]) if type == 0: pos = nx.spring_layout(Diffusion_Tree) if type == 1: pos = nx.random_layout(Diffusion_Tree) if type == 2: pos = nx.shell_layout(Diffusion_Tree) plt.subplot(133) nx.draw_networkx(Diffusion_Tree, pos, with_labels=True, node_color='blue', node_size=4) # 按参数构图 return Diffusion_Tree
def test_smoke_int(self): G = self.Gi vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.fruchterman_reingold_layout(self.bigG) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G.to_directed()) vpos = nx.spectral_layout(self.bigG) vpos = nx.spectral_layout(self.bigG.to_directed()) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
def test_empty_graph(self): G = nx.empty_graph() vpos = nx.random_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.circular_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.spring_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.spectral_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.shell_layout(G, center=(1, 1)) assert_equal(vpos, {})
def __init__(self, matrix): self.graph = net.Graph() for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] == '1': self.graph.add_edge(i + 1, j + 1) net.draw(self.graph, pos=net.shell_layout(self.graph), with_labels=True, node_size=100, width=1, font_size=13, font_family="Rockwell Condensed", node_color="white")
def small_world_population(a, b, c): """a-->种群中个体数量 b-->每个节点的相邻节点 c-->节点重连概率""" ER = nx.random_graphs.watts_strogatz_graph(a, b, c) # 生成包含a个节点、b个相邻节点、以概率0.2连接的随机图 pos = nx.shell_layout(ER) #nx.draw(ER, pos, with_labels=True, node_size=100) #print ER.nodes() #print ER.neighbors(1) #plt.show() list_neighbour = [[] for i in xrange(pop_size)] # 节点邻居 for i in xrange(pop_size): list_neighbour[i].extend(ER.neighbors(i)) return list_neighbour
def compute_and_save_rm_spec(domain_file, prob_file, plan_file, rm_file_dest, world, strict=False, render=False): pop = compute_pop(domain_file, prob_file, plan_file) task_rm_net = pop_to_rm_network(pop) if render: nx.draw_networkx(task_rm_net, pos=nx.shell_layout(task_rm_net), with_labels=False) nx.draw_networkx_edge_labels(task_rm_net, pos=nx.shell_layout(task_rm_net)) plt.show() task_rm = rm_net_to_reward_machine(task_rm_net, world, strict=strict) spec = task_rm.get_txt_representation() write_file(rm_file_dest, spec) return pop
def draw_graph(G, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos = nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos = nx.spectral_layout(G) elif graph_layout == 'random': graph_pos = nx.random_layout(G) else: graph_pos = nx.shell_layout(G) # draw graph nx.draw_networkx_nodes(G, graph_pos, 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) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=labels, label_pos=edge_text_pos) # show graph frame = plt.gca() plt.gcf().set_size_inches(10, 10) frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) plt.show()
def created_graph(event): graf1 = nwx.Graph() for i in edges: graf1.add_nodes_from(i) for i, j in edges: graf1.add_edge(i, j) nwx.draw(graf1, pos=nwx.shell_layout(graf1), alpha=0.6, edge_color='b', font_size=20, node_size=700, arrows=True, with_labels=True) plt.show()
def draw_graph(graph, save_path): import matplotlib.pyplot as plt graph_pos = nx.shell_layout(graph) nx.draw_networkx_nodes(graph, graph_pos, node_size=1000, node_color='blue', alpha=0.3) nx.draw_networkx_edges(graph, graph_pos) nx.draw_networkx_labels(graph, graph_pos, font_size=12, font_family='sans-serif') plt.savefig(save_path) plt.close()
def print_graph(self): nodes, edges = self.graph() G = nx.DiGraph(directed=True) G.add_edges_from(edges) G.add_nodes_from(nodes) nx.draw(G.reverse(), with_labels=True) pos = nx.shell_layout(G) x_values, y_values = zip(*pos.values()) x_max = max(x_values) x_min = min(x_values) x_margin = (x_max - x_min) * 2 plt.xlim(x_min - x_margin, x_max + x_margin) plt.savefig('foo.png')
def layouting(layout, m): pos = graphviz_layout(m) if layout == 1: pos = graphviz_layout(m) elif layout == 2: pos = nx.circular_layout(m) elif layout == 3: pos = nx.spring_layout(m) elif layout == 4: pos = nx.spectral_layout(m) elif layout == 5: pos = nx.random_layout(m) elif layout == 6: pos = nx.shell_layout(m) return pos
def initialize_layout(self): # Calculate the positions of all nodes in the network visualization # Generate an auxiliary graph and fill it with nodes from the network auxiliary_graph = nx.Graph() auxiliary_graph.add_nodes_from( itertools.islice(self.net.nodes, 0, self.nodes)) # Set the layout for one layer, and offset the positions of nodes in each other layer accordingly all_pos = {} pos = nx.shell_layout(auxiliary_graph) for l in range(0, self.layers): for node in pos: all_pos[l * self.nodes + node] = pos[node] * self.layer_scale + ( 0, l * self.layer_y_dist) return all_pos