我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用networkx.draw_networkx_labels()。
def draw_graph(gv, ge, name): Gr = nx.Graph() for i in range(N): Gr.add_node(i, pos=gv[i]) for i in range(N): for j in range(N): if ge[i][j]: Gr.add_edge(i,j) labels = dict() for i in range(N): labels[i] = str(i) pos=nx.get_node_attributes(Gr,'pos') nx.draw(Gr, pos=pos, node_size=400, with_labels=False) nx.draw_networkx_labels(Gr, pos, labels) plt.savefig(name)
def create_image(g, path): path = os.path.relpath(path) if pygraphviz: a = nx.nx_agraph.to_agraph(g) # ['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop'] a.layout(prog='neato', args="-Goverlap=false -Gsplines=true") # splines=true a.draw(path) elif plt: nodes = g.nodes(True) colors = [attrs['color'] for n, attrs in nodes] labels = {n: attrs['label'] for n, attrs in nodes} if graphviz_layout: pos = graphviz_layout(g) else: pos = nx.spring_layout(g) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color=colors, alpha=0.3) nx.draw_networkx_edges(g, pos, style='solid', alpha=0.2) nx.draw_networkx_labels(g, pos, labels, alpha=0.5) # plt.show() plt.imsave(path) # todo: this is not tested! print 'Image saved to', path
def save(self, path='out.png'): import networkx import matplotlib.pyplot as plt pos = networkx.spring_layout(self.graph, iterations=500) # pos = networkx.spectral_layout(self.graph) # pos = networkx.shell_layout(self.graph) # pos = networkx.fruchterman_reingold_layout(self.graph) nodelist = list(range(self.num_rooms)) networkx.draw_networkx_nodes(self.graph, pos, nodelist=nodelist) edgelist = sorted(self.edges - self.secret_edges) secret = sorted(self.secret_edges) networkx.draw_networkx_edges(self.graph, pos, edgelist=edgelist, edge_color='k') networkx.draw_networkx_edges(self.graph, pos, edgelist=secret, edge_color='r') networkx.draw_networkx_labels(self.graph, pos, self.labels) plt.savefig(path)
def Drawsubgraph(HG, DrawGraph): #Draw the graph #print HG.nodes() pos=nx.spring_layout(HG) nx.draw_networkx_edges(HG, pos, alpha=0.4) #nx.draw_networkx_labels(HG, pos, font_size=10, font_family='sans-serif') i = 0 colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' for key in DrawGraph.keys(): nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=20,node_color=colorList[i%len(colorList)]) i = i + 1 plt.title("Network Community Analysis") plt.show() ###========================================================================================
def drawcomgraph(HG, DrawGraph): #Draw the graph #print HG.nodes() pos=nx.spring_layout(HG) nx.draw_networkx_edges(HG, pos, alpha=0.4) nx.draw_networkx_labels(HG, pos, font_size=6, font_family='sans-serif') i = 0 colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' for key in DrawGraph.keys(): nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=100,node_color=colorList[i%len(colorList)]) i = i + 1 plt.title("Network Community Analysis") plt.show() #************************************************************************
def plot(self): # print(list(self.root.edge_list())) labels = {} for i, j in self.root.edge_list(): labels[i] = i labels[j] = j G = nx.Graph(self.root.edge_list()) pos = graphviz_layout(G, prog='dot') nx.draw(G, pos) nx.draw_networkx_labels(G, pos, labels) plt.show() # class BST_count(BST): # def __init__(self, url=None, file=None,tree=None): # if tree: # pass # else: # super(BST).__init__(url,file)
def plot_networkx(self, with_label=False, block=True): nx.draw_networkx_edges( self.G, self.pos, edge_color=self.edges_color(self.G.edges()), alpha=0.08 ) if with_label: nx.draw_networkx_labels( self.G, self.pos, font_size=8, font_color='r', alpha=0.2 ) nodes = self.G.nodes() nx.draw_networkx_nodes( self.G, self.pos, node_size=self.nodes_size(nodes), node_color=self.nodes_color(nodes), alpha=0.85 ) plt.axis('off') plt.show(block=block) plt.clf()
def draw_graph(edges): G = nx.DiGraph() G.add_edges_from(edges) values = [1.0 for node in G.nodes()] # Specify the edges you want here edge_colours = ['black' for edge in G.edges()] black_edges = [edge for edge in G.edges()] # Need to create a layout when doing # separate calls to draw nodes and edges pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('Reds'), node_color = values, node_size=4800) nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True) nx.draw_networkx_labels(G,pos,font_size=12,font_family='sans-serif') plt.axis('off') plt.show() # In[183]:
def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True): import matplotlib.pyplot as plt # pos = nx.spring_layout(self.graph) pos = nx.shell_layout(self.graph, dim=1024, scale=0.5) # pos = nx.random_layout(self.graph, dim=1024, scale=0.5) if label_edges: edge_labels = { (edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True) } nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5) if label_nodes: labels = {node[0]: node[1] for node in self.graph.nodes(data=True)} nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8) # nx.draw(self.graph, with_labels=True, arrows=True, node_size=80) nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80) plt.savefig(file_name, dpi=1024)
def plotRoadsGraphNetworkx(G): import matplotlib.pyplot as plt eoriginal=[(u,v) for (u,v,d) in G.edges(data=True) if d['level'] >= 3] enew=[(u,v) for (u,v,d) in G.edges(data=True) if d['level'] < 3] pos={} for n in G.nodes(): pos[n] = (G.node[n]['longitude'],G.node[n]['latitude']) # nodes nx.draw_networkx_nodes(G,pos,node_size=3) # edges nx.draw_networkx_edges(G,pos,edgelist=eoriginal,alpha=0.8,width=1) nx.draw_networkx_edges(G,pos,edgelist=enew,width=1,alpha=0.8,edge_color='r') # labels nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif') plt.show()
def draw_tier2(): print 'loading tier2 data' loadEntity(tier2filename) print 'entity size: ', len(entityList) G = nx.Graph() G.add_node(u'???') for entity in entityList: name = entity.name[0].decode('utf8') print name G.add_node(name) G.add_edge(u'???',name) for child in entity.child: cn = child.decode('utf8') G.add_node(cn) G.add_edge(name, cn) pos=nx.spring_layout(G) # positions for all nodes nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5) # labels nx.draw_networkx_labels(G,pos,font_size=15,font_family='sans-serif') plt.axis('off') plt.show() # draw tier 3 test
def draw_grid(ts, edgelabel='control', prop_colors=None, current_node=None): assert edgelabel is None or nx.is_weighted(ts.g, weight=edgelabel) pos = nx.get_node_attributes(ts.g, 'location') if current_node == 'init': current_node = next(ts.init.iterkeys()) colors = dict([(v, 'w') for v in ts.g]) if current_node: colors[current_node] = 'b' for v, d in ts.g.nodes_iter(data=True): if d['prop']: colors[v] = prop_colors[tuple(d['prop'])] colors = colors.values() labels = nx.get_node_attributes(ts.g, 'label') nx.draw(ts.g, pos=pos, node_color=colors) nx.draw_networkx_labels(ts.g, pos=pos, labels=labels) edge_labels = nx.get_edge_attributes(ts.g, edgelabel) nx.draw_networkx_edge_labels(ts.g, pos=pos, edge_labels=edge_labels)
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 show_graph_communities(graph, partition, color_map=None, with_labels=False): if color_map is None: color_map = generate_color_map(partition) pos = nx.spring_layout(graph,k=0.1,iterations=50) comm_nodes = utils.partition_to_comm_nodes_map(partition) for comm, nodes in comm_nodes.items(): nx.draw_networkx_nodes(graph, pos, nodelist=nodes, node_size=400, node_color=color_map.get(comm), label=comm, cmap=plt.cm.jet) if with_labels: nx.draw_networkx_labels(graph, pos, font_size=12) nx.draw_networkx_edges(graph, pos, alpha=0.3) plt.legend() plt.axis('off') plt.show()
def show_graph(graph, with_labels=False): pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=200, node_color='red') if with_labels: nx.draw_networkx_labels(graph, pos, font_size=12) nx.draw_networkx_edges(graph, pos, alpha=0.3) plt.axis('off') plt.show()
def ped_group(pedgraph, nlist, nscale=600, nalpha=0.95, nsize=15, ealpha=0.2, ewidth=0.3, ecolor="#000000", atName="attr1", atCol=4): ''' Receives a networkx graph and plots. - needs matplotlib package :param pedgraph: networkX graph object (pedigree) :param nscale: scale of the plot :param nalpha: node transparency :param nsize: node size :param ncolor: node color :param ealpha: edge transparency :param ewidth: edge width :param ecolor: edge color :return: ''' grpList = [line.strip() for line in open(nlist, 'r')] part = add_node_attribute("ped_testherd.in", pedgraph, atName=atName, atCol=atCol) values = [part.get(node) for node in grpList] pos = nx.spring_layout(pedgraph, scale=nscale) nx.draw_networkx_nodes(pedgraph, pos, nodelist=grpList, alpha=nalpha, node_color=values, node_size=nsize, linewidths=0.1, cmap=plt.get_cmap('Paired')) # label plot not feasable for larger networks # nx.draw_networkx_labels(pedgraph, pos) # nx.draw_networkx_edges(pedgraph, pos, alpha=ealpha, width=ewidth, edge_color=ecolor) plt.axis("off") plt.show()
def draw_transmat_graph(G, edge_threshold=0, lw=1, ec='0.2', node_size=15): num_states = G.number_of_nodes() edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)] edgewidth = np.array(edgewidth) edgewidth[edgewidth<edge_threshold] = 0 labels = {} labels[0] = '1' labels[1]= '2' labels[2]= '3' labels[num_states-1] = str(num_states) npos=circular_layout(G, scale=1, direction='CW') lpos=circular_layout(G, scale=1.15, direction='CW') nx.draw_networkx_edges(G, npos, alpha=0.8, width=edgewidth*lw, edge_color=ec) nx.draw_networkx_nodes(G, npos, node_size=node_size, node_color='k',alpha=0.8) ax = plt.gca() nx.draw_networkx_labels(G, lpos, labels, fontsize=18, ax=ax); # fontsize does not seem to work :/ ax.set_aspect('equal') return ax
def nx_plot(adj, pos, value): # input: adjacent matrix, position, value map label = np.arange(len(pos)) G=nx.from_numpy_matrix(adj) nx.draw_networkx_nodes(G, pos, node_color = value) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos) plt.ion() plt.show()
def nx_plot(adj, pos, value): # input: adjacent matrix, position, value map label = np.arange(len(pos)) G=nx.from_numpy_matrix(adj) nx.draw_networkx_nodes(G, pos, node_color = value) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, width=1.0) plt.ion() plt.show()
def nx_plot(adj, pos, value): # input: adjacent matrix, position, value map label = np.arange(len(pos)) G=nx.from_numpy_matrix(adj) nodes = nx.draw_networkx_nodes(G, pos, node_color=value, node_size=200) nodes.set_edgecolor('black') nx.draw_networkx_labels(G, pos, font_size=10) nx.draw_networkx_edges(G, pos, width=1.0) plt.ion() plt.show()
def view_city(self): pos = nx.circular_layout(self.city) node_labels = {} for u in self.city.nodes(): node_labels[u] = u nx.draw(self.city, pos) nx.draw_networkx_labels(self.city, pos, labels=node_labels) self.btnViewCity.setEnabled(True) plt.show()
def malt_demo(nx=False): """ A demonstration of the result of reading a dependency version of the first sentence of the Penn Treebank. """ dg = DependencyGraph("""Pierre NNP 2 NMOD Vinken NNP 8 SUB , , 2 P 61 CD 5 NMOD years NNS 6 AMOD old JJ 2 NMOD , , 2 P will MD 0 ROOT join VB 8 VC the DT 11 NMOD board NN 9 OBJ as IN 9 VMOD a DT 15 NMOD nonexecutive JJ 15 NMOD director NN 12 PMOD Nov. NNP 9 VMOD 29 CD 16 NMOD . . 9 VMOD """) tree = dg.tree() tree.pprint() if nx: # currently doesn't work import networkx from matplotlib import pylab g = dg.nx_graph() g.info() pos = networkx.spring_layout(g, dim=1) networkx.draw_networkx_nodes(g, pos, node_size=50) # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8) networkx.draw_networkx_labels(g, pos, dg.nx_labels) pylab.xticks([]) pylab.yticks([]) pylab.savefig('tree.png') pylab.show()
def draw_text_graph(G): plt.figure(figsize=(18,12)) pos = nx.spring_layout(G, scale=18) nx.draw_networkx_nodes(G, pos, node_color="white", linewidths=0, node_size=500) nx.draw_networkx_labels(G, pos, font_size=10) nx.draw_networkx_edges(G, pos) plt.xticks([]) plt.yticks([])
def draw_street_graph(networkx_graph, node_index): """ This function draws the networkx graph and visualise it. PARAMETERS ---------- networkx_graph : networkx graph class instance The networkx graph to be visualised. node_index : list of floats The index of the nodes in the networkx graph. """ import matplotlib.pyplot as plt node_pos = {} ntcnt = 0 for np in node_index: node_pos[ntcnt] = (np[0],np[1]) ntcnt+=1 nx.draw_networkx_labels(networkx_graph,pos=node_pos) nx.draw_networkx_nodes(networkx_graph,node_pos, node_size = 10) nx.draw_networkx_edges(networkx_graph,node_pos,width=1.0,alpha=0.5) plt.show() #================================================================================================================ #NSHFAI #================================================================================================================
def _draw_graph_diffing(graph1, graph2, differences): plt.subplot(121) pos = nx.pygraphviz_layout(graph1, prog='dot') nx.draw_networkx_nodes(graph1, pos, graph1.nodes(), node_color='b', node_size=200) nx.draw_networkx_nodes(graph1, pos, differences[0], node_color='r', node_size=600) nx.draw_networkx_nodes(graph1, pos, differences[2], node_color='y', node_size=600) nx.draw_networkx_edges(graph1, pos, graph1.edges()) nx.draw_networkx_labels(graph1, pos, font_size=8) plt.title('Graph 1') plt.axis('off') plt.subplot(122) pos = nx.pygraphviz_layout(graph2, prog='dot') nx.draw_networkx_nodes(graph2, pos, graph2.nodes(), node_color='b', node_size=200) nx.draw_networkx_nodes(graph2, pos, differences[1], node_color='r', node_size=600) nx.draw_networkx_nodes(graph2, pos, differences[3], node_color='g', node_size=600) nx.draw_networkx_edges(graph2, pos, graph2.edges()) nx.draw_networkx_labels(graph2, pos, font_size=8) plt.title('Graph 2') plt.axis('off') lr = plt.Circle((0, 0), 5, fc='r') lb = plt.Circle((0, 0), 5, fc='b') lg = plt.Circle((0, 0), 5, fc='g') ly = plt.Circle((0, 0), 5, fc='y') plt.legend([lb, lr, lg, ly], ['No changed', 'Changed', 'Added', 'Removed'], loc=4) # plt.savefig(graph1.name + '-' + graph2.name + '.png') plt.show()
def Drawcomgraph(G): #Draw the graph pos=nx.spring_layout(G) nx.draw_networkx_edges(G, pos, alpha=0.4) nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif') #colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua' nx.draw_networkx_nodes(G, pos, nodelist=G.nodes(), node_size=150) plt.title("Network Community Analysis") plt.show()
def plot_and_save_net(self, picpath='../output/net.png'): net = nx.DiGraph() edge_label = dict() for edge in self.edges: net.add_edge(edge[0], edge[1], weight=1) edge_label[(edge[0], edge[1])] = edge[3] if len(edge_label) > 8: break # edge_label.update({(edge[0], edge[1]) : edge[2]}) pos = nx.spring_layout(net, k=20) # positions for all nodes # nodes nx.draw_networkx_nodes(net, pos, node_size=6000, node_color="green") # edges nx.draw_networkx_edges(net, pos, width=1.5, alpha=0.5, arrows=True, edge_color='black') # labels nx.draw_networkx_labels(net, pos, font_size=20) nx.draw_networkx_edge_labels(net, pos, edge_labels=edge_label, label_pos=0.5, font_family='sans-serif') plt.axis('off') plt.savefig(picpath) # save as png plt.show() # display
def draw_relation_graph(G,node_ip,node_main,node_cname): from networkx.drawing.nx_pydot import graphviz_layout node_size =100 pos = graphviz_layout(G, prog="fdp") # neato fdp nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_ip, node_color='red', label="IP") nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_cname, node_color='green', label="CNAME") nx.draw_networkx_nodes(G, pos=pos, node_size=160, nodelist=node_main, node_color='blue', label="Main") nx.draw_networkx_edges(G, pos=pos) # nx.draw_networkx_labels(G, pos, font_size=10) # show the node labe plt.legend(loc='lower center', ncol=3, shadow=True, numpoints=1) plt.axis('off') plt.savefig('./graph/dd_type.png', dpi=75) plt.show()
def create_web_network_graph(self): ''' Functions that creates a NetworkX network visualization from the explored pages For documentation about NetworkX, check : https://networkx.github.io/''' #Create a directed graph web_graph=nx.DiGraph() # Add our start nodes first to the graph, as the center. web_graph.add_nodes_from(self.to_visit_urls[0]) #Now we explore our results to add the relevant websites to the graph for base_url in os.listdir(self.main_directory+"web_content/"): if self.is_danish_company(base_url): #Only Danish companies are added : web_graph.add_node(base_url) #Explore again to fill up all the edges (connections/links) between websites for base_url in os.listdir(self.main_directory+"web_content/"): if self.is_danish_company(base_url): # Same as before only Danish companies #Load up the links from this Danish company to other websites filename = self.main_directory+"web_content/"+base_url+"/external_urls_"+str(self.redirect_count)+"_redirect.p" external_base_urls=pickle.load(open(filename, "rb" )) #Now we also filter the list of external links for external_link in external_base_urls: if web_graph.has_node(external_link) : # The link is also in the graph, so the connection is added web_graph.add_edge(base_url,external_link) #Finally draw the network #plt.figure(figsize=(120, 90)) plt.figure(figsize=(40, 40)) pos = nx.random_layout(web_graph) nx.draw_networkx_nodes(web_graph,pos,node_size=2500) nx.draw_networkx_nodes(web_graph,nodelist=self.to_visit_urls[0],pos=pos,node_size=3000,node_color='b') #nx.draw_networkx_labels(web_graph,pos,fontsize=12) nx.draw_networkx_edges(web_graph,pos,alpha=0.5) plt.savefig(self.main_directory+"DTU network.png",dpi=40) plt.show()
def save_topology(adj, sample_folder, dataset_name, graph_name): graph = nx.Graph() path = sample_folder+'/'+dataset_name if not os.path.isdir(path): os.makedirs(path) # 1. transfer adj to nx # adj_list = list(np.squeeze(adj[0,:,:,:])) adj_list = list(adj) for src in range(len(adj_list)): graph.add_node(src) for dst in range(len(adj_list[src])): if adj_list[src][dst] >= 0.2: # ?? sample ?? ?? [0,1]??? graph.add_edge(src,dst) # 2. read position pos_file = glob.glob(path+'/*.pos') if pos_file == []: pos = nx.spring_layout(graph) pickle.dump(pos, open(path+'/graph.pos','wb')) else: pos = pickle.load(open(pos_file[0],'rb')) # 3. draw graph nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8) nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8) nx.draw_networkx_labels(graph, pos, font_color='w') plt.savefig(path+'/'+graph_name+'.png') plt.savefig(path+'/'+graph_name+'.pdf') # plt.show() # 4. store graph pickle.dump(graph, open(path+'/'+graph_name+'.graph','wb'))
def save_topology(adj, path, graph_name, link_possibility): graph = nx.Graph() if not os.path.isdir(path): os.makedirs(path) # 1. transfer adj to nx adj_list = list(np.squeeze(adj[0,:,:,:])) for src in range(len(adj_list)): graph.add_node(src) for dst in range(len(adj_list[src])): if adj_list[src][dst] >= link_possibility: # ?? sample ?? ?? [0,1]??? graph.add_edge(src,dst) # 2. read position pos_file = glob.glob(path+'*.pos') if pos_file == []: node_size = len(graph.nodes()) tmp_graph = nx.barabasi_albert_graph(node_size,2) pos = nx.spring_layout(tmp_graph) pickle.dump(pos, open(path+'graph.pos','wb')) else: pos = pickle.load(open(pos_file[0],'rb')) # 3. draw graph nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8) nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8) nx.draw_networkx_labels(graph, pos, font_color='w') plt.savefig(path+'/'+graph_name+'.png') plt.savefig(path+'/'+graph_name+'.pdf') # plt.show() plt.clf() # 4. store graph pickle.dump(graph, open(path+graph_name+'.graph','wb')) # ------------------------------ # show_all_variables() # @purpose: ??TF?????? # ------------------------------
def draw_tier3(): print 'loading tier3 data' loadEntity(tier3filename) print 'entity size: ', len(entityList) G = nx.Graph() for entity in entityList: name = entity.name[0].decode('utf8') print name G.add_node(name) for parent in entity.parent: pr = parent.decode('utf8') G.add_node(pr) G.add_edge(pr, name) for child in entity.child: cn = child.decode('utf8') G.add_node(cn) G.add_edge(name, cn) pos=nx.spring_layout(G) # positions for all nodes nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5) # labels nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif') plt.axis('off') plt.show()
def plot_module_dependency_graph(graph): """ Plot a graph of specified yang modules. this function is used to plot both the full dependency graph of all yang modules in the DB, or a subgraph of dependencies for a specified module :param graph: Graph to be plotted :return: None """ # fixed_pos = { 'ietf-interfaces':(0.01,0.01) } # fixed_nodes = fixed_pos.keys() # pos = nx.spring_layout(graph, iterations=200, # pos=fixed_pos, fixed=fixed_nodes) #pos = nx.circular_layout(graph) pos = nx.spring_layout(graph, iterations=2000) # Draw RFC nodes (yang modules) in red nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, RFC_TAG), node_size=200, node_shape='s', node_color='red', alpha=0.5, linewidths=0.5) # Draw draft nodes (yang modules) in green nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, DRAFT_TAG), node_size=200, node_shape='o', node_color='green', alpha=0.5, linewidths=0.5) # Draw unknown nodes (yang modules) in orange nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, UNKNOWN_TAG), node_size=200, node_shape='^', node_color='orange', alpha=1.0, linewidths=0.5) # Draw edges in light gray (fairly transparent) nx.draw_networkx_edges(graph, pos=pos, alpha=0.25, linewidths=0.1, arrows=False) # Draw labels on nodes (modules) nx.draw_networkx_labels(graph, pos=pos, font_size=10, font_weight='bold', alpha=1.0)
def show_network(self): import time plt.figure(time.time()) for v in self.G.nodes(): self.G.node[v]['state'] = str(v) node_labels = nx.get_node_attributes(self.G, 'state') pos = nx.circular_layout(self.G) nx.draw_networkx_labels(self.G, pos, node_labels=node_labels) nx.draw(self.G, pos) plt.savefig('./assets/result2.png') # plt.show(block=False) plt.close()
def display_graph(G): pos=nx.spring_layout(G) node_labels = {node:node for node in G.nodes()} nx.draw_networkx_labels(G, pos, labels=node_labels) nx.draw(G,pos) pylab.show()
def visualize(self, edgelabel='prob', current_node=None, draw='pygraphviz'): """ Visualizes a LOMAP system model. """ assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel) if draw == 'pygraphviz': nx.view_pygraphviz(self.g, edgelabel) elif draw == 'matplotlib': pos = nx.get_node_attributes(self.g, 'location') if len(pos) != self.g.number_of_nodes(): pos = nx.spring_layout(self.g) if current_node is None: colors = 'r' else: if current_node == 'init': current_node = next(self.init.iterkeys()) colors = dict([(v, 'r') for v in self.g]) colors[current_node] = 'b' colors = colors.values() nx.draw(self.g, pos=pos, node_color=colors) nx.draw_networkx_labels(self.g, pos=pos) edge_labels = nx.get_edge_attributes(self.g, edgelabel) nx.draw_networkx_edge_labels(self.g, pos=pos, edge_labels=edge_labels) else: raise ValueError('Expected parameter draw to be either:' + '"pygraphviz" or "matplotlib"!')
def visualize(self, edgelabel='control', current_node=None, draw='pygraphviz'): """ Visualizes a LOMAP system model. """ assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel) if draw == 'pygraphviz': nx.view_pygraphviz(self.g, edgelabel) elif draw == 'matplotlib': pos = nx.get_node_attributes(self.g, 'location') if len(pos) != self.g.number_of_nodes(): pos = nx.spring_layout(self.g) if current_node is None: colors = 'r' else: if current_node == 'init': current_node = next(self.init.iterkeys()) colors = dict([(v, 'r') for v in self.g]) colors[current_node] = 'b' colors = colors.values() nx.draw(self.g, pos=pos, node_color=colors) nx.draw_networkx_labels(self.g, pos=pos) edge_labels = nx.get_edge_attributes(self.g, edgelabel) nx.draw_networkx_edge_labels(self.g, pos=pos, edge_labels=edge_labels) else: raise ValueError('Expected parameter draw to be either:' + '"pygraphviz" or "matplotlib"!')
def visualize(self, edgelabel=None, draw='pygraphviz'): """ Visualizes a LOMAP system model """ if draw == 'pygraphviz': nx.view_pygraphviz(self.g, edgelabel) elif draw == 'matplotlib': pos = nx.spring_layout(self.g) nx.draw(self.g, pos=pos) nx.draw_networkx_labels(self.g, pos=pos) else: raise ValueError('Expected parameter draw to be either:' + '"pygraphviz" or "matplotlib"!')
def _draw_node_labels(self, labels, **kwargs): pos = kwargs.pop('pos', self._pos) return nx.draw_networkx_labels(self._G, pos, labels=labels, **kwargs)
def animate(self, save=False): """ Animates the Given algorithm with given Graph :param save: Boolean indicating weather output has to be written into output/ """ result = self.fn(self.graph) for matrix, active in result: self.frames.append(matrix) self.active.append(active) # Draw the original matrix if self.pos is None: self.pos = nx.nx_pydot.graphviz_layout(self.graph) nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8, node_size=self.node_size).set_edgecolor('k') nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.6) if self.weights: nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1, edge_labels=nx.get_edge_attributes(self.graph, 'weight')) if self.lables: nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1) # Draw its adjacancy matrix vmin = 0 vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1]))) cmap = plt.get_cmap('jet') cmap.set_bad('white', 1.) masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0])) self.ax2.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7) if self.matrix_labels: self.__plot_matrix_labels(self.frames[0], self.ax2) # Now start the animation x = animation.FuncAnimation(self.fig, self.__update, interval=1000, blit=False, repeat=False, init_func=self.__init_animation, frames=len(self.frames)) if save: import errno import os path = "output" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise Writer = animation.writers['ffmpeg'] writer = Writer(fps=1, metadata=dict(artist='V'), bitrate=1800) from multiprocessing import Process import os path = os.path.join('output', '%s.mp4' % self.fn.__name__) Process(target=x.save, args=(path,), kwargs={'writer': writer}).start() plt.show()
def apply_to_graph(self, show_graph=True): """ Applies the given algorithm to given graph and displays it :param show_graph: Weather to show the graph in final result or not """ # Draw the original matrix if show_graph: if self.pos is None: self.pos = nx.nx_pydot.graphviz_layout(self.graph) nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8, node_size=self.node_size).set_edgecolor('k') nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.5) if self.weights: nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1, edge_labels=nx.get_edge_attributes(self.graph, 'weight')) if self.lables: nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1) # Draw its adjacancy matrix result, adj = None, None for i, matrix in enumerate(self.fn(self.graph)): if i == 0: adj = matrix[0] result = matrix[0] # print(adj, result) cmap = plt.get_cmap('jet') cmap.set_bad('white', 1.) vmin = 0 vmax = np.max(result) from mpl_toolkits.axes_grid1 import make_axes_locatable div = make_axes_locatable(self.ax2) cax = div.append_axes('right', '5%', '5%') cax.axis('off') masked_array = np.ma.array(adj, mask=np.isinf(adj)) self.ax2.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax) if self.matrix_labels: self.__plot_matrix_labels(adj, self.ax2) # Now draw the final matrix masked_array = np.ma.array(result, mask=np.isinf(result)) div = make_axes_locatable(self.ax3) cax = div.append_axes('right', '5%', '5%') if self.matrix_labels: self.__plot_matrix_labels(result, self.ax3) self.img = self.ax3.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax) self.fig.colorbar(self.img, cax=cax) plt.show()
def apply_to_graph(fun, G = None): """ Applies given algorithm to random geometric graph and displays the results side by side :param fun: A function which has the signature f(G) and returns iterator of edges of graph G :param G: a networkx Graph. If None, random geometric graph is created and applied :return: Plot showing G and fun(G) """ if G is None: G = nx.random_geometric_graph(100, .125) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, 'pos') nodesize = 80 for u, v in G.edges(): G.edge[u][v]['weight'] = ((G.node[v]['pos'][0] - G.node[u]['pos'][0]) ** 2 + (G.node[v]['pos'][1] - G.node[u]['pos'][1]) ** 2) ** .5 else: pos = graphviz_layout(G) nodesize = 200 # find node near center (0.5,0.5) color = {} dmin = 1 ncenter = 0 for n in pos: x, y = pos[n] d = (x - 0.5) ** 2 + (y - 0.5) ** 2 color[n] = d if d < dmin: ncenter = n dmin = d res = nx.Graph(list(fun(G))) plt.figure(figsize=(10, 8)) plt.suptitle(fun.__name__ + " algorithm application") plt.subplot(1, 2, 1) plt.title("Original Graph G") nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) nx.draw_networkx_nodes(G, pos, nodelist=color.keys(), node_size=nodesize, node_color=list(color.values()), cmap=plt.get_cmap("Reds_r") ).set_edgecolor('k') if G is not None: nx.draw_networkx_labels(G,pos) nx.draw_networkx_edge_labels(G,pos, edge_labels=nx.get_edge_attributes(G,'weight')) plt.axis('off') plt.subplot(1, 2, 2) plt.title("Resultant Graph, R = {0}(G)".format(fun.__name__)) nx.draw_networkx_edges(res, pos, nodelist=[ncenter], alpha=0.4) nx.draw_networkx_nodes(res, pos, node_color=list(color[n] for n in res.nodes()), node_size=nodesize, cmap=plt.get_cmap("Greens_r")).set_edgecolor('k') if G is not None: nx.draw_networkx_labels(res,pos) nx.draw_networkx_edge_labels(res, pos, edge_labels=nx.get_edge_attributes(res, 'weight')) plt.axis('off') plt.show()