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 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 generateNetworkCoordinates(G, forRadius=4, forSize=(800,600)):#, layout='dot'): ''' """ generates network coordinates in the attribute 'pos' :param G: :Param layout: neato|dot|twopi|circo|fdp|nop :return: """ ag = networkx.nx_agraph.to_agraph(G) ag.layout(prog=layout) ag.write(path='dot.dot') G = networkx.nx_agraph.from_agraph(ag) ''' import networkx as nx if forSize[0] > forSize[1]: scale = 1.0-(float(forRadius)/float(forSize[1])) else: scale = 1.0-(float(forRadius)/float(forSize[0])) try: G = nx.random_layout(G, dim=2, scale=scale, center=(0,0)) except TypeError: # Fixes the problem of having another version of nx G = nx.random_layout(G, dim=2) for (key,(x,y)) in G.items(): x = 2 * x - 1 y = 2 * y - 1 G[key] = [x,y] return G
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(self): """ Draws the graph of relations """ G=nx.Graph() list_location1 = [] list_location2 = [] list_location3 = [] list_location4 = [] for citizen in self.citizens: G.add_node(citizen.id) if citizen.location == 1: list_location1.append(citizen.id) elif citizen.location == 2: list_location2.append(citizen.id) elif citizen.location == 3: list_location3.append(citizen.id) else: list_location4.append(citizen.id) for citizen in self.citizens: for friend in citizen.friends: G.add_edge(citizen.id,friend.id) pos = nx.random_layout(G) nx.draw_networkx_nodes(G,pos,node_size=60,nodelist=list_location1, node_color='r') nx.draw_networkx_nodes(G,pos,node_size=60,nodelist=list_location2, node_color='g') nx.draw_networkx_nodes(G,pos,node_size=60,nodelist=list_location3, node_color='b') nx.draw_networkx_nodes(G,pos,node_size=60,nodelist=list_location4, node_color='y') nx.draw_networkx_edges(G,pos, width=1) plt.show()
def display_community_graph(self): """ Display the subgraph identified by community detection """ plt.figure(num=None, figsize=(70, 50), dpi=80) up_pos_cnm=nx.random_layout(user_post_graph_cnm) for (idx, comm) in enumerate(self.sig_communities_by_id): comm_u_cnm = [] comm_p_cnm = [] for n in self.all_post_users: if n in comm: comm_u_cnm.append(n) for n in self.all_posts_res: if n in comm: comm_p_cnm.append(n) nx.draw_networkx_nodes(self.user_post_graph_cnm,up_pos_cnm, nodelist=comm_u_cnm, node_color=self.group_colors[idx], alpha=0.8) nx.draw_networkx_nodes(self.user_post_graph_cnm,up_pos_cnm, nodelist=comm_p_cnm, node_color=self.group_colors[idx], alpha=0.8) elsg1_cnm = [e for e in self.up_likes if e[0] in comm_u_cnm and e[1] in comm_p_cnm] ecsg1_cnm = [e for e in self.up_comments if e[0] in comm_u_cnm and e[1] in comm_p_cnm] epsg1_cnm = [e for e in self.up_posts if e[0] in comm_u_cnm and e[1] in comm_p_cnm] nx.draw_networkx_edges(self.user_post_graph_cnm,up_pos,edgelist=elsg1_cnm,alpha=0.5,edge_color='m') nx.draw_networkx_edges(self.user_post_graph_cnm,up_pos,edgelist=ecsg1_cnm,alpha=0.5,edge_color='teal') nx.draw_networkx_edges(self.user_post_graph_cnm,up_pos,edgelist=epsg1_cnm,alpha=0.5,edge_color='y')
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
def draw_graph(self, type): val_map = {} if type == 'whole': for user in self.extr_dic_users: if self.extr_dic_users[user] == 'c': val_map.update({ user : '******'}) elif self.extr_dic_users[user] == 'n': val_map.update({ user : '******'}) else: val_map.update({ user : '******'}) #for user in self.extr_dic_users: # val_map.update({ user : '******'}) self.m_extr_G = self.m_extr_G.to_undirected() values = [val_map.get(node) for node in self.m_extr_G.nodes()] nx.draw(self.m_extr_G, pos = nx.random_layout(self.m_extr_G, dim = 2), randomcmap = plt.get_cmap('jet'), node_color = values, width = 1, node_size = 40, with_labels=False) plt.show() elif type == 'internal': for user in self.dic_users: if self.dic_users[user][1] == 'c': val_map.update({ user : '******'}) else: val_map.update({ user : '******'}) #for user in self.extr_dic_users: # val_map.update({ user : '******'}) #self.G = self.G.to_undirected() values = [val_map.get(node) for node in self.m_G.nodes()] nx.draw(self.m_G, pos = nx.spring_layout(self.m_G, dim = 2), randomcmap = plt.get_cmap('jet'), node_color = values, width = 1, node_size = 200, with_labels=True) plt.show()
def render_path(self, **kwargs): path = kwargs['p'] open_set_size = kwargs['open_set_size'] closed_set_size = kwargs['closed_set_size'] if len(path) < 2: return else: self.sprites.set_facecolor('black') self.window.master.controller.references['path_length'].set( 'Path length: %d' % len(path) ) self.window.master.controller.references['open_set_size'].set( 'OpenSet size: %d' % open_set_size ) self.window.master.controller.references['closed_set_size'].set( 'ClosedSet size: %d' % closed_set_size ) self.window.master.controller.references['total_set_size'].set( 'Total set size: %d' % (open_set_size + closed_set_size) ) if not self.pos: self.pos = nx.random_layout(self.graph) colors = self.generate_colors(path[0]) self.sprites.set_facecolors(colors) self.canvas.draw()
def draw_facebook_graph(rxn_dict): all_edges = [] for usr in rxn_dict: for friend in rxn_dict[usr]: all_edges.append((usr, friend)) G = nx.path_graph(200) pos = nx.random_layout(G) nx.draw_networkx_nodes(G,pos, nodelist=[i for i in range(CELEB)], node_color='w', node_size=50) A = CELEB + FREQ nx.draw_networkx_nodes(G,pos, nodelist=[i for i in range(CELEB, A)], node_color='b', node_size=35) B = A + RARE nx.draw_networkx_nodes(G,pos, nodelist=[i for i in range(A, B)], node_color='r', node_size=20) C = B + EAGER nx.draw_networkx_nodes(G,pos, nodelist=[i for i in range(B, C)], node_color='g', node_size=35) D = C + NORM nx.draw_networkx_nodes(G,pos, nodelist=[i for i in range(C, D)], node_color='k', node_size=28) nx.draw_networkx_edges(G,pos, edgelist=all_edges, width=0.3, edge_color='b') nx.draw_networkx_labels(G, pos, {}) 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) 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 test_layouts(): G =nx.gnm_random_graph(10,15) rand = [nx.random_layout(G)] circ = [nx.circular_layout(G)] #shell = [nx.shell_layout(G)] #same as circular layout... spectral = [nx.spectral_layout(G)] tripod = [tripod_layout(G)] layouts = [rand,circ,spectral, tripod] regimes = ["random","circular","spectral", "tripod"] for layout in layouts: layout.append(nx.spring_layout(G,2,layout[0])) layout.append(iterate_swaps(G,layout[0])) layout.append(nx.spring_layout(G,2,layout[2])) layout.append(greedy_swapper(G,layout[0])) # Now have list of lists... Find lengths of edgecrossings... num_crossings = [] for layout in layouts: for sublayout in layout: num_crossings.append(count_crosses(G,sublayout)) names = [] for regime in regimes: names.append(regime) names.append(regime + "-spring") names.append(regime + "-swap") names.append(regime + "-swap-spr") names.append(regime + "-greedy") return G, layouts, names, num_crossings
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 playwithkmeans(n=50,k=3,p=0.6,save=False): '''randomly generate a random Watts-Strogatz graph with n - nodes k - connected to k neighbors p - rewiring from base NN ring with prob b. Labeled graph is plotted according to kmeans clust=3 to see by eye how "well" it does WH StatConn HW 1 ''' G = nx.watts_strogatz_graph(n,k,p) pos = nx.random_layout(G) adjmat = nx.to_numpy_matrix(G) km = KMeans(n_clusters=3) kmfit = km.fit(adjmat) l = kmfit.labels_ c1 = [] c2 = [] c3 = [] for i,x in enumerate(l): if x == 0: c1.append(i) if x == 1: c2.append(i) if x == 2: c3.append(i) nx.draw_networkx_nodes(G,pos,nodelist=c1,node_color='r',node_size=500,alpha=0.8) nx.draw_networkx_nodes(G,pos,nodelist=c2,node_color='g',node_size=500,alpha=0.8) nx.draw_networkx_nodes(G,pos,nodelist=c3,node_color='b',node_size=500,alpha=0.8) nx.draw_networkx_edges(G,pos) plt.title('Random Graph G with color-coded overlay of kmeans clustering k=3') if save: plt.savefig('C:\\Users\Will\\Pictures\\graph-%s.pdf'%date.today(),format='pdf') plt.show()
def opti(nodeList, colorList, edgeList, cList, firstDistance): #Only recheck for node with new color for i in range(10): v = random.randint(0, len(nodeList)) currentDistance = 0 cListBis = cList cListBis.pop(i) newColor = random.choice(cListBis) colorList[i] = newColor newDistance = 0 for (u,v) in graph.edges(): if graph.node[u]['color'] == graph.node[v]['color']: newDistance += 1 if newDistance <= distance : pos=nx.random_layout(graph) plt.figure(3,figsize=(12,9)) for nodes in graph.nodes(): nx.draw_networkx_nodes(graph, pos, nodelist=[nodes], node_color=graph.node[nodes]['color']) nx.draw_networkx_edges(graph, pos) plt.axis('off') plt.draw()
def draw_graph(G): """ @type G: DiGraph @param G: DiGraph """ nx.draw(G, pos = nx.random_layout(G, dim = 2), randomcmap = plt.get_cmap('jet'), node_color = "blue", alpha = 0.5, width = 1, node_size = 400, with_labels=True) 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(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()
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(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 communities_histogram(graph, verbose=False): graph, partition = detect_communities(graph, verbose) #plt.hist(partition.values(), bins=25, color="#0f6dbc") #plt.title("Size of Marvel Communities") #plt.xlabel("Community") #plt.ylabel("Nodes") parts = defaultdict(int) for part in partition.values(): parts[part] += 1 bubbles = nx.Graph() for part in parts.items(): bubbles.add_node(part[0], size=part[1]) pos = nx.random_layout(bubbles) plt.figure(figsize=(12,12)) plt.axis('off') nx.draw_networkx_nodes(bubbles, pos, alpha=0.6, node_size=map(lambda x: x*6, parts.values()), node_color=[random.random() for x in parts.values()], cmap=plt.cm.RdYlBu) #plt.show() plt.savefig("figure/communities_histogram_alt.png")
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 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(graph, labels=None, graph_layout='shell', node_size=1000, 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.DiGraph() # add edges i=0 for edge in graph: G.add_edge(edge[0], edge[1], attr_dict={"pkts":labels[i]}) G.node[edge[0]]['name'] = edge[0] G.node[edge[1]]['name'] = edge[1] i+=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,arrows=True) nx.draw_networkx_labels(G, graph_pos,font_size=node_text_size, font_family=text_font) 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 / save to png or pdf plt.savefig('/Users/vpattni/tmp/force/traffic.pdf',bbox_inches='tight') # Dump data in json format d = json_graph.node_link_data(G) json.dump(d, open('/Users/vpattni/tmp/force/force.json','w')) # plt.show() # Serve the file over http to allow for cross origin requests app = flask.Flask(__name__, static_folder="/Users/vpattni/tmp/force") @app.route('/<path:path>') def static_proxy(path): return app.send_static_file(path) print('\nGo to http://localhost:8000/force.html to see the example\n') app.run(port=8000)
def draw_graph(graph, labels=None, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.4, node_text_size=10, edge_color='grey', 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(graph) elif graph_layout == 'spectral': graph_pos = nx.spectral_layout(graph) elif graph_layout == 'random': graph_pos = nx.random_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) if labels is None: labels = range(len(graph.edges())) # dict([((u,v,),d) for u,v,d in graph.edges(data=True)]) edge_labels = dict(zip(graph.edges(), labels)) nx.draw_networkx_edge_labels(graph, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos) font = {'fontname' : 'Helvetica', 'color' : 'm', 'fontweight' : 'bold', 'fontsize' : 14 } plt.title("Database Tables Graph", font) font = {'fontname' : 'Helvetica', 'color' : 'r', 'fontweight' : 'bold', 'fontsize' : 14 } plt.text(0.5, 0.97, "edge = foreign key relationship", horizontalalignment='center', transform=plt.gca().transAxes) plt.axis('off') plt.savefig("db_tbls_graph.png") # show graph plt.show()
def plot_graph_k(k,n,G,list_of_Graphs_final, Gagr,d1=0.8,d2=5.0,nodesize=1000,withlabels=True,edgelist=[],layout=True,b_alpha=0.5): ''' Plotting the synthetic graph after increasing the distance among layers by a parameter d1 and dilating each layer by a parameter d1 ''' if layout: pos=nx.spring_layout(Gagr) else: pos=nx.random_layout(Gagr) minPos=min(pos.keys()) top_set=set() bottom_set=set() middle_set=set() levels=dict() created_pos={} colors=[name for name,hex in matplotlib.colors.cnames.iteritems()] for j in range(k): sset=set() pos_lis=[] for i in range(n): ij=i+j*n npos=pos[i] created_pos[ij]=[d2*npos[0],d2*(npos[1]+j*n*d1)] sset.add(ij) pos_lis.append(created_pos[ij]) col_li=colors[j] levels[j]=(sset,pos_lis,col_li) xylevels={} for i in range(k): xlevel2=[ij[0] for ij in levels[i][1]] ylevel2=[ij[1] for ij in levels[i][1]] alevel2 = [min(xlevel2)-d1/2.-0.7,max(ylevel2)+d1/2.] blevel2 = [max(xlevel2)+d1/2.-0.7,max(ylevel2)+d1/2.] clevel2 = [max(xlevel2)+d1/2.,min(ylevel2)-d1/2.] dlevel2 = [min(xlevel2)-d1/2.,min(ylevel2)-d1/2.] xylevels[i]=[alevel2,blevel2,clevel2,dlevel2] fig=plt.figure()#figsize=(20,20)) ax=fig.add_subplot(111) for i in range(k): ax.add_patch(Polygon(xylevels[i],color=levels[i][2],alpha=0.1)) xa=[j[0] for j in xylevels[i]] xa.append(xylevels[i][0][0]) ya=[j[1] for j in xylevels[i]] ya.append(xylevels[i][0][1]) plt.plot(xa,ya,'-',color=levels[i][2]) nx.draw(list_of_Graphs_final[i],created_pos,with_labels=withlabels,nodelist=list(levels[i][0]),node_color=levels[i][2],node_size=nodesize,edge_color=levels[i][2],alpha=0.2) nx.draw_networkx_edges(G,created_pos,edgelist=edgelist,edge_color='k',alpha=0.2) plt.show() return created_pos
def test_smoke_string(self): G=self.Gs vpos=nx.random_layout(G) vpos=nx.circular_layout(G) vpos=nx.spring_layout(G) vpos=nx.fruchterman_reingold_layout(G) vpos=nx.spectral_layout(G) vpos=nx.shell_layout(G)
def draw_2_level_social_graph_screen_name(self, screen_name): """ generate the two level social graph given a screen_name @type screen_name: string @param screen_name: screen name of a given user """ node_list, edge_list = self.read_node_edge_lists_screen_name("user_graph/user_graph_393_screen_name.txt") user_dic = {} f = open("../semantic_analysis/data/labelled_user_dic_393.json", "r") user_dic = cjson.decode(f.readline()) f.close() new_edge = [] new_node = set() for edge in edge_list: if screen_name == edge[1]: #new_edge.append(edge) new_node.add(edge[0]) new_node_2 = set() for node in new_node: for edge in edge_list: if node == edge[1]: #new_edge.append(edge) new_node_2.add(edge[0]) new_node.add(screen_name) new_node_list = list(new_node.union(new_node_2)) for edge in edge_list: if edge[0] in new_node_list and edge[1] in new_node_list: new_edge.append(edge) new_node_color = [] for node in new_node_list: if user_dic[node]["label"] == "d": new_node_color.append("b") elif user_dic[node]["label"] == "r": new_node_color.append("r") self.construct_graph(new_node_list, new_edge) new_node_size = [] for node in new_node_list: indegree = self.G.in_degree(node) if node == screen_name: new_node_size.append(indegree*20+5000) else: new_node_size.append(indegree*20+1000) rcParams['figure.figsize'] = 20, 16 nx.draw(self.G, pos = nx.random_layout(self.G, dim = 2), randomcmap = plt.get_cmap('jet'), node_color = new_node_color, alpha = 0.5, width = 0.5, node_size = new_node_size, with_labels=True) plt.savefig("figures/%s_%s_labelled.png" %(screen_name, user_dic[screen_name]["label"]), dpi = 100) #plt.show() plt.clf() self.G.clear()
def draw_network(dict_, sp): network = nx.Graph(name="Prueba") for node in sp.keys(): network.add_node(sp[node]) for node in dict_.keys(): for prey in dict_[node].keys(): network.add_edge(sp[node], sp[prey]) a = nx.random_layout(network) nx.draw_networkx(network, pos=a, node_size=150, font_size=0.0, width=0.7)
def NLD_random_processing_graph(g, weights, colors, layout): degree_sequence = sorted([d for n, d in g.degree()], reverse=True) magicnumber = (g.number_of_nodes() / degree_sequence[0]**2) r = 2.2 / magicnumber my_points = nx.random_layout(g) graph = from_networkx(g, layout) my_colors = [] for key, value in my_points.items(): x = value[0] + 1.0 # x = -1 .. +1, so move to 0 ... 2 y = value[1] + 1.0 # y = -1 .. +1, so move to 0 ... 2 my_colors.append("#%02x%02x%02x" % (int(50 + 100 * x), int(30 + 100 * y), 150)) # nodes and egdes attributes graph.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1] graph.node_renderer.data_source.data['degree2'] = [ sqrt(x + 6) for x in graph.node_renderer.data_source.data['degree'] ] graph.node_renderer.data_source.data['nodessize'] = [ x * 115 / (sqrt(g.number_of_nodes() + (np.mean(degree_sequence)))) for x in graph.node_renderer.data_source.data['degree2'] ] graph.node_renderer.data_source.data['my_fill_color'] = my_colors graph.edge_renderer.data_source.data['weight'] = weights graph.edge_renderer.data_source.add(colors, 'color') graph.node_renderer.glyph = Circle(size='nodesize', fill_alpha=0.85, fill_color='my_fill_color') graph.node_renderer.selection_glyph = Circle(size=10, fill_alpha=0.8, fill_color='red') graph.node_renderer.hover_glyph = Circle(size=10, fill_alpha=0.8, fill_color='yellow') graph.edge_renderer.glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='color') graph.edge_renderer.selection_glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='red') graph.edge_renderer.hover_glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='yellow') graph.edge_renderer.glyph.line_width = {'field': 'weight'} graph.selection_policy = NodesAndLinkedEdges() graph.inspection_policy = NodesAndLinkedEdges() return graph
def SimpleDraw(given1, given2, separate): print("Wywolano Funkcje rysowania z Wyróżnioną ścieżką") ToDraw = convert(given1) copy = convert(given2) ToHighlight = nx.empty_graph() ToHighlight.add_edges_from(copy.edges) Weights1 = ExtractWeight(given1) Weights2 = ExtractWeight(given2) XYpositions = { 1: (2, 7), 2: (6, 6), 3: (1, 2), 4: (4, 4), 5: (7, 2) # opcja sztywnego zakodowania koordynatow X, Y grafu, zostalo do ogarniecia } pos = nx.shell_layout( ToDraw ) # shell position definiuje ulozenie wezlow na naszym grafie w taki typowy pseudo-okragly ksztalt pos2 = nx.random_layout( ToDraw ) # random position robi dokladnie to co brzmi czyli rzuca przypadkowo wezlami plt.figure(1) nx.draw_networkx_nodes(ToDraw, pos, node_color='black', node_size=500, alpha=0.8) nx.draw_networkx_labels( ToDraw, pos, font_size=16, font_color='white' ) # wazne! Pozycjonowanie w pisaniu etykiet oraz przypinaniu krawedzi musi == pozycjonowaniu wezlow (co w sumie dosc logiczne) nx.draw_networkx_edge_labels(ToDraw, pos, edge_labels=Weights1, label_pos=0.4, font_size=16) nx.draw_networkx_edges(ToDraw, pos, edge_color='black', width=2) if separate: plt.figure(2) nx.draw_networkx_nodes(ToHighlight, pos, node_color='r', node_size=300, alpha=0.8) if separate: nx.draw_networkx_labels(ToHighlight, pos, font_size=16) nx.draw_networkx_edge_labels(ToHighlight, pos, edge_labels=Weights2, label_pos=0.4, font_size=16) nx.draw_networkx_edges(ToHighlight, pos, edge_color='r', width=4) print("Wywolano Okno") plt.show() print("Zakonczono wyswietlanie okna")
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 render_graph(G, graph_edges, edge_weights, 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(graph_edges)) edge_labels = dict(zip(graph_edges, edge_weights)) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos) # show graph plt.show() return G
def draw_graph_colored(G, graph_layout='shell', node_size=200, node_color='blue', node_alpha=0.5, node_text_size=6, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif', draw_name=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(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) cMap = plt.get_cmap('jet') tmp_nc = [] tmp_nr = [] for member in nx.get_node_attributes(G, 'region'): tmp_nc.append(nx.get_node_attributes(G, 'color')[member]) tmp_nr.append(nx.get_node_attributes(G, 'region')[member]) ncolor = cMap(tmp_nc) # draw graph nx.draw_networkx_nodes(G, graph_pos, node_size=node_size, alpha=node_alpha, node_color=ncolor, cmap=plt.get_cmap('jet')) nx.draw_networkx_edges(G, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) if draw_name: nx.draw_networkx_labels(G, graph_pos, font_size=node_text_size, font_family=text_font) plt.savefig('./output/colored_m2m_graph.jpg') print("Colored dynamic m2m graph saved.")
def update_graph(n_clicks, fig_name, dim): G = nx.from_pandas_edgelist(df, "source_id", "target_id", create_using=nx.DiGraph(), edge_attr="weights") valid = 0 if dim == "2D": valid = 1 network = network_graph_2d if fig_name == "Spring Layout": layout = nx.spring_layout(G, weight="weights", k=4 * 1 / np.sqrt(len(G.nodes())), iterations=30, dim=2, seed=10) if fig_name == "Random Layout": layout = nx.random_layout(G, seed=10) if fig_name == "Bipartite Layout": top = nx.bipartite.sets(G)[0] layout = nx.bipartite_layout(G, top) if fig_name == "Circular Layout": layout = nx.circular_layout(G) if dim == "3D": network = network_graph_3d if fig_name == "Spring Layout": layout = nx.spring_layout(G, weight="weights", k=4 * 1 / np.sqrt(len(G.nodes())), iterations=30, dim=3, seed=10) valid = 1 if fig_name == "Random Layout": layout = nx.random_layout(G, seed=10, dim=3) valid = 1 if valid == 1: return network.create_figure(df, df_nodes, layout, global_config) else: fig = go.Figure() return fig
def generate_random_(self, n): G = nx.DiGraph() for i in range(n): for j in range(i, n): if random.randint(1, 15) == 1: G.add_edge(i, j, R=random.randint(1, 20)) G.remove_nodes_from(list(nx.isolates(G))) G = nx.convert_node_labels_to_integers(G, first_label=0) random_nodes = random.sample(list(G.nodes()), 2) return G, (random_nodes[0], random_nodes[1], random.randint(10, 100)), nx.random_layout(G)
def cria_trace(G, df_parlamentares, parlamentares, cores): pos = nx.random_layout(G) edge_x = [] edge_y = [] for edge in G.edges(): x0, y0 = pos[edge[0]] x1, y1 = pos[edge[1]] edge_x.append(x0) edge_x.append(x1) edge_x.append(None) edge_y.append(y0) edge_y.append(y1) edge_y.append(None) edge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') node_x = [] node_y = [] for node in G.nodes(): x, y = pos[node] node_x.append(x) node_y.append(y) node_trace = go.Scatter(x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=dict(color=cores, size=10, line_width=2)) node_adjacencies = [] node_text = [] for node, adjacencies in enumerate(G.adjacency()): if df_parlamentares[df_parlamentares['cod'] == parlamentares[node]].afastado.item() == 'Sim': node_adjacencies.append(1) else: node_adjacencies.append(2) node_text.append(str(df_parlamentares[df_parlamentares['cod'] == parlamentares[node]].tratamento.item()) + \ str(df_parlamentares[df_parlamentares['cod'] == parlamentares[node]].nome.item()) ) if pd.isnull( df_parlamentares[df_parlamentares['cod'] == parlamentares[node]].email.item()) == False: node_text[-1] = node_text[-1] + '<br>email: ' + str( df_parlamentares[df_parlamentares['cod'] == parlamentares[node]].email.item()) node_trace.marker.color = node_adjacencies node_trace.text = node_text return edge_trace, node_trace
def draw_graph(graph, labels=None, graph_layout='shell', node_size=360, 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) # 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) # show graph plt.show() # graph = [(0, 1), (1, 5), (1, 7), (4, 5), (4, 8), (1, 6), (3, 7), (5, 9), # (2, 4), (0, 4), (2, 5), (3, 6), (8, 9)] # draw_graph(graph)
def test_single_edge_color_directed(edge_color, expected, edgelist): """Tests ways of specifying all edges have a single color for edges drawn with FancyArrowPatches""" G = nx.path_graph(3, create_using=nx.DiGraph) drawn_edges = nx.draw_networkx_edges(G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color) for fap in drawn_edges: assert mpl.colors.same_color(fap.get_edgecolor(), expected)
def visualize(self): pos = nx.random_layout(self.G) nx.draw(self.G, pos, font_size=16, node_color=self.color_map, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.04 nx.draw_networkx_labels(self.G, pos) plt.show()
def set_random_nodes_coordinates(G, attribute_label, factor=1): if factor != 1: pos = { k: factor * v for k, v in nx.random_layout(G.copy(), dim=2).items() } nx.set_node_attributes(G, pos, attribute_label) return G
def init(): global time, network, maxNodeID, positions time = 0 network = NX.Graph() network.add_node(0) maxNodeID = 0 positions = NX.random_layout(network)
def draw_network(transaction_log): G=nx.Graph() #dictionary to record the volume that a trader trades freq={} #define the trade relations between the two traders, {(trader1, trader2), frequency} relations = {} #the array of sizes for graph drawing sizes=[] for log in transaction_log: if log["trader1"] not in freq or freq[log["trader1"]] is None: freq[log["trader1"]]=1 else: freq[log["trader1"]]+=1 if log["trader2"] not in freq or freq[log["trader2"]] is None: freq[log["trader2"]]=1 else: freq[log["trader2"]]+=1 for log in transaction_log: tmp = () if log["trader1"] < log["trader2"]: tmp = (log["trader1"],log["trader2"]) else: tmp = (log["trader2"],log["trader1"]) #if the edges are already connected if tmp in relations: relations[tmp] += 1 else: relations[tmp] = 1 G.add_edge(log["trader1"],log["trader2"], weight=relations[tmp]*10) 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] #get the list of nodes from the graph nodes=G.nodes() for node in nodes: if node in freq: #the maximum size if freq[node]>=500: sizes.append(500*10) else: sizes.append(freq[node]*10) else: sizes.append(0) #pos=nx.spring_layout(G,k=0.5,iterations=500) # positions for all nodes pos=nx.random_layout(G) # nodes nx.draw_networkx_nodes(G,pos,node_size=sizes) # edges nx.draw_networkx_edges(G,pos,edgelist=elarge, width=1) nx.draw_networkx_edges(G,pos,edgelist=esmall, width=1,alpha=0.5,edge_color='b',style='dashed') plt.axis('off') plt.savefig("transaction_network.png") # save as png plt.show() # display
def test_smoke_empty_graph(self): G = [] vpos = nx.random_layout(G) vpos = nx.circular_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) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
def test_smoke_string(self): G = self.Gs vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.spectral_layout(G) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G) vpos = nx.kamada_kawai_layout(G, dim=1)
def draw_graph(graph, labels=None, graph_layout='spectral', node_size=1600, node_color='red', node_alpha=0.3, node_text_size=10, 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], color='green') # 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(graph)) edge_labels = zip(graph, labels) # show graph plt.show()
def do_sub_print(self, arg): "Visualizes first-degree relations relations of a node\nUsage: subprint <person_uid>" labels2 = {} edgelabels2 = collections.OrderedDict() Y=nx.DiGraph() for v in self.G.get_first_degree_relatives(self.G.person_list[int(parse(arg)[0])]): try: Y.nodes().index(v.uid) except: Y.add_node(v.uid) labels2[v.uid] = v.str_short() labels2[int(parse(arg)[0])] = self.G.person_list[int(parse(arg)[0])].str_short() for rel in self.G.get_persons_relations(self.G.person_list[int(parse(arg)[0])]): try: Y.edges().index(rel[0], rel[3]) except: Y.add_edge(rel[0], rel[3]) edgelabels2[rel[0], rel[3]] = r'${}$'.format(rel[1].name) pos=nx.spring_layout(Y, iterations= 3000) if len(parse(arg)) > 0: if parse(arg)[0] == "circular": pos=nx.circular_layout(Y) if parse(arg)[0] == "spectral": pos = nx.spectral_layout(Y) if parse(arg)[0] == "random": pos = nx.random_layout(Y) if parse(arg)[0] == "shell": pos = nx.shell_layout(Y) if parse(arg)[0] == "graphviz": pos = nx.graphviz_layout(Y) plt.title("First-Degree Relatives of {}".format(self.G.person_list[int(parse(arg)[0])].str_short())) nx.draw_networkx(G=Y, pos=pos, labels=labels2, font_size=14, style="dashed") nx.draw_networkx_edge_labels(Y,pos, edgelabels2, style="dashed") #nx.draw_circular(Y) #plt.axis("off") #plt.savefig("family_graph.png") # save as png mng = plt.get_current_fig_manager() mng.resize(*mng.window.maxsize()) plt.show() # display
def one_layout(self, func, kwargs): """Calculates one arbitrary layout""" if 'fixed' in kwargs.keys(): if not kwargs['fixed'] is None: kwargs['pos'] = nx.random_layout(self.G, dim=kwargs['dim']) if func == 'dh_spring_layout': return self.dh_spring_layout(self.G, **kwargs) elif func == 'draw_graphviz': return graphviz_layout(self.G, **kwargs) else: return getattr(nx, func)(self.G, **kwargs)
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)
def do_print(self, arg): "Visualizes the family graph\nUsage: print" labels2 = {} node_sizes=[] edgelabels2 = collections.OrderedDict() Y=nx.DiGraph() for k, v in self.G.person_list.items(): try: Y.nodes().index(v.uid) except: Y.add_node(v.uid) labels2[v.uid] = v.str_short() node_sizes.append(1200/(math.pow(2, self.G.get_level(v)))) for rel in self.G.relation_list: try: Y.edges().index(rel[0], rel[3]) except: Y.add_edge(rel[0], rel[3]) edgelabels2[rel[0], rel[3]] = r'${}$'.format(rel[1].name) pos=nx.spring_layout(Y, iterations= 3000) if len(parse(arg)) > 0: if parse(arg)[0] == "circular": pos=nx.circular_layout(Y) if parse(arg)[0] == "spectral": pos = nx.spectral_layout(Y) if parse(arg)[0] == "random": pos = nx.random_layout(Y) if parse(arg)[0] == "shell": pos = nx.shell_layout(Y) if parse(arg)[0] == "graphviz": pos = nx.graphviz_layout(Y) plt.title("Family Graph") nx.draw_networkx(G=Y, pos=pos, labels=labels2, font_size=14, style="dashed", node_size=node_sizes) nx.draw_networkx_edge_labels(Y,pos, edgelabels2, style="dashed") #nx.draw_circular(Y) #plt.axis("off") #plt.savefig("family_graph.png") # save as png mng = plt.get_current_fig_manager() mng.resize(*mng.window.maxsize()) plt.show() # display
def engine_picker(G: Graph, engine: str, node_mode: bool = False): """Generate a position dict.""" if not node_mode: G_ = Graph() nodes = {i: edge for i, edge in edges_view(G)} for i, (l1, l2) in nodes.items(): for j, edge in nodes.items(): if i == j: continue if (l1 in edge) or (l2 in edge): G_.add_edge(i, j) H = G_ else: H = G if type(engine) != str: return engine if engine == "random": E = {k: (x * 200, y * 200) for k, (x, y) in random_layout(H).items()} elif engine == "shell": E = shell_layout(H, scale=100) elif engine == "circular": E = circular_layout(H, scale=100) elif engine == "spring": E = spring_layout(H, scale=100) elif engine == "spectral": E = spectral_layout(H, scale=100) else: try: E = nx_pydot.graphviz_layout(H, prog=engine) except: raise EngineError("No Graphviz") x_max = -inf x_min = inf y_max = -inf y_min = inf for x, y in E.values(): x = round(float(x), 4) y = round(float(y), 4) if x > x_max: x_max = x if x < x_min: x_min = x if y > y_max: y_max = y if y < y_min: y_min = y x_cen = (x_max + x_min) / 2 y_cen = (y_max + y_min) / 2 pos = { node: (round(float(x), 4) - x_cen, round(float(y), 4) - y_cen) for node, (x, y) in E.items() } return pos
def route_get_graph_figure(game): games = get_game_dict() G, color_map = generate_games_graph(games[game]) positions = nx.random_layout(G) nx.set_node_attributes(G, positions, 'pos') node_trace = create_node_trace(G, False) edge_trace = create_edge_trace(G) node_trace['marker']['color'] = color_map routes_add_color_and_hover_text(G, node_trace) fig = create_figure(node_trace, edge_trace) return G, fig
def show_nwk(self): pos = nx.random_layout(self.nwk_graph) labels = {} for node in self.nwk_graph.nodes: if type(node) == person.Person: labels[node] = node.id nx.draw(self.nwk_graph, pos=pos, with_labels=False) nx.draw_networkx_labels(self.nwk_graph, pos=pos, labels=labels, font_size=12) plt.show()
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) sc(nx.kamada_kawai_layout(G), scale=1, center=c)
def draw_graph(G, directed): """ This function draws the network :param G: nx graph or DiGraph :param directed: True if we want to draw the arrows of the graph for directed graph otherwise - False :return: """ pos = nx.random_layout(G) nx.draw(nx.Graph(G), pos) nx.draw_networkx_edges(G, pos, arrows=directed) plt.show()
def test_edge_color_string_with_gloabl_alpha_undirected(): edge_collection = nx.draw_networkx_edges( barbell, pos=nx.random_layout(barbell), edgelist=[(0, 1), (1, 2)], edge_color="purple", alpha=0.2, ) ec = edge_collection.get_color().squeeze() # as rgba tuple assert len(edge_collection.get_paths()) == 2 assert mpl.colors.same_color(ec[:-1], "purple") assert ec[-1] == 0.2
def plot_graph(G): edge_labels = dict([(( u, v, ), d['weight']) for u, v, d in G.edges(data=True)]) plt.figure(figsize=(18, 18)) random_pos = nx.random_layout(G, seed=0) pos = nx.spring_layout(G, pos=random_pos) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw_networkx(G, pos, node_size=3000) pylab.show()
def get_graph_plot(self, graph_layout: str, mark_closures: bool): """ Function for displaying the Markov chain as a graph :param graph_layout: layout directive of the graph :param mark_closures: Possibility to highlight closures in the graph :return: Plot of the Markov chain graph """ figure = plt.figure() colors = [ "red", "green", "blue", "#FF9400", "#71F8FF", "#80E868", "#FFB400", "E93FFF", "#DFFF47" ] graph = self.get_markov_chain().get_graph() if graph is None: (V, E) = self.calculate_graph() self.get_markov_chain().set_graph((V, E)) else: (V, E) = graph closures = self.get_markov_chain().get_closures() for closure in closures: colors.append("#000000") if not closures: closures = self.closures((V, E)) self.get_markov_chain().set_closures(closures) G = nx.DiGraph() E = [(str(e[0]), str(e[1])) for e in list(E)] G.add_edges_from(E) color_map = [] num_closures = len(closures) for node in G: color = "#000000" if mark_closures: for index in range(num_closures): if node in [str(v) for v in closures[index]]: color = colors[index] color_map.append(color) if graph_layout == "Spring layout": pos = nx.spring_layout(G, scale=2) elif graph_layout == "Circular layout": pos = nx.circular_layout(G, scale=2) elif graph_layout == "Spectral layout": pos = nx.spectral_layout(G, scale=2) else: pos = nx.random_layout(G) nodes = nx.draw_networkx_nodes(G, pos, node_color="w", node_size=600) nodes.set_edgecolor(color_map) nx.draw_networkx_labels(G, pos, color=color_map) nx.draw_networkx_edges(G, pos, arrows=True, arrowsize=20) return figure
def __init__(self, graph=None, voting='simple', clock='discrete', nbeliefs=2, visualization='shell', redraw=False): """ Construct a VoterModel. Parameters: graph: a networkx graph representing the model connectivity automatically generates an E-R(50, 0.125) graph if None voting: string representing the voting and belief update method valid options are: {simple, probability, weighted_prob} clock: string representing the time scale at which voters decide to change their belief (discrete or exponential) nbeliefs: the number of possible beliefs must be 2 for now visualization: string representing the visualization method redraw: boolean which is true if visualization plots should be redrawn on the same axes and false otherwise """ if graph is None: self.graph = nx.erdos_renyi_graph(50, 0.125) else: self.graph = graph self.clock = clock assert voting in Voter.voting_methods, "voting method must be in {}".format(Voter.voting_methods) self.voting = voting assert nbeliefs == 2, "only 2 beliefs allowed for now" self.nbeliefs = nbeliefs assert visualization in self.visualization_methods, "visualization method must be in {}".format(self.visualization_methods) self.visualization = visualization self._voters = [] self.redraw = redraw self.node_pos = None if self.visualization == 'shell': pass elif self.visualization == 'random': self.node_pos=nx.random_layout(self.graph) elif self.visualization == 'kamada_kawai': pass elif self.visualization == 'spring': self.node_pos=nx.spring_layout(self.graph) elif self.visualization == 'spectral': self.node_pos=nx.spectral_layout(self.graph) elif self.visualization == 'circular': self.node_pos=nx.circular_layout(self.graph) self.init_method = None