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 initialize(): G.add_node("A") G.add_node("B") G.add_node("C") G.add_node("D") G.add_node("E") G.add_node("F") labels = {k: k for k in G.nodes()} G.add_edge("A", "F", weight=1) G.add_edge("A", "E", weight=3) G.add_edge("A", "C", weight=4) G.add_edge("F", "B", weight=3) G.add_edge("F", "E", weight=2) G.add_edge("B", "D", weight=3) G.add_edge("B", "E", weight=2) G.add_edge("E", "D", weight=4) G.add_edge("E", "C", weight=2) G.add_edge("C", "D", weight=1) labels = nx.get_edge_attributes(G, "weight") plt.title("Single-Router Network") nx.draw(G, pos=nx.spectral_layout(G)) nx.draw_networkx(G, with_labels=True, pos=nx.spectral_layout(G)) nx.draw_networkx_edge_labels(G, pos=nx.spectral_layout(G), edge_labels=labels) plt.show()
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.spectral_layout(G) vpos = nx.spectral_layout(self.bigG) vpos = nx.shell_layout(G)
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(self.bigG) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(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(self, layout="graphviz"): """ Lay out and draw graph. Parameters ---------- layout : string ("graphviz") layout method. Default is "graphviz", which also requires installation of pygraphviz. """ if layout == "graphviz": pos = nx.graphviz_layout(self.graph) elif layout == "spring": pos = nx.spring_layout(self.graph) elif layout == "spectral": pos = nx.spectral_layout(self.graph) elif layout == "circular": pos = nx.circular_layout(self.graph) normal = [] msouter = [] minus = [] for node in self.graph.nodes(): if isinstance(node, paths.TISEnsemble): normal.append(node) elif isinstance(node, paths.MinusInterfaceEnsemble): minus.append(node) else: msouter.append(node) nx.draw_networkx_nodes(self.graph, pos, nodelist=normal, node_color="r", node_size=500) nx.draw_networkx_nodes(self.graph, pos, nodelist=minus, node_color="b", node_size=500) nx.draw_networkx_nodes(self.graph, pos, nodelist=msouter, node_color="g", node_size=500) nx.draw_networkx_edges(self.graph, pos, width=self.weights)
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 main(): base_layout = [("value", 32)] packed_layout = structuring.pack_layout(base_layout, pack_factor) rawbits_layout = [("value", 32*pack_factor)] source = SimActor(source_gen(), ("source", Source, base_layout)) sink = SimActor(sink_gen(), ("sink", Sink, base_layout)) # A tortuous way of passing integer tokens. packer = structuring.Pack(base_layout, pack_factor) to_raw = structuring.Cast(packed_layout, rawbits_layout) from_raw = structuring.Cast(rawbits_layout, packed_layout) unpacker = structuring.Unpack(pack_factor, base_layout) g = DataFlowGraph() g.add_connection(source, packer) g.add_connection(packer, to_raw) g.add_connection(to_raw, from_raw) g.add_connection(from_raw, unpacker) g.add_connection(unpacker, sink) comp = CompositeActor(g) reporter = perftools.DFGReporter(g) fragment = comp.get_fragment() + reporter.get_fragment() sim = Simulator(fragment, Runner()) sim.run(1000) g_layout = nx.spectral_layout(g) nx.draw(g, g_layout) nx.draw_networkx_edge_labels(g, g_layout, reporter.get_edge_labels()) plt.show()
def prepare_plot(graph): """ Prepares a Matplotlib plot for further handling :param graph: datamodel.base.Graph instance :return: None """ G = graph.nxgraph # Color map for nodes: color is proportional to depth level # http://matplotlib.org/examples/color/colormaps_reference.html depth_levels_from_root = nx.shortest_path_length(G, graph.root_node) vmax = 1. colormap = plt.get_cmap('BuGn') step = 1./len(graph) node_colors = [vmax - step * depth_levels_from_root[n] for n in G.nodes()] # Draw! # https://networkx.github.io/documentation/networkx-1.10/reference/drawing.html pos = nx.spectral_layout(G) nx.draw_networkx_labels(G, pos, labels=dict([(n, n.name) for n in G.nodes()]), font_weight='bold', font_color='orangered') nx.draw_networkx_nodes(G, pos, node_size=2000, cmap=colormap, vmin=0., vmax=vmax, node_color=node_colors) nx.draw_networkx_edge_labels(G, pos, edge_labels=dict([((u, v,), d['name']) for u, v, d in G.edges(data=True)])) nx.draw_networkx_edges(G, pos, edgelist=[edge for edge in G.edges()], arrows=True)
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_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, 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(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 setup_space(self): """ Method to setup our space. """ # Initialize a space with a grid network self.g = nx.grid_graph(dim=self.size) self.g=self.g.to_directed() # Set Pheromones print 'Setting up network' capacity_pheromone_list=[self.initial_pheromone]*len(self.capacities[0])*2 capacity_pheromone_list.extend([self.initial_pheromone]*len(self.capacities[1])*2) for e in self.g.edges_iter(): self.g.add_edge(e[0],e[1],max_capacity=self.edge_capacity) self.g.add_edge(e[0],e[1],capacity=0) #initial capacity self.g.add_edge(e[0],e[1],edge_pheromone=[self.initial_pheromone]*2*2) #pheromone per edge self.g.add_edge(e[0],e[1],capacity_pheromone=capacity_pheromone_list) #pheromone per capacity for n in self.g.nodes_iter(): neighbors_n=self.g.neighbors(n) branch_pheromone_list=[] branch_pheromone_list=[self.initial_pheromone] branch_pheromone_list.extend([self.initial_pheromone*.5]*(len(neighbors_n)-1)) self.g.add_node(n,branch_pheromone=branch_pheromone_list*2*2) termination_pheromone_list=[self.initial_termination*0.25,self.initial_termination]*2*2 self.g.add_node(n,termination_pheromone=termination_pheromone_list) # Set layout self.g_layout = nx.spectral_layout(self.g)
def partieAleatoire(decks): partie = [decksString(decks)] enJeu = [] F = nx.DiGraph() previous = decksString(decks) while decks[0] != [] and decks[1] != []: decks, enJeu, gagnant = jouerTour(decks, enJeu) strategies = permutationsSansRepetition(enJeu) enJeu = [] decks[gagnant] += strategies[r.randint(0,len(strategies)-1)] visu = decksString(decks) partie += [visu] F.add_edge(previous,visu) previous = visu pos = nx.spectral_layout(F) plt.figure(facecolor = 'w') plt.axis('off') nx.draw_networkx_edges(F,pos,alpha=0.7) nx.draw_networkx_labels(F,pos) plt.show() return partie
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(nx_graph_orig, nx_graph_new, nx_labels, opts): """ Try to draw a nice graph """ # intersection between the original and targeted graph, with the trick to conserve attributes intersect_graph = nx_graph_orig.copy() if nx_graph_new: intersect_graph.remove_nodes_from(n for n in nx_graph_orig if n not in nx_graph_new) # printing edges data #print intersect_graph.edges(data=True) pos = nx.spectral_layout(intersect_graph) nx.draw_networkx_nodes(intersect_graph,pos,node_size=700) nx.draw_networkx_edges(intersect_graph, pos, width=6) nx.draw_networkx_labels(intersect_graph, pos, font_size=14, alpha=0, font_color='yellow') plt.axis('off') if opts.graph: plt.show() if opts.output_graph: figure_abs_path = os.path.join(os.getcwdu(), opts.output_graph) plt.savefig(figure_abs_path, format='png') print "[+] Graph saved at: %s" % figure_abs_path return
def create_simple_graph(self,name): import networkx as nx G=nx.Graph() for i,r in enumerate(self.reslist): G.add_node(i+1,name=r.name) print G.nodes() h = self.hbond_matrix() nr = numpy.size(h,0) for i in range(nr): for j in range(i+1,nr): if GenericResidue.touching(self.reslist[i], self.reslist[j],2.8): print 'adding edge',i+1,j+1 G.add_edge(i+1,j+1,name="special") # pos0=nx.spectral_layout(G) # pos=nx.spring_layout(G,iterations=500,pos=pos0) # pos=nx.spring_layout(G,iterations=500) # nx.draw_shell(G) pos0=nx.spectral_layout(G) pos=nx.spring_layout(G,iterations=500,pos=pos0) # pos=nx.graphviz_layout(G,root=1,prog='dot') # nx.draw(G) nx.draw_networkx(G,pos) plt.axis('off') plt.savefig(name)
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, 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 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 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 plot_graphs(graphs,t): num_graphs = len(graphs) grange = range(0,num_graphs) for g in grange: plt.figure(str(g)+str(t)) plt.title("Time " + str(t) + " Graph " + str(g)) edge_labels_1 = nx.get_edge_attributes(graphs[g],'weight') if g < 3: nx.draw(graphs[g],nx.spectral_layout(graphs[g],weight=None),with_labels = True) nx.draw_networkx_edge_labels(graphs[g],nx.spectral_layout(graphs[g],weight=None),edge_labels=edge_labels_1) else: nx.draw(graphs[g],nx.spectral_layout(graphs[g],weight=None),with_labels = True) nx.draw_networkx_edge_labels(graphs[g],nx.spectral_layout(graphs[g],weight=None),edge_labels=edge_labels_1) plt.savefig("debug_graph_plots/graph_"+str(t)+"_"+str(g)+".pdf") plt.close()
def plot(self): """Visualize the graph.""" try: import networkx as nx import matplotlib.pyplot as plt except Exception as e: print('Can not plot graph: {}'.format(e)) return gnx = nx.Graph() if self.is_undirected else nx.DiGraph() vlbs = {vid: v.vlb for vid, v in self.vertices.items()} elbs = {} for vid, v in self.vertices.items(): gnx.add_node(vid, label=v.vlb) for vid, v in self.vertices.items(): for to, e in v.edges.items(): if (not self.is_undirected) or vid < to: gnx.add_edge(vid, to, label=e.elb) elbs[(vid, to)] = e.elb fsize = (min(16, 1 * len(self.vertices)), min(16, 1 * len(self.vertices))) plt.figure(3, figsize=fsize) pos = nx.spectral_layout(gnx) nx.draw_networkx(gnx, pos, arrows=True, with_labels=True, labels=vlbs) nx.draw_networkx_edge_labels(gnx, pos, edge_labels=elbs) plt.show()
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 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 __grid_layout__(width, height): # Construct the width + 1 by height + 1 grid with directed edges. G = nx.grid_2d_graph(width + 1, height + 1) G = nx.DiGraph(G) pos = nx.spectral_layout(G) return (G, pos)
def main(): tb = TB() sim = Simulator(tb).run(1000) g_layout = nx.spectral_layout(tb.g) nx.draw(tb.g, g_layout) nx.draw_networkx_edge_labels(tb.g, g_layout, tb.reporter.get_edge_labels()) plt.show()
def draw_graph_list(G_list, row, col, fname = 'figures/test', layout='spring', is_single=False,k=1,node_size=55,alpha=1,width=1.3): # # draw graph view # from pylab import rcParams # rcParams['figure.figsize'] = 12,3 plt.switch_backend('agg') for i,G in enumerate(G_list): plt.subplot(row,col,i+1) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) # if i%2==0: # plt.title('real nodes: '+str(G.number_of_nodes()), fontsize = 4) # else: # plt.title('pred nodes: '+str(G.number_of_nodes()), fontsize = 4) # plt.title('num of nodes: '+str(G.number_of_nodes()), fontsize = 4) # parts = community.best_partition(G) # values = [parts.get(node) for node in G.nodes()] # colors = [] # for i in range(len(values)): # if values[i] == 0: # colors.append('red') # if values[i] == 1: # colors.append('green') # if values[i] == 2: # colors.append('blue') # if values[i] == 3: # colors.append('yellow') # if values[i] == 4: # colors.append('orange') # if values[i] == 5: # colors.append('pink') # if values[i] == 6: # colors.append('black') plt.axis("off") if layout=='spring': pos = nx.spring_layout(G,k=k/np.sqrt(G.number_of_nodes()),iterations=100) # pos = nx.spring_layout(G) elif layout=='spectral': pos = nx.spectral_layout(G) # # nx.draw_networkx(G, with_labels=True, node_size=2, width=0.15, font_size = 1.5, node_color=colors,pos=pos) # nx.draw_networkx(G, with_labels=False, node_size=1.5, width=0.2, font_size = 1.5, linewidths=0.2, node_color = 'k',pos=pos,alpha=0.2) if is_single: # node_size default 60, edge_width default 1.5 nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='#336699', alpha=1, linewidths=0, font_size=0) nx.draw_networkx_edges(G, pos, alpha=alpha, width=width) else: nx.draw_networkx_nodes(G, pos, node_size=1.5, node_color='#336699',alpha=1, linewidths=0.2, font_size = 1.5) nx.draw_networkx_edges(G, pos, alpha=0.3,width=0.2) # plt.axis('off') # plt.title('Complete Graph of Odd-degree Nodes') # plt.show() plt.tight_layout() plt.savefig(fname+'.png', dpi=600) plt.close()
def drawGraph(): time.sleep(15) log.info("Network's topology graph:") log.info(' -> ingress switches: {}'.format(list(ingress))) log.info(' -> egress switches: {}'.format(list(egress))) nx.draw_spectral(graph) nx.draw_networkx_edge_labels(graph, pos=nx.spectral_layout(graph)) #nx.draw_circular(graph) #nx.draw_networkx_edge_labels(graph, pos=nx.circular_layout(graph)) #nx.draw_shell(graph) #nx.draw_networkx_edge_labels(graph, pos=nx.shell_layout(graph)) plt.show()
def test_smoke_string(self): G = self.Gs 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.spiral_layout(G) vpos = nx.kamada_kawai_layout(G) vpos = nx.kamada_kawai_layout(G, dim=1)
def PrintGraph(G): pos = nx.spectral_layout(G) nx.draw_networkx_nodes(G, pos, node_size=60, node_color='b', node_shape='o') nx.draw_networkx_edges(G, pos, width=1, edge_color='black') edge_labels = nx.draw_networkx_edge_labels(G, pos, font_size=7, label_pos=.5)
def save_graph_drawing(graph, filename, labels=None, graph_layout='spring', node_size=1600, node_alpha=0.3, node_text_size=12, edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): figure, axis = plt.subplots() if graph_layout == 'shell': graph_pos = nx.shell_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.spring_layout(graph) colors = [] for vertex in graph.nodes(): try: colors.append(graph.node[vertex]['color']) except KeyError: colors.append('white') nx.draw_networkx_nodes(graph, graph_pos, node_size=node_size, alpha=node_alpha, node_color=colors, ax=axis) nx.draw_networkx_edges(graph, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color='blue', arrows=True, ax=axis) nx.draw_networkx_labels(graph, graph_pos, font_size=node_text_size, font_family=text_font, ax=axis) plt.axis('off') plt.savefig(filename)
def showGraphList(gList, gLabels, layout="spring", nodeSize=50, nodeColor1='blue', transp=0.5): nAx = len(gList) f = gr.figure(figsize=(17, 11)) rows = 2 cols = sc.ceil(nAx / rows) ax = list() gr.ioff() for n in sc.arange(nAx): ax.append(f.add_subplot(rows, cols, n + 1)) if layout == "spring": nx.draw(gList[n], ax=ax[n], pos=nx.spring_layout(gList[n]), node_size=nodeSize, node_color=nodeColor1, alpha=transp) if layout == "shel": nx.draw(gList[n], ax=ax[n], pos=nx.shell_layout(gList[n]), node_size=nodeSize, node_color=nodeColor1, alpha=transp) if layout == "random": nx.draw(gList[n], ax=ax[n], pos=nx.random_layout(gList[n]), node_size=nodeSize, node_color=nodeColor1, alpha=transp) if layout == "circular": nx.draw(gList[n], ax=ax[n], pos=nx.circular_layout(gList[n]), node_size=nodeSize, node_color=nodeColor1, alpha=transp) if layout == "spectral": nx.draw(gList[n], ax=ax[n], pos=nx.spectral_layout(gList[n]), node_size=nodeSize, node_color=nodeColor1, alpha=transp) ax[n].set_title(gLabels[n]) gr.ion() gr.draw() return f
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) if self.scipy is not None: sc(nx.kamada_kawai_layout(G), scale=1, center=c)
def test_spectral_for_small_graphs(self): G = nx.Graph() vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G, center=(2, 3)) G.add_node(0) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G, center=(2, 3)) G.add_node(1) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G, center=(2, 3)) # 3 nodes should allow eigensolvers to work G.add_node(2) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G, center=(2, 3))
def draw_graph(G, labels=None, graph_layout='spring', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=9, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): ''' From SO - graph drawing function from NetworkX ''' # 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 = 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 __init__(self, graph, layout="spring"): self.__graph = Graph() self.__graph.append_graph(graph) self.element_colors = [ '#000000', '#0000FF', '#13E853', # Subgraphs 1's color '#FF0000', # Subgraphs 2's color '#E67E22', '#9B59B6', '#2980B9', '#1ABC9C', '#27AE60', '#F1C40F', '#7F8C8D', '#C0392B', '#E74C3C', '#8E44AD', '#3498DB', '#16A085', '#2ECC71', '#F39C12', '#D35400' ] self.default_node_size = 15 self.default_color = '#C2C2C2' self.__graph_x = nx.Graph() # self.__node_weighted = graph.is_node_weighted() if graph.is_node_weighted(): for node in graph: self.__graph_x.add_node(node, weight=graph[node][0]) for adj_node, weight in graph[node][1].iteritems(): self.__graph_x.add_edge(node, adj_node, weight=weight) else: for node in graph: self.__graph_x.add_node(node) for adj_node, weight in graph[node].iteritems(): self.__graph_x.add_edge(node, adj_node, weight=weight) if layout == "spectral": # Spectral layout looks better for grid graphs. self.pos = nx.spectral_layout(self.__graph_x) elif layout == "kamada_kawai": self.pos = nx.kamada_kawai_layout(self.__graph_x) else: self.pos = nx.spring_layout(self.__graph_x)
def DrawGraph(Achievement, layout = "random"): if layout == "random": pos = nx.random_layout(Achievement) if layout == "shell": pos = nx.shell_layout(Achievement) if layout == "spring": pos = nx.spring_layout(Achievement) if layout == "spectral": pos = nx.spectral_layout(Achievement) # for nodes auth1 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] ==1] auth2 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] ==2] auth3 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] ==3] auth4 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] ==4] auth5_10 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] >=5 and d["paper_num"] < 11 ] auth11_20 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] >=11 and d["paper_num"] < 21 ] auth21_30 = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] >=21 and d["paper_num"] < 31 ] auth31_ = [ auth for (auth, d) in Achievement.nodes(data = True) if d["paper_num"] >=31] nx.draw_networkx_nodes(Achievement,pos,nodelist = auth1, node_size=50) nx.draw_networkx_nodes(Achievement,pos,nodelist = auth2, node_size=100, node_color = 'g') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth3, node_size=200, node_color = 'y') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth4, node_size=300, node_color = 'b') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth5_10, node_size=400, node_color = 'c') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth11_20, node_size=600, node_color = 'm') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth21_30, node_size=800, node_color = 'k') nx.draw_networkx_nodes(Achievement,pos,nodelist = auth31_, node_size=1000, node_color = 'k') # for edges edge1 = [ (u,v) for (u,v,d) in Achievement.edges(data = True) if d["freq"] == 1] edge2 = [ (u,v) for (u,v,d) in Achievement.edges(data = True) if d["freq"] == 2] edge3 = [ (u,v) for (u,v,d) in Achievement.edges(data = True) if d["freq"] == 3] nx.draw_networkx_edges(Achievement, pos, edgelist = edge1, width = 1, edge_color = "grey") nx.draw_networkx_edges(Achievement, pos, edgelist = edge2, width = 3, edge_color = 'b') nx.draw_networkx_edges(Achievement, pos, edgelist = edge3, width = 10, edge_color = "m") # for labels names = {} for v, d in Achievement.nodes(data = True): names[v] = d["full_name"] nx.draw_networkx_labels(Achievement,pos,names,font_size=2, color ="w")
def test_center_parameter(self): G = nx.path_graph(1) vpos = nx.random_layout(G, center=(1, 1)) vpos = nx.circular_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.spring_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.spectral_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.shell_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1))
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 draw_bw(G): pos = nx.spectral_layout(G) pos = nx.kamada_kawai_layout(G, pos=pos, weight="mass") font_size = 10 if G.number_of_nodes() < 10 else 6 alpha = 1 if G.number_of_nodes() < 150 else 0.855 nx.draw(G, pos=pos, with_labels=True, node_color='w', font_size=font_size, width=0.2, alpha=alpha) st.pyplot()
def draw_graph(): graph_pos = nx.spectral_layout(graph) # # draw nodes, edges and labels nx.draw_networkx_nodes(graph, graph_pos, node_size=5, node_color='blue', alpha=0.3) nx.draw_networkx_edges(graph, graph_pos) # nx.draw_networkx_labels(G, graph_pos, font_size=12, font_family='sans-serif') # # # show graph # plt.show()a # nx.draw(graph) plt.savefig("narrower_all_graph.png") plt.show()
def layout(self, value): if value == 'circular': self.__pos = nx.circular_layout(self.__nx_graph) elif value == 'shell': self.__pos = nx.shell_layout(self.__nx_graph) elif value == 'spectral': self.__pos = nx.spectral_layout(self.__nx_graph) elif value == 'spring': self.__pos = nx.spring_layout(self.__nx_graph, k=1, iterations=50) else: self.__pos = nx.random_layout(self.__nx_graph) value = 'random' self._layout = value
def SpectralLayout(overlap, graph, baseoutput): layout = nx.spectral_layout(graph, dim=5) with open(baseoutput + '-SLL', 'w') as output: for ov in overlap: edge = ov v1 = layout.get(edge[0]) v2 = layout.get(edge[1]) distance = 0 for z in range(1, 5): distance = distance + math.pow((v1[z] - v2[z]), 2) distance = math.sqrt(distance) SL = distance output.write(str(SL) + '\n')
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) sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
def draw_graph_list(G_list, row, col, fname='exp/gen_graph.png', layout='spring', is_single=False, k=1, node_size=55, alpha=1, width=1.3): plt.switch_backend('agg') for i, G in enumerate(G_list): plt.subplot(row, col, i + 1) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) # plt.axis("off") # turn off axis label plt.xticks([]) plt.yticks([]) if layout == 'spring': pos = nx.spring_layout( G, k=k / np.sqrt(G.number_of_nodes()), iterations=100) elif layout == 'spectral': pos = nx.spectral_layout(G) if is_single: # node_size default 60, edge_width default 1.5 nx.draw_networkx_nodes( G, pos, node_size=node_size, node_color='#336699', alpha=1, linewidths=0, font_size=0) nx.draw_networkx_edges(G, pos, alpha=alpha, width=width) else: nx.draw_networkx_nodes( G, pos, node_size=1.5, node_color='#336699', alpha=1, linewidths=0.2, font_size=1.5) nx.draw_networkx_edges(G, pos, alpha=0.3, width=0.2) plt.tight_layout() plt.savefig(fname, dpi=300) plt.close()
def draw_topology(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'): G = nx.Graph() for edge in graph: G.add_edge(edge[0], edge[1]) 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_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 = dict(zip(graph, labels)) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, label_pos=edge_text_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 main(): n = int(sys.argv[1]) print(f"Creating a tree with size {n}") G = nx.random_tree(n) update = threading.Event() draw_delay = threading.Event() plt.ion() fig = plt.figure(num=0) topology = Topology() topology.construct_from_graph(G, FireWireNode, P2PFIFOPerfectChannel) topology.start() FireWireNode.callback = update FireWireNode.draw_delay = draw_delay while True: update.wait() node_colours = list() G = Topology().G pos = nx.spectral_layout(G, center=(0, 0)) for nodeID in Topology().nodes: node = Topology().nodes[nodeID] if node.is_leader: node_colours.append(LEADER_NODE_COLOUR) elif node.in_root_contention: node_colours.append(CONTENDING_NODE_COLOUR) elif node.is_terminated: node_colours.append(PASSIVE_NODE_COLOUR) elif not node.is_terminated: node_colours.append(ACTIVE_NODE_COLOUR) nx.draw( G, pos, node_color=node_colours, edge_color=EDGE_COLOUR, with_labels=True, font_weight="bold", ) fig.canvas.draw() fig.canvas.flush_events() fig.clear() update.clear() draw_delay.set() sleep(1.0 / FPS)
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 draw_graph_list_separate(G_list, fname='exp/gen_graph', layout='spring', is_single=False, k=1, node_size=55, alpha=1, width=1.3): for i, G in enumerate(G_list): plt.switch_backend('agg') plt.axis("off") # turn off axis label # plt.xticks([]) # plt.yticks([]) if layout == 'spring': pos = nx.spring_layout( G, k=k / np.sqrt(G.number_of_nodes()), iterations=100) elif layout == 'spectral': pos = nx.spectral_layout(G) if is_single: # node_size default 60, edge_width default 1.5 nx.draw_networkx_nodes( G, pos, node_size=node_size, node_color='#336699', alpha=1, linewidths=0, font_size=0) nx.draw_networkx_edges(G, pos, alpha=alpha, width=width) else: nx.draw_networkx_nodes( G, pos, node_size=1.5, node_color='#336699', alpha=1, linewidths=0.2, font_size=1.5) nx.draw_networkx_edges(G, pos, alpha=0.3, width=0.2) plt.draw() plt.tight_layout() plt.savefig(fname+'_{:03d}.png'.format(i), dpi=300) plt.close()
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_graph(G): import matplotlib.pyplot as plt import pylab edge_labels = dict([((u, v,), d['weight']) for u, v, d in G.edges(data=True)]) node_labels = {node: node for node in G.nodes()} pos = nx.spectral_layout(G) nx.draw_networkx_labels(G, pos, labels=node_labels) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw(G, pos, node_size=500, edge_cmap=plt.cm.Reds) plt.savefig('Finals_Q2_Graph.png') pylab.title("Input Graph") pylab.show()
def show_graph(graph, agentA, agentB, goalA, goalB): layout = nx.spectral_layout(graph) for k in layout: layout[k] = index2pos(k) labels = dict((n, n) for n in range(BOARD_DIM**2)) labels[agentA] = "A" labels[agentB] = "B" labels[goalA] = "gA" labels[goalB] = "gB" nx.draw(graph, labels=labels, with_labels=True, pos=layout) plt.show() plt.close()
def __init__( self , graph , positions = None ) : """ Parameters --------------- graph : networkx graph the graph for plotting positions : list set of positions. Currently only supports plotting in 2D. """ self.graph = graph if positions is not None and positions != 'spectral': #If we have more than 2 position coords then take only the first two: if len(positions[0]) != 2 : print("More than 2d found. Taking first two dimensions") self.positions = [ [ i[0] , i[1] ] for i in positions ] else : self.positions = positions #If positions are not specified use the spring layout: elif positions == None : self.positions=nx.spring_layout(graph) elif positions == 'spectral' : self.positions=nx.spectral_layout(graph) #Set default parameters: self.node_size = 35 self.node_line_width = 0.1 self.color_scheme = 'jet' self.edge_width = 1.0 self.node_color = 'b' self.node_shape = 'o' self.node_transparency = 1.0 self.edge_color = 'k' self.edge_style = 'dashed' #solid|dashed|dotted,dashdot self.edge_transparency = 1.0
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 __tutte_embedding(self, outter_face): """ Produces a list of positions for each vertice """ print("Creating a tutte embedding of the graph...") # a dictionary of node positions pos = {} tmp = nx.Graph() for edge in outter_face: edge_a, edge_b = edge tmp.add_edge(edge_a, edge_b) # ensures that outterface is a convex shape tmp_pos = nx.spectral_layout(tmp) print("Check: outer face is of convex shape...") pos.update(tmp_pos) outter_vertices = tmp.nodes() remaining_vertices = [ x for x in self.__graph.nodes() if x not in outter_vertices ] size = len(remaining_vertices) # create the the system of equations that will determine the x and y positions of # remaining vertices print("Creating system of linear equations...") a_list = [[0 for i in range(size)] for i in range(size)] # the elements of theses matrices are indexed by the remaining_vertices list b_list = [0 for i in range(size)] c_list = [[0 for i in range(size)] for i in range(size)] d_list = [0 for i in range(size)] print("Get coordinates of all nodes...") for rem in remaining_vertices: i = remaining_vertices.index(rem) neighbors = self.__graph.neighbors(rem) len_neighb = len([n for n in neighbors]) neighbors = self.__graph.neighbors(rem) a_list[i][i] = 1 c_list[i][i] = 1 for vertice in neighbors: if vertice in outter_vertices: b_list[i] += float(pos[vertice][0]) / len_neighb d_list[i] += float(pos[vertice][1]) / len_neighb else: j = remaining_vertices.index(vertice) a_list[i][j] = -(1 / float(len_neighb)) c_list[i][j] = -(1 / float(len_neighb)) x_coord = np.linalg.solve(a_list, b_list) y_coord = np.linalg.solve(c_list, d_list) for rem in remaining_vertices: i = remaining_vertices.index(rem) pos[rem] = [x_coord[i], y_coord[i]] print("Tutte embedding succesfully created.") return pos
def draw(self, x=None, observed=None, dependent=None): """Draw the Bayesian network. Arguments --------- x : str The source variable. observed : iterable of str The variables on which we condition. dependent : iterable of str The variables which are dependent on ``x`` given ``observed``. """ pos = nx.spectral_layout(self) nx.draw_networkx_edges(self, pos, edge_color=EDGE_COLOR, width=EDGE_WIDTH) if x or observed or dependent: rest = list( set(self.nodes()) - set([x]) - set(observed) - set(dependent)) else: rest = self.nodes() if rest: obj = nx.draw_networkx_nodes(self, pos, nodelist=rest, node_size=NODE_SIZE, node_color=NODE_COLOR_NORMAL) obj.set_linewidth(NODE_BORDER_WIDTH) obj.set_edgecolor(NODE_BORDER_COLOR) if x: obj = nx.draw_networkx_nodes(self, pos, nodelist=[x], node_size=3000, node_color=NODE_COLOR_SOURCE, node_shape=NODE_SHAPE_SOURCE) obj.set_linewidth(NODE_BORDER_WIDTH) obj.set_edgecolor(NODE_BORDER_COLOR) if observed: obj = nx.draw_networkx_nodes(self, pos, nodelist=list(observed), node_size=NODE_SIZE, node_color=NODE_COLOR_OBSERVED) obj.set_linewidth(NODE_BORDER_WIDTH) obj.set_edgecolor(NODE_BORDER_COLOR) if dependent: obj = nx.draw_networkx_nodes(self, pos, nodelist=list(dependent), node_size=NODE_SIZE, node_color=NODE_COLOR_REACHABLE) obj.set_linewidth(NODE_BORDER_WIDTH) obj.set_edgecolor(NODE_BORDER_COLOR) nx.draw_networkx_labels(self, pos, font_color=LABEL_COLOR)