def draw_ag(ag, file_name): position = {} number_of_layers = 1 largest_number = 15 node_size = math.log10(largest_number)*15 # print "Node Size", node_size node_distance_x = 0.05 * (number_of_layers+1) node_distance_y = 0.05 * (number_of_layers+1) offset_x = 0.05 offset_y = 0.05 plt.figure(num=None, figsize=(3, 3), dpi=100) for Node in ag.nodes(): x, y, z = return_node_location(Node) position[Node] = [(x*node_distance_x)+(z*offset_x), (y*node_distance_y)+(z*offset_y)] # POS = networkx.spring_layout(AG) networkx.draw(ag, pos=position, with_labels=True, node_size=node_size, arrows=False, font_size=7, linewidths=1) plt.savefig("GraphDrawings/"+file_name+".png") plt.close() plt.clf() return None
def create_tree(r, h): G = nx.balanced_tree(r, h) return G #nx.draw_networkx(G, pos = nx.spring_layout(G)) #nx.draw_spring(G) for i in range(7): G.node[i]['color'] = 'white' ####### Visualization with graphviz ######## #write_dot(G,'test.dot') # same layout using matplotlib with no labels #plt.title("draw_networkx") pos=graphviz_layout(G,prog='dot') nx.draw(G,pos,with_labels=True,arrows=False, node_color = 'lightgray') plt.show() return G
def display_graph(self): G = nx.Graph() count = 0 edges = set() edges_list = [] for pkt in self.pcap_file: if pkt.haslayer(Dot11Elt): src = pkt[Dot11].addr1 dst = pkt[Dot11].addr2 edges_list.append((src, dst)) edges.add(src) edges.add(dst) plt.clf() filepath = os.path.splitext(self.path)[0] filename = basename(filepath) plt.suptitle('Connection Map of: '+ str(filename), fontsize=14, fontweight='bold') plt.title("\n Number of Users: " + str(int(len(edges)))) plt.rcParams.update({'font.size': 10}) G.add_edges_from(edges_list) nx.draw(G, with_labels=True, node_color=MY_COLORS) plt.show()
def draw_difference(self, path_old, path_new): self.draw_path(path_old) H = self.G.copy() H.add_edges_from(path_edges(path_new.path)) H_ = nx.difference(self.G, H) nx.draw(self.G, self.pos) nx.draw(H_, self.pos, edge_color='blue')
def display_graph_by_specific_mac(self, mac_address): G = nx.Graph() count = 0 edges = set() edges_list = [] for pkt in self.pcap_file: src = pkt[Dot11].addr1 dst = pkt[Dot11].addr2 if mac_address in [src, dst]: edges_list.append((src, dst)) edges.add(src) edges.add(dst) plt.clf() plt.suptitle('Communicating with ' + str(mac_address), fontsize=14, fontweight='bold') plt.title("\n Number of Communicating Users: " + str(int(len(edges)))) plt.rcParams.update({'font.size': 10}) G.add_edges_from(edges_list) nx.draw(G, with_labels=True, node_color=MY_COLORS) plt.show()
def as_path_plot(self,as_path, prefix): '''This method accpets the list of as-path to plot for the selected prefix as per the GUI. It uses networkx module. The Nodes represent the AS and the edges represent the AS connectivity. ''' G = nx.Graph() l= as_path for i,a in enumerate(l): #print a, type(a), len(a) G.add_node(a[-1]) for i in xrange(len(a)): if i == len(a)-1: break G.add_node(a[i]) G.add_edge(a[i],a[i+1]) # plt.title("draw_networkx") # plt.savefig('abcd.png',dpi=500, facecolor='w', edgecolor='w',orientation='landscape', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.8) plt.title("AS Path for "+prefix) pos=nx.graphviz_layout(G,prog='dot') plt.figure(1,figsize=(10,8)) #nx.draw_networkx(G,pos) nx.draw(G,pos,with_labels=True,arrows=True, font_size = 9,edge_color='r', node_color='b') plt.savefig(prefix+'_as_path.png',pad_inches = 0.8) plt.show()
def plot_neighbourhood(ax,G,direction_colors={},node_color='white',alpha=0.8,labels=True,node_size=300,font_size=12): """ Plots the Graph using networkx' draw method. Each edge should have an direction assigned to it; with the direction_colors parameter you can assign different directions different colors for plotting. @param ax Axis-object. @param G Graph-object. @param direction_colors Dictionary with directions as keys and colors as values. """ pos_dict={} for i in G.node: pos_dict[i]=np.array([G.node[i]['phi'],G.node[i]['theta']]) edge_colors='black' if len(direction_colors.keys())>0: edge_colors=[] for edge_origin in G.edge.keys(): for edge_target in G.edge[edge_origin].keys(): if direction_colors.keys().count(G.edge[edge_origin][edge_target]['direction']): edge_colors.append(direction_colors[G.edge[edge_origin][edge_target]['direction']]) else: edge_target.append('black') nx.draw(G,pos_dict,ax,with_labels=labels,edge_color=edge_colors,node_color=node_color,alpha=alpha,node_size=node_size,font_size=font_size) return G
def make_function_graphs(data): fgraph = nx.Graph(data.functions, name='Functions') drawkwargs = {'font_size': 10,\ 'linewidths': 1,\ 'width': 2,\ 'with_labels': True,\ 'node_size': 700,\ 'node_color':'w',\ 'node_shape':'o',\ 'style':'solid',\ 'alpha':1,\ 'cmap': mpl.cm.jet} filepath = 'images'+'/functions/' for function in data.functions_only: g = nx.Graph() nbrs = fgraph.neighbors(function) edges_to_add = [tuple([function, i]) for i in nbrs] g.add_edges_from(edges_to_add) fig = plt.figure(figsize=(20,20)) ax = fig.add_subplot(111) pos=nx.spring_layout(g, iterations=20) nx.draw(g, pos, **drawkwargs ) ax.set_title(function) filepathname = filepath+zeros(function, padlength=4)+'.jpg' plt.savefig(filepathname, bbox_inches='tight') print 'Written to: '+filepathname fig.clf() plt.close() del fig
def plot_graph(graph, protein, Tc, nodecolor, nodesymbol): fig = plt.figure(figsize=(20,20)) ax = fig.add_subplot(111) drawkwargs = {'font_size': 10,\ 'linewidths': 1,\ 'width': 2,\ 'with_labels': True,\ 'node_size': 700,\ 'node_color':nodecolor,\ 'node_shape':'o',\ 'style':'solid',\ 'alpha':1,\ 'cmap': mpl.cm.jet} pos=nx.spring_layout(graph, iterations=200) nx.draw(graph, pos, **drawkwargs ) if protein in Tc: string = "Protein: %i Cancer" string_s = (protein) title=string%string_s else: string = "Protein: %i Non-Cancer" string_s = (protein) title=string%string_s ax.set_title(title) filepath = 'images'+'/'+zeros(protein, padlength=4)+'.jpg' plt.savefig(filepath, bbox_inches='tight') print 'Written to: '+filepath fig.clf() plt.close() del fig
def plot_graph(self): client_nodes = [node for node,data in self.g.nodes(True) if self.g.in_degree(node) == 0 and self.g.out_degree(node) > 0] client_nodes = [n for n in client_nodes if n!= None and (n[2:6] != "180a" and n[0:6] != "008048")] ap_nodes = [node for node in self.g.nodes() if self.g.in_degree(node) > 0] pylab.figure() nx.draw(self.g, nodelist = client_nodes + ap_nodes, edgelist = self.g.edges(client_nodes), with_labels=False, ) pylab.savefig("graph-%d.png" % int(time.time()))
def draw_graph(G): pos = nx.spring_layout(G) nx.draw(G, pos) # networkx draw() #P.draw() # pylab draw() plt.show() # display
def print_pdf_graph(file_f, regulon, conn): pdf = PdfPages(file_f) edgesLimits = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] #CRP = regulon_set['LexA'] for lim in edgesLimits: print lim g = buildSimilarityGraph_top_10_v2(conn, lim) # Here the node is motif, eg 87878787_1, the first 8 digits represent gi node_color = [ 1 if node[0:8] in regulon else 0 for node in g ] pos = nx.graphviz_layout(g, prog="neato") plt.figure(figsize=(10.0, 10.0)) plt.axis("off") nx.draw(g, pos, node_color = node_color, node_size = 20, alpha=0.8, with_labels=False, cmap=plt.cm.jet, vmax=1.0, vmin=0.0 ) pdf.savefig() plt.close() pdf.close()
def plot(graph, **kwargs): pos=kwargs.get('pos', nx.spring_layout(graph)) if kwargs.get('draw_edge_labels', False): edge_labels=nx.draw_networkx_edge_labels(graph,pos) else: edge_labels=[] nx.draw(graph, pos, edge_labels=edge_labels, **kwargs) # plt.savefig('plot.pdf') plt.show()
def plot_graph_3D(graph, I_shape, plot_terminal=True, plot_weights=True, font_size=7): w_h = I_shape[1] * I_shape[2] X, Y = np.mgrid[:I_shape[1], :I_shape[2]] aux = np.array([Y.ravel(), X[::-1].ravel()]).T positions = {i: aux[i] for i in xrange(w_h)} for i in xrange(1, I_shape[0]): for j in xrange(w_h): positions[w_h * i + j] = [positions[j][0] + 0.3 * i, positions[j][1] + 0.2 * i] positions['s'] = np.array([-1, int(I_shape[1] / 2)]) positions['t'] = np.array([I_shape[2] + 0.2 * I_shape[0], int(I_shape[1] / 2)]) nxg = graph.get_nx_graph() if not plot_terminal: nxg.remove_nodes_from(['s', 't']) nx.draw(nxg, pos=positions) nx.draw_networkx_labels(nxg, pos=positions) if plot_weights: edge_labels = dict([((u, v,), d['weight']) for u, v, d in nxg.edges(data=True)]) nx.draw_networkx_edge_labels(nxg, pos=positions, edge_labels=edge_labels, label_pos=0.3, font_size=font_size) plt.axis('equal') plt.show()
def plot_func(play, stats): generation = stats["generation"] best = stats["generation_best"] every = play.config["live_plot"].get("every", 100) if generation == 0: plt.figure(figsize=(10, 8)) if (generation % every) == 0: plt.clf() # create graph graph = nx.DiGraph() traverse_tree(best.root, graph) labels = dict((n, d["label"]) for n, d in graph.nodes(data=True)) pos = nx.graphviz_layout(graph, prog='dot') nx.draw( graph, pos, with_labels=True, labels=labels, arrows=False, node_shape=None ) # plot graph plt.draw() plt.pause(0.0001) # very important else plot won't be displayed
def drawTopology(body): extract=body[(body.find('<ApList>')+8):(body.find('</ApList>'))] junk,ap=extract.split('$\n',1) aplist = ap.split(',\n',23) aplist.pop() count = 0 ssiddict={} for item in range(len(aplist)): ssid,q,strength,encryption=aplist[item].split('|',3) if ssid in ssiddict: count+=1 ssiddict[ssid+'(%d)'%count]=int(strength) else: ssiddict[ssid]=int(strength) angle = math.radians(360/len(ssiddict)) ap ={'wemo':(0,0)} up=1 for item,value in ssiddict.iteritems(): ap[item] = ((125-value)*math.cos(up*angle),(125-value)*math.sin(up*angle)) up+=1 G = nx.Graph() for item in ssiddict: G.add_edge('wemo',item) nx.draw(G, pos=ap, with_labels=True) plt.show()
def show_graph_with_labels(adjacency_matrix, mylabels): rows, cols = np.where(adjacency_matrix == 1) edges = zip(rows.tolist(), cols.tolist()) gr = nx.Graph() gr.add_edges_from(edges) nx.draw(gr, node_size=2000, labels=mylabels, with_labels=True) plt.show()
def main(map_name, show = True): TransportNetwork, demand = parse_map(map_name) if show == True: positions = nx.get_node_attributes(TransportNetwork, 'pos') nx.draw(TransportNetwork, positions, node_size = 300) plt.show()
def printClusters(msp_list_deleted, msp_list_remain, msp_list, name): G = nx.Graph() deleted = nx.Graph() remain = nx.Graph() for l in range(0, len(msp_list)): G.add_edge(msp_list[l][1], msp_list[l][2], weight="{0:.2f}".format(msp_list[l][0])) pos = nx.circular_layout(G) for l in range(0, len(msp_list_deleted)): deleted.add_edge(msp_list_deleted[l][1], msp_list_deleted[l][2], weight="{0:.2f}".format(msp_list_deleted[l][0])) for l in range(0, len(msp_list_remain)): remain.add_edge(msp_list_remain[l][1], msp_list_remain[l][2], weight="{0:.2f}".format(msp_list_remain[l][0])) nx.draw(G, pos) edge_labels = dict([((u, v,), d['weight']) for u, v, d in G.edges(data=True)]) edge_labels_deleted = dict([((u, v,), d['weight']) for u, v, d in deleted.edges(data=True)]) edge_labels_remain = dict([((u, v,), d['weight']) for u, v, d in remain.edges(data=True)]) nx.draw_networkx_edges(G, pos, edge_labels=edge_labels_deleted) nx.draw_networkx_edge_labels(remain, pos, edge_labels=edge_labels) nx.draw_networkx_edges(deleted, pos, edge_labels=edge_labels_remain, width=3, edge_color='w', style='dashed') plt.savefig(name + ".png")
def draw_molecule(molecule): # Create a new NetworkX graph g = nx.Graph() # For each vertex and edge in molecule graph add node and edge in NetworkX graph for n in molecule.vertices(): g.add_node(molecule.position_of_vertex(n), element=n.label) for e in molecule.edges(): if e.single: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='single') elif e.double: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='double') elif e.triple: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='triple') elif e.quadruple: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='quadruple') elif e.aromatic: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='aromatic') # Set the layout pos = nx.spring_layout(g, iterations=30) # Display the element type and edge type as labels labels = dict((n,d['element']) for n,d in g.nodes(data=True)) edge_labels = dict(((u,v),d['type']) for u,v,d in g.edges(data=True)) # Add the labels to the graph nx.draw(g, pos=pos, node_color='w') nx.draw_networkx_labels(g, pos=pos, labels=labels) nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=edge_labels) # Display the completed graph plt.show() return g
def final_graphs(Graphs,psi): if Graphs == []: print "There are no models for the input formula: ", (syntax.formula_to_string(psi)) print "So the the negation of it : ", "~(",(syntax.formula_to_string(psi)), ") is valid." else: for i in range(0,len(Graphs)): graph = Graphs[i] custom_labels={} node_colours=['y'] for node in graph.nodes(): custom_labels[node] = graph.node[node] node_colours.append('c') nx.draw(Graphs[i], nx.circular_layout(Graphs[i]), node_size=1500, with_labels=True, labels = custom_labels, node_color=node_colours) #show with custom labels fig_name = "graph" + str(i) + ".png" plt.savefig(fig_name) plt.show() print "Satisfiable models have been displayed." if len(Graphs) == 1: print "You have ",len(Graphs), " valid model." else: print "You have ",len(Graphs), " valid models." print "Your provided formula is: ", (syntax.formula_to_string(psi)) print "Pictures of the graphs have been saves as: graph0.png, graph1.png etc."
def state_change_handler(self, ev): ## to do add flow in switch enter hander and switch leave handler """Update topology graph when a switch enters or leaves. ev -- datapath event and all of it's fields important fields: ev.dp.id: dpid that is joining or leaving ev.enter is true if the datapath is entering and false if it is leaving """ dp=ev.datapath # ports = ev.datapath.ports ofproto = dp.ofproto parser = dp.ofproto_parser assert dp is not None if dp.id is None: return if ev.state == MAIN_DISPATCHER: match = parser.OFPMatch() switch_list = [] for i in self.dpid_to_switch: switch_list.append(i) self.deploy_flow_entry(dp,switch_list,match) if not self.graph.has_node(dp.id): # dpid = format_dpid_str(dpid_to_str(dp.id)) self.graph.add_node(dp.id) thread.start_new(getPeriodicStats, (dp,)) self.logger.info('Switch %s added to the topology', str(dp.id)) # for port in ev.datapath.ports: # ports = [] # ports=dp.ports # out_port = ports[port][0] # print out_port # print 'f**k' # actions =[] # actions = [parser.OFPActionOutput(out_port)] # self.add_flow( dp ,0 ,match , actions) elif ev.state == DEAD_DISPATCHER: if dp.id is None: return if self.graph.has_node(dp.id): self.graph.remove_node(dp.id) self.logger.info('Switch %s removed from the topology', str(dp.id)) nx.draw(self.graph) plt.show() LOG.debug(dp)
def display(g, title): """Displays a graph with the given title.""" pos = nx.circular_layout(g) plt.figure() plt.title(title) nx.draw(g, pos) nx.draw_networkx_edge_labels(g, pos, font_size=20)
def plot_graph(graph, ax=None, cmap='Spectral', **kwargs): """ Parameters ---------- graph : object A networkX or derived graph object ax : objext A MatPlotLib axes object cmap : str A MatPlotLib color map string. Default 'Spectral' Returns ------- ax : object A MatPlotLib axes object. Either the argument passed in or a new object """ if ax is None: ax = plt.gca() cmap = matplotlib.cm.get_cmap(cmap) # Setup edge color based on the health metric colors = [] for s, d, e in graph.edges_iter(data=True): if hasattr(e, 'health'): colors.append(cmap(e.health)[0]) else: colors.append(cmap(0)[0]) nx.draw(graph, ax=ax, edge_color=colors) return ax
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 draw(self): """ Canvas for draw the relationship between apis """ mashup_map = data_source.mashup_with_apis() layout = {} g = nx.Graph() node_size = {} node_color = {} node_map = {} node_id = 0 for key in mashup_map: if len(mashup_map[key]) == 20: for api in mashup_map[key]: if node_map.get(api) == None: node_map[api] = node_id g.add_node(node_id) node_size[node_id] = 50 node_color[node_id] = 0.5 layout[node_id] = (random.random() , random.random()) node_id = node_id + 1 for i in range(0, len(mashup_map[key])): for j in range(0, len(mashup_map[key])): node_id_start = node_map.get(mashup_map[key][i]) node_id_end = node_map.get(mashup_map[key][j]) g.add_edge(node_id_start, node_id_end) node_size[node_id_start] = node_size[node_id_start] + 5 node_size[node_id_end] = node_size[node_id_end] + 5 try: nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False) except Exception, e: print e
def draw_related_mashup(self, mashups, current_mashup=None, highlight_mashup=None): """ Draw the realated mashup graph """ self.ax.clear() layout = {} g = nx.Graph() node_size = {} node_color = {} node_map = {} node_id = 0 for mashup in mashups: if node_map.get(mashup["id"]) == None: node_map[mashup["id"]] = node_id g.add_node(node_id) node_size[node_id] = 20 if current_mashup and mashup["id"] == current_mashup["id"]: node_color[node_id] = 0.7 node_size[node_id] = 180 layout[node_id] = (random.random() , random.random()) else: node_color[node_id] = 0.5 layout[node_id] = (random.random() , random.random()) node_id = node_id + 1 for i in range(0, len(mashups)): node_id_start = node_map.get(mashups[i]["id"]) node_id_end = node_map.get(current_mashup["id"]) g.add_edge(node_id_start, node_id_end) try: nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False) except Exception, e: print e
def add_switch(self): """Add switches to the topology graph Extracts switches information stored in switch_list dictionary important fields: switch.dp.id """ print('self.sw_list_body {}'.format(self.sw_list_body)) for index,switch in enumerate( self.switch_list): # dpid = format_dpid_str(dpid_to_str(switch.dp.id)) self.graph.add_node(switch.dp.id) dpid=switch.dp.id # dpid = hex2decimal(switch['ports']['dpid']) # self.graph.add_node(switch['ports']['dpid']) # for node in switch["ports"]: # dpid = hex2decimal(node['dpid']) # self.graph.add_node(dpid) print(self.graph.nodes()) nx.draw(self.graph) plt.show()
def draw(graph): pos = nx.graphviz_layout(graph, prog='sfdp', args='') list_nodes = graph.nodes() plt.figure(figsize=(20,10)) nx.draw(graph, pos, node_size=20, alpha=0.4, nodelist=list_nodes, node_color="blue", with_labels=False) plt.savefig('graphNX.png') plt.show()
def draw_fault_scenario(title, fault_edge, pp, dp, fwp): nx.draw(G, pos, node_size=300, font_size=10, node_color='w', alpha=1, with_labels=True) if title is not None: plt.text(0.5, 0.5, title, fontsize=12) if pp is not None: draw_edge_node(pp, 0.8, 'b') # Source nx.draw_networkx_nodes(G, pos, nodelist=[pp[0]], node_color='black', node_size=500, label='S', font_size=10, node_shape='s', alpha=0.5) # Detour path if dp is not None: draw_edge_node(dp, 0.8, 'g') # Fault edge if fault_edge is not None: nx.draw_networkx_edges(G, pos, edgelist=[fault_edge], width=4, alpha=0.8, edge_color='r') # FW Back path if fwp is not None: draw_edge_node(fwp, 0.8, 'y', 'dashed')
def draw_graphviz(tree, label_func=str, prog='twopi', args='', node_color='#c0deff', **kwargs): """Display a tree or clade as a graph, using the graphviz engine. Requires NetworkX, matplotlib, Graphviz and either PyGraphviz or pydot. The third and fourth parameters apply to Graphviz, and the remaining arbitrary keyword arguments are passed directly to networkx.draw(), which in turn mostly wraps matplotlib/pylab. See the documentation for Graphviz and networkx for detailed explanations. The NetworkX/matplotlib parameters are described in the docstrings for networkx.draw() and pylab.scatter(), but the most reasonable options to try are: *alpha, node_color, node_size, node_shape, edge_color, style, font_size, font_color, font_weight, font_family* :Parameters: label_func : callable A function to extract a label from a node. By default this is str(), but you can use a different function to select another string associated with each node. If this function returns None for a node, no label will be shown for that node. The label will also be silently skipped if the throws an exception related to ordinary attribute access (LookupError, AttributeError, ValueError); all other exception types will still be raised. This means you can use a lambda expression that simply attempts to look up the desired value without checking if the intermediate attributes are available: >>> Phylo.draw_graphviz(tree, lambda n: n.taxonomies[0].code) prog : string The Graphviz program to use when rendering the graph. 'twopi' behaves the best for large graphs, reliably avoiding crossing edges, but for moderate graphs 'neato' looks a bit nicer. For small directed graphs, 'dot' may produce a normal-looking cladogram, but will cross and distort edges in larger graphs. (The programs 'circo' and 'fdp' are not recommended.) args : string Options passed to the external graphviz program. Normally not needed, but offered here for completeness. Example ------- >>> import pylab >>> from Bio import Phylo >>> tree = Phylo.read('ex/apaf.xml', 'phyloxml') >>> Phylo.draw_graphviz(tree) >>> pylab.show() >>> pylab.savefig('apaf.png') """ try: import networkx except ImportError: from Bio import MissingPythonDependencyError raise MissingPythonDependencyError( "Install NetworkX if you want to use to_networkx.") G = to_networkx(tree) try: # NetworkX version 1.8 or later (2013-01-20) Gi = networkx.convert_node_labels_to_integers(G, label_attribute='label') int_labels = {} for integer, nodeattrs in Gi.node.items(): int_labels[nodeattrs['label']] = integer except TypeError: # Older NetworkX versions (before 1.8) Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False) int_labels = Gi.node_labels try: posi = networkx.graphviz_layout(Gi, prog, args=args) except ImportError: raise MissingPythonDependencyError( "Install PyGraphviz or pydot if you want to use draw_graphviz.") def get_label_mapping(G, selection): """Apply the user-specified node relabeling.""" for node in G.nodes(): if (selection is None) or (node in selection): try: label = label_func(node) if label not in (None, node.__class__.__name__): yield (node, label) except (LookupError, AttributeError, ValueError): pass if 'nodelist' in kwargs: labels = dict(get_label_mapping(G, set(kwargs['nodelist']))) else: labels = dict(get_label_mapping(G, None)) kwargs['nodelist'] = list(labels.keys()) if 'edge_color' not in kwargs: kwargs['edge_color'] = [ isinstance(e[2], dict) and e[2].get('color', 'k') or 'k' for e in G.edges(data=True) ] if 'width' not in kwargs: kwargs['width'] = [ isinstance(e[2], dict) and e[2].get('width', 1.0) or 1.0 for e in G.edges(data=True) ] posn = dict((n, posi[int_labels[n]]) for n in G) networkx.draw(G, posn, labels=labels, node_color=node_color, **kwargs)
def draw_plots_with_edge_attributes_no_node_module_file( infile, node_attrib_file, outfilestring, img_qual, img_frmt, delim, attrib_color_map, categ_color_map, edge_color_map, node_abund_file, common_edge_list, common_edge_diff_correl_list, dynamic): # edges edges = readColumnsSep(infile, ' ', 0, 2, 4) edges_attrib_dict = get_edge_attributes(edges, edge_color_map, common_edge_list, common_edge_diff_correl_list) edges_list = edges_attrib_dict.keys() # calculate avg. relative abundance of the node node_abundance = get_node_abundance(node_abund_file, delim) #and make a list and submit as node_size to draw() node_sizes_dict = node_weights_to_sizes(node_abundance) samModG = nx.Graph() samModGcolors = [] for (u, v) in edges_list: # for singleton nodes in module, dummy self edge was added to display on plot color_ = '' if (u, v) in edges_attrib_dict: color_ = edges_attrib_dict[(u, v)] elif u == v: color_ = 'cyan' samModG.add_edge(u, v, color=color_) samModGcolors.append(color_) all_nodes_in_edge_list = [','.join(e) for e in edges_list] # identify the category the OTU belongs to node_categ_dict = identify_node_categ( condense_list(all_nodes_in_edge_list, ',')) # use to dynamically create color map if dynamic: categ_color_map = create_color_map(node_categ_dict.values()) for node in samModG.nodes(): samModG.add_node(node, category=node_categ_dict[node]) samModGnode_sizes_list = [node_sizes_dict[i] for i in samModG.nodes()] # reduce length of label for easier visualization # nodecolor as per the phyla nodeColor = [ categ_color_map[samModG.node[node]['category']] for node in samModG ] new_labels = create_pretty_node_labels(samModG) # create legend f = plt.figure(1) ax = f.add_subplot(1, 1, 1) for label in categ_color_map: if label in node_categ_dict.values( ): # only show legend for values that are in my data ax.plot([], [], 'o', color=categ_color_map[label], label=label) for label in edge_color_map: # 0, 1, -1 correlation values if edge_color_map[ label] in samModGcolors: # colors, only show legend for values that are in my data ax.plot([], [], color=edge_color_map[label], label=label) plt.title('OTUs colored as per Phylum.') # other layout algos: dot, neato, fdp, twopi, circo algo = 'circo' pos = nx.graphviz_layout(samModG, prog=algo) #https://wiki.ubuntu.com/Fonts #williamslab@HORT-MW-Vos:/usr/share/matplotlib/mpl-data/fonts$ sudo ln -s /usr/share/fonts/truetype/msttcorefonts/Arial.ttf ./ttf/arial.ttf #williamslab@HORT-MW-Vos:/usr/share/matplotlib/mpl-data/fonts$ sudo ln -s /usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf ./ttf/times.ttf ''' fontpath = '/usr/local/share/fonts/Arial.ttf' prop = font_manager.FontProperties(fname=fontpath) matplotlib.rcParams['font.family'] = prop.get_name() ''' #/usr/share/fonts/truetype/msttcorefonts/ text_font = 'Arial' # 'Times' 'Helvetica' ''' #http://stackoverflow.com/questions/18821795/how-can-i-get-list-of-font-familyor-name-of-font-in-matplotlib ''' nx.draw(samModG, edgelist=edges_list, edge_color=samModGcolors, pos=pos, node_color=nodeColor, labels=new_labels, with_labels=True, node_size=samModGnode_sizes_list, font_size=8, font_family=text_font) #http://stackoverflow.com/questions/7125009/how-to-change-legend-size-with-matplotlib-pyplot #http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend #plt.legend(loc=3,prop={'size':6}) plt.legend(bbox_to_anchor=(0.15, 0.93), loc=0, borderaxespad=0., prop={'size': 6}) #, title = "Legend" plt.savefig(outfilestring + "-edge-node-color-phyla." + img_frmt, dpi=img_qual) plt.close()
role_extractor.extract_role_factors(features) node_roles = role_extractor.roles print('\nNode role assignments:') pprint(node_roles) print('\nNode role membership by percentage:') print(role_extractor.role_percentage.round(2)) # build color palette for plotting unique_roles = sorted(set(node_roles.values())) color_map = sns.color_palette('Paired', n_colors=len(unique_roles)) # map roles to colors role_colors = {role: color_map[i] for i, role in enumerate(unique_roles)} # build list of colors for all nodes in G node_colors = [role_colors[node_roles[node]] for node in G.nodes] # plot graph plt.figure() with warnings.catch_warnings(): # catch matplotlib deprecation warning warnings.simplefilter('ignore') nx.draw( G, pos=nx.spring_layout(G, seed=42), # with_labels=True, node_color=node_colors, node_size=100, #default=300 font_size=5 #default=12 ) plt.show()
def draw_graph(self, graph): value = nx.draw(graph, ax=self.sp) self.sp.draw(value)
for p in spl: pathlengths.append(spl[p]) print() print(f"average shortest path length {sum(pathlengths) / len(pathlengths)}") # histogram of path lengths dist = {} for p in pathlengths: if p in dist: dist[p] += 1 else: dist[p] = 1 print() print("length #paths") verts = dist.keys() for d in sorted(verts): print(f"{d} {dist[d]}") print(f"radius: {nx.radius(G)}") print(f"diameter: {nx.diameter(G)}") print(f"eccentricity: {nx.eccentricity(G)}") print(f"center: {nx.center(G)}") print(f"periphery: {nx.periphery(G)}") print(f"density: {nx.density(G)}") pos = nx.spring_layout(G, seed=3068) # Seed layout for reproducibility nx.draw(G, pos=pos, with_labels=True) plt.show()
import sys import pprint import argparse import pickle import pylab as pl import matplotlib.pyplot as plt import networkx as nx parser = argparse.ArgumentParser(description='Construct meshterm network for search criteria.') parser.add_argument('--outfile', type=argparse.FileType('w'), required=True ) parser.add_argument('--pickle', type=argparse.FileType('r'), required=True ) args = parser.parse_args() outfile = args.outfile pickle_file = args.pickle if __name__ == '__main__': G = pickle.Unpickler(pickle_file).load() print "nodes: ", len(G.nodes()) plt.cla() fig = plt.figure(figsize=(38,38), dpi=800) nx.draw(G, node_size = [G.degree(n) for n in G.nodes()], width = [G.get_edge_data(*e)['citations'] for e in G.edges()], edge_color = [G.get_edge_data(*e)['jin'] for e in G.edges()] ) plt.savefig( outfile )
#print(pos) pos.update((node, (2, index)) for index, node in enumerate(r)) #print(pos) color_map = [] for nodeCount in range(len(item1)): #print(nodeCount) color_map.append('pink') #Item 1 objects colored one color for nodeCount in range(len(item2)): #print(nodeCount) color_map.append('green') #Item 2 objects colored second color print("Colored the Nodes") #print(color_map) #This is for two parallel line bipartite graph. Put pos=pos as an argument and see . To plot based on some edge weights #nx.draw(B, pos=pos, with_labels=True, edge_color=Edge_Weight, node_color=color_map, node_size=1500, font_size=25, font_color="yellow", font_weight="bold",edge_cmap=plt.get_cmap('BuGn'), label ="SNP To Gene eQTL Associations Cis & Trans") #To plot with degrees of association in linear bipartite nx.draw(B, pos=pos, with_labels=True, edge_color=['blue' if B.degree[e[0]] >= int(sys.argv[1]) else 'red' for e in B.edges],font_size=4,font_weight="bold", node_color=color_map, font_color="black", edge_cmap=plt.get_cmap('BuGn'), label ="SNP To Gene eQTL Associations Cis & Trans") #We make circular network plot with argument in command line for the degree of connectedness and above that needs to be colored differently #nx.draw_circular(B,with_labels=True, edge_color=['blue' if B.degree[e[0]] >= int(sys.argv[1]) else 'red' for e in B.edges], node_color=color_map, font_color="black",edge_cmap=plt.get_cmap('Blues'), label ="SNP To Gene eQTL Associations Cis & Trans" ) #plt.title("SNP to Gene eQTL Association") plt.title('ReGen Bipartite Plot', color='magenta') #plt.show() print("Drawing for Circular Plot prepared") plt.savefig('abiPlot.png', bbox_inches='tight') print("Graph Plotted by name abiPlot.png") #######################################################Here we Generate the Communities######################################## communities_generator = community.girvan_newman(B) #Finds communities in a graph using the Girvan–Newman Division method for centrality in packing #communities_generator = community.greedy_modularity_communities(B)#Find communities in graph using Clauset-Newman-Moore greedy modularity maximization. #communities_generator = community.asyn_fluidc(B) #Returns communities in G as detected by Fluid Communities algorithm. #communities_generator = community.label_propagation_communities(B) #Generates community sets determined by label propagation #communities_generator = community.kernighan_lin_bisection(B) #Partition a graph into two blocks using the Kernighan–Lin algorithm.
# nodes = list(G.nodes()) conn = {i: set(conn[i]) for i in conn} # Метрика по степени centrality_degree = dict() for node in nodes: centrality_degree[node] = len(conn[node]) / (len(nodes) - 1) print('-' * 100) print('Метрика по степени:', centrality_degree) x = [centrality_degree[i] for i in nodes] nx.draw(G, pos=None, node_size=100, node_color=x) plt.show() # Метрика по близости centrality_closeness = dict() for node in nodes: centrality_closeness[node] = (len(nodes) - 1) / sum( distance[node].values()) print('-' * 100) print('Метрика по близости:', centrality_closeness) x = [centrality_closeness[i] for i in nodes] nx.draw(G, pos=None, node_size=100, node_color=x)
# path_stage1 = path_dir + "o1.json" path_stage2 = path_dir + "o2.json" graph, ranks = pytextrank.text_rank(grafs) pytextrank.render_ranks(graph, ranks) with open(path_stage2, 'w') as f: for rl in pytextrank.normalize_key_phrases(grafs, ranks): f.write("%s\n" % pytextrank.pretty_print(rl._asdict())) # to view output in this notebook print(pytextrank.pretty_print(rl)) import networkx as nx import pylab as plt nx.draw(graph, with_labels=True) plt.show() path_stage1 = path_dir + "o1.json" path_stage2 = path_dir + "o2.json" path_stage3 = path_dir + "o3.json" kernel = pytextrank.rank_kernel(path_stage2) with open(path_stage3, 'w') as f: for s in pytextrank.top_sentences(kernel, path_stage1): f.write(pytextrank.pretty_print(s._asdict())) f.write("\n") # to view output in this notebook print(pytextrank.pretty_print(s._asdict()))
def Main(): if len(sys.argv) == 1: show_help() opts,restlist = getopt(sys.argv[1:],"m:oht:d",\ ["matrix=","threshold=","help","direct"]) threshold = 0.5 direct = False for o, a in opts: if o in ("-m", "--matrix"): M = a if o in ("-h", "--help"): show_help() if o in ("-t", "--threshold"): threshold = float(a) if o in ("-d", "--direct"): direct = True if not 'M' in dir(): show_help() try: f = open(M) except: print >> sys.stderr, "Can't open file", M show_help() max = 0 nodes = [] edges = [] pos = {} edges_col = [] col = {} rank = {} lines = f.readlines() i = 0 maxcols = 0 for line in lines: line = line.strip() if line[0] == "#": continue a = line.split("\t") nodes.append(a[0]) rank[a[0]] = 0 for k, x in enumerate(a[1:]): if k == i: continue x = float(x) if x > threshold or x < -threshold: if k < len(nodes) and rank[a[0]] < rank[nodes[k]] + 1: rank[a[0]] = rank[nodes[k]] + 1 if col.has_key(rank[a[0]]): col[rank[a[0]]] += 1 else: col[rank[a[0]]] = 1 #pos[a[0]]=(rank[a[0]],col[rank[a[0]]]+rank[a[0]]%2*0.5+rank[a[0]]*0.111) pos[a[0]] = (rank[a[0]], col[rank[a[0]]]) i += 1 for e in col.values(): if e > maxcols: maxcols = e for e in pos.keys(): a = pos[e] pos[e] = (a[0], float(a[1] + 0.05 * (rank[e] % 3)) / float(col[rank[e]] + 1) * maxcols) j = 0 G = nx.DiGraph() G.add_nodes_from(nodes) edges = [] for line in lines: line = line.strip() if line[0] == "#": continue a = line.split("\t") for i, x in enumerate(a[1:]): if i == j: continue x = float(x) if max < abs(x): max = abs(x) if x > threshold: edges.append((nodes[i], nodes[j], { 'color': 'green', 'weight': x })) # edges_col.append(x) elif x < -threshold: edges.append((nodes[i], nodes[j], { 'color': 'red', 'weight': x })) # edges_col.append(x) j += 1 G.add_edges_from(edges) e = G.edges() for i in e: edges_col.append(G[i[0]][i[1]]['weight']) nx.draw(G, edge_cmap=plt.get_cmap("RdYlGn"), edgelist=e, edge_color=edges_col, pos=pos, node_color="y", edge_vmin=-max, edge_vmax=max, linewidths=0, width=2, arrows=direct, node_size=100, font_size=10) #nx.draw(G,edge_cmap=plt.get_cmap("RdYlGn"),edge_list=edges,edge_color=edges_col,pos=pos,node_color="y",edge_vmin=-max,edge_vmax=max,linewidths=0,width=2) #nx.draw(G,pos=pos,node_color="y",linewidths=0,width=2) plt.colorbar() plt.show()
auth = tweepy.OAuthHandler( consumer_key='u6PzLjPnLzSEmYMJzYjFw', consumer_secret='qROGgsYiOmXwBbZUAfxV0Wx13SuD0ro4LyvPOXVL12E') auth.set_access_token( key='60838213-Rd9hm2lwlTfy60f661z46mPCI17AROCaTF6Rox255', secret='t19PCabTmNO4DGBoT3WTJ2UASSO2AO9bBAkrorVK8') api = tweepy.API(auth) WORLD_WOE_ID = 1132599 #http://woeid.rosselliot.co.nz/lookup tren = api.trends_place(WORLD_WOE_ID) trends = [trend['name'] for trend in tren[0]['trends']] search_results = [] for trend in trends: for page in range(1, MAX_PAGES + 1): search_results += api.search(q=trend, rpp=RESULTS_PER_PAGE, page=page) all_tweets = [tweet for tweet in search_results] g = create_rt_graph(all_tweets) print >> sys.stderr, "Number nodes:", g.number_of_nodes() print >> sys.stderr, "Num edges:", g.number_of_edges() print >> sys.stderr, "Num connected components:", len( nx.connected_components(g.to_undirected())) print >> sys.stderr, "Node degrees:", sorted(nx.degree(g)) nx.draw(g) plt.show()
def draw_choice(self, stationClass, option): """ This functions will create a visualisation of the graph. The input is the dict of the class Station """ graphdict = {} locations = [(obj.name, obj.location) for obj in gc.get_objects() if isinstance(obj, stationClass)] graphdict = {x[0]: x[1] for x in locations} c_list = [ obj.name for obj in gc.get_objects() if isinstance(obj, st.Station) if obj.importance == 'critical' ] nc_list = [ obj.name for obj in gc.get_objects() if isinstance(obj, st.Station) if obj.importance == 'not critical' ] nx.draw(self.graph, graphdict, font_size=8, node_size=1, edge_width=0.1, width=0.1) nx.draw_networkx_nodes(self.graph, graphdict, node_size=30, nodelist=c_list, node_color='lightsalmon') nx.draw_networkx_nodes(self.graph, graphdict, node_size=20, nodelist=nc_list, node_color='lightgrey') if option == 'standard': labels = { obj.name: obj.label for obj in gc.get_objects() if isinstance(obj, st.Station) } elif option == 'critical': labels = { obj.name: obj.label for obj in gc.get_objects() if isinstance(obj, st.Station) if obj.importance == 'critical' } elif option[0] == 'track': tracks = option[1] for x in tracks: track = x[0] time = x[1] tracklist = [] templist = [] edge_labels = {} for y in track: templist.append(y[0][0]) templist.append(y[0][1]) edge_labels[(y[0][0], y[0][1])] = y[1] tracklist = set(templist) t_labels = { obj.name: obj.label for obj in gc.get_objects() if isinstance(obj, st.Station) if obj.name in tracklist } r_labels = { obj.name: obj.label for obj in gc.get_objects() if isinstance(obj, st.Station) if obj.importance == 'critical' and obj.name not in t_labels } nx.draw(self.graph, graphdict, font_size=8, node_size=1, edge_width=0.1, width=0.1) nx.draw_networkx_nodes(self.graph, graphdict, node_size=30, nodelist=c_list, node_color='lightsalmon') nx.draw_networkx_nodes(self.graph, graphdict, node_size=20, nodelist=nc_list, node_color='lightgrey') nx.draw_networkx_edges(self.graph, graphdict, edgelist=edge_labels, width=0.5, edge_color='blue', style='solid', with_label=True) nx.draw_networkx_edge_labels(self.graph, graphdict, edge_labels=edge_labels, font_size=6) nx.draw_networkx_labels(self.graph, graphdict, t_labels, font_size=8, font_weight='bold') nx.draw_networkx_labels(self.graph, graphdict, r_labels, font_size=8, font_weight='normal') plt.show(self.graph) if 'labels' in locals(): nx.draw_networkx_labels(self.graph, graphdict, labels, font_size=8, font_weight='normal') edge_labels = nx.get_edge_attributes(self.graph, 'weight') #nx.draw_networkx_edge_labels(self.graph, graphdict,edge_labels=edge_labels,font_size=6) nx.draw_networkx_edges(self.graph, graphdict, edge_labels=edge_labels, width=0.1, edge_color='k', style='solid') plt.show(self.graph)
def main(): path = 'C:/Users/97899/Desktop/N/' single_nested = LoadDict(path + "Zuhe/single_nested_ex.txt") rich = pd.read_excel(path + "Richness/rich_null.xls") strong = pd.read_excel(path + "Network/Strong_index.xls") print(strong) A = [] for item in single_nested: for i in single_nested[item]: if i in A: continue else: A.append(i) # print(A,len(A)) # 各物种环的数量 D = {} D_rich = {} D_rich["cent"], D_rich["rich"] = [], [] for year in range(2009, 2021): path1 = path + "N_year/N_" + str(year) + '/Assemb/' + str( year) + '-' + str(0) + '.txt' Specise_set = LoadDict(path1) path3 = path + "N_year/N_" + str(year) + '/Spearman/' + str( year) + '-' + str(0) + '.txt' Spear_set = LoadDict(path3) for ex in range(1, 39): ex = float(ex) if [year, ex] not in A: path2 = path + "N_year/N_" + str(year) + '/CPmat/' + str( year) + '-' + str(ex) + '.txt' CP_mat = LoadDict(path2) if year < 2016: C_mat, Ass = Select_Zuhe(CP_mat, Specise_set[str(ex)], Spear_set[str(ex)]) else: C_mat, Ass = Select_Zuhe(CP_mat, Specise_set[ex], Spear_set[ex]) if np.all(C_mat == 0): continue else: node_list = Ass G = nx.DiGraph() G.add_nodes_from(node_list) # 添加点a edge_list = get_edge(C_mat, node_list) G.add_edges_from(edge_list) # 添加边,起点为x,终点为y cent = nx.betweenness_centrality(G) # print(Ass) print(nx.betweenness_centrality(G)) max_centr = max(cent.values()) print(max(cent.values())) '''取字典中的最大值''' # 考察最大中介中心性与物种多样性的关系 if max_centr > 0 and strong.loc[ex - 1, year] > -0.15: D_rich["cent"].append(max_centr) D_rich["rich"].append(strong.loc[ex - 1, year]) for jtem in cent: if jtem not in D.keys(): D[jtem] = [cent[jtem], 1] else: D[jtem] = [D[jtem][0] + cent[jtem], D[jtem][1] + 1] '''显示图形''' plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = 'SimHei' nx.draw(G, pos=nx.circular_layout(G), node_color='lightgreen', edge_color='black', with_labels=True, font_size=10, node_size=3000) # plt.show() # for item in D.keys(): # print(item,D[item][0]/D[item][1]) print(D_rich) plt.scatter(D_rich["rich"], D_rich["cent"]) plt.show()
# -*- coding: utf-8 -*- """ Created on Thu Oct 18 14:40:52 2018 @author: Administrator """ import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]) nx.draw(G, with_labels=True) plt.show() print(len(list(nx.simple_cycles(G)))) copyG = G.copy() copyG.remove_nodes_from([1]) copyG.remove_edges_from([(0, 1)]) print(len(list(nx.simple_cycles(copyG))))
def display(matrix, points): axis((-5, 10 * len(points.keys()) + 5, -5, 10 * len(points.keys()) + 5)) nx.draw(matrix.graph(), points) show()
def movie_map_example(): G = nx.balanced_tree(3, 3) # (splits per node, height h) nx.draw(G, pos=nx.spring_layout(G), with_labels=True)
print e pos = nx.spring_layout(self.__celltype_graph) node_size_list = [ self.__celltype_graph.node[vertex]['count'] * 10 for vertex in self.__celltype_graph ] edge_weights = [ edata['weight'] for u, v, edata in self.__celltype_graph.edges(data=True) ] plt.figure(1) nx.draw(self.__celltype_graph, pos, alpha=0.4, with_labels=True, node_size=node_size_list, edge_color=edge_weights, edge_cmap=plt.cm.jet, edge_vmin=min(edge_weights), edge_vmax=max(edge_weights)) #plt.show() plt.savefig(filename) print 'Saved figure in', filename def plot_celltype_graph_3d(self, filename='celltypes_graph_3d.png'): """Some eyecandi useful for presentations.""" if not has_mayavi: return numeric_graph = nx.convert_node_labels_to_integers( self.__celltype_graph) pos = nx.spring_layout(numeric_graph, dim=3)
edgeLables = {} for i in range(0, len(G)): key = (G[i][0], G[i][1]) value = G[i][2] edgeLables[key] = value #print("edge", edgeLables) SP = nx.from_pandas_edgelist(df1, source='Source Node', target='Destination Node', edge_attr=True) plt.figure(figsize=(8, 5)) pos = nx.layout.planar_layout(SP) #nx.draw(SP) nx.draw(SP, pos, with_labels=True) nx.draw_networkx_edge_labels(SP, pos, edge_labels=edgeLables) plt.show() a = createAdjMatrix(5, G) d = dijkstra(5, 3, a) #print(d) minLables = {} totalWeight = 0 for i in range(0, len(d)): key = (d[i][0], d[i][1]) value = d[i][2] #print(value) totalWeight += d[i][2] minLables[key] = value
# Assign position for each node (how it gets rendered with matplotlib) pos = {} pos.update((node, (0,index)) for index, node in enumerate(l)) #Critics pos.update((node, (1,index)) for index, node in enumerate(r)) #Movies # Change color of node based on whether its a critic or movie color_map = [] for node in bg: if node in l: color_map.append("red") else: color_map.append("blue") # Apply color and position changes, then display with matplotlib plt.figure(figsize=(30,30)) nx.draw(bg, pos=pos, node_color=color_map, with_labels=True,) #plt.show() ################################### ''' STEP 2 ''' ################################### # List the most important movie and most important critic for the following centrality metrics: degree, closeness, betweenness # Second argument could be l or r, score for all nodes are returned regardless dc = nx.bipartite.degree_centrality(bg, l) cc = nx.bipartite.closeness_centrality(bg, l) bc = nx.bipartite.betweenness_centrality(bg, l) DictLargestValue(dc, list(l), "degree") DictLargestValue(cc, list(l), "closeness")
for j in range(BUS_SIZE): for k in range(BUS_SIZE): if count + j != count + k: G.add_edge(count + j, count + k) # print("Added edge", count + j, "to", count + k) count += BUS_SIZE for i in range(EXTRA_FRIEND_CONNS): j = random.randint(0, NUM_STUDENTS-1) k = random.choice(list(range(0, j)) + list(range(j+1, NUM_STUDENTS))) G.add_edge(j, k) # print("Added edge", j, "to", k) print("Finished Constructing Graph") # Writing the graph to file nx.write_gml(G, 'graph.gml', nx.readwrite.gml.literal_stringizer) nx.draw(G) plt.savefig('graph.png') print("Finished Printing Graph") # Starting the parameter file param_file = open('parameters.txt', 'w') param_file.write(str(BUS_COUNT) + '\n') param_file.write(str(BUS_SIZE) + '\n') # Rowdy group generation rowdy_groups = [] count = 0 while count < NUM_ROWDY_GROUPS: num_in_group = random.randint(ROWDY_GROUP_MAX_SIZE - 2, ROWDY_GROUP_MAX_SIZE) # Can tune this range group = [] for i in range(num_in_group):
import pandas as pd # 显示中文,即字体设置 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['font.size'] = 10 plt.rcParams['axes.unicode_minus'] = False # 文件路径 file_dir = os.path.split(os.path.realpath('__file__'))[0] file_path = file_dir + os.sep + 'user_follow_list.csv' # 读取文件 df = pd.read_csv(file_path, header=None) df.columns = ['follow_id', 'follow_name', 'user_id', 'user_name'] print(df.head()) plt.figure(figsize=(20, 20)) G = nx.Graph() for index in df.index: G.add_edge(df.follow_name[index], df.user_name[index]) nx.draw(G, node_color='b', edge_color='r', with_labels=True, font_size=10, node_size=5) plt.savefig('network.png') plt.show()
## The inversing algorithm a*a^-1 = b*(-b)^-1(mod a) + 1 def inverse(a, b, g, h): ''' Compute the modular inverse of a mod b ''' ## show the procedure in a graph g.add_node(a) h.add_node(b) x = [n for n in g.nodes if g.out_degree(n) == 0] y = [n for n in h.nodes if h.out_degree(n) == 0] if x[0] != a: g.add_edge(x[0], a) if y[0] != b: h.add_edge(y[0], b) ## actually computing the function return (b * (a - inverse(b % a, a, g, h)) + 1) / a if a % b != 1 else 1 ## driver code g = nx.DiGraph() h = nx.DiGraph() a = int(input("input value a:")) b = int(input("input value b:")) print(f"The modular multiplcative inverse of a mod b is {inverse(a, b, g, h)}") posg = nx.kamada_kawai_layout(g) posh = nx.kamada_kawai_layout(h) plt.figure(f"values of a") nx.draw(g, posg, with_labels=True, edge_color="black", node_color="red") plt.figure(f"values of b") nx.draw(h, posh, with_labels=True, edge_color="black", node_color="red") plt.show()
# In[1]: import networkx as nx import matplotlib.pyplot as plt import pandas as pd from numpy import linalg as LA from collections import defaultdict # In[2]: Knetwork = nx.krackhardt_kite_graph() # In[4]: nx.draw(Knetwork, with_labels=True) # In[5]: #Adjacency matrix for the krackhardt_kite network Adjacency_matrix = [[0] * Knetwork.number_of_nodes() for i in range(Knetwork.number_of_nodes())] for row, column in list(Knetwork.edges): Adjacency_matrix[row][column] = 1 #edge exists between i and j so insert 1 Adjacency_matrix[column][ row] = 1 #value of Adjacency_matrix[j][i] equals Adjacency_matrix[i][j] since krackhardt_kite is an undirected graph # In[6]: eigen_values, eigen_vectors = LA.eig(Adjacency_matrix) eigenvector_centrality_vector = list(eigen_vectors[:, eigen_values.argmax()])
def graph_align(g1, g2, ops, title="", save=None, rna=False): """ Draw aligned graphs. """ f = nx.compose(g1, g2) path = reversed(list(ops.path_iter())) cost = ops.cost # for o in path: edit_edges = [] edge_list = [] color_list = [] for i, o in enumerate(path): e1, e2 = o.op if e1 == 'NILL' and e2 == 'NILL': continue f.add_edge(e1, e2, label='') edit_edges.append((e1, e2)) c = plt.get_cmap('Paired') pos = nx.spring_layout(f) # pos = rna_layout.circular_layout(f) # nx.draw_networkx(f, pos, color='red') config = {'node_size': 500, 'alpha': 1, 'font_size': 25} nx.draw(f, pos, nodelist=['NILL'], color='red', **config) nx.draw_networkx_edges(f, pos, edgelist=edit_edges, edge_color='grey', width=3) nx.draw_networkx_nodes(f, pos, nodelist=g1.nodes, node_color='blue', **config) nx.draw_networkx_edges(f, pos, edgelist=g1.edges) nx.draw_networkx_nodes(f, pos, nodelist=g2.nodes, node_color='green', **config) nx.draw_networkx_edges(f, pos, edgelist=g2.edges) make_label = lambda s: labels[s[:2]] + labels[s[0::2]] if len(set(s[1:])) == 2 \ else labels[s[:2]] edge_labels = {} for e in f.edges.data(): label = e[2]['label'] if label == 'B53': label = '' edge_labels[(e[0], e[1])] = label if rna: import matplotlib # matplotlib.rcParams['text.usetex'] = False matplotlib.rcParams['text.usetex'] = True params = {'text.latex.preamble': [r'\usepackage{fdsymbol}\usepackage{xspace}']} plt.rcParams.update(params) labels = { 'CW': r"$\medblackcircle$\xspace", 'CS': r"$\medblacktriangleright$\xspace", 'CH': r"$\medblacksquare$\xspace", 'TW': r"$\medcircle$\xspace", 'TS': r"$\medtriangleright$\xspace", 'TH': r"$\medsquare$\xspace" } make_label = lambda s: labels[s[:2]] + labels[s[0::2]] if len(set(s[1:])) == 2 \ else labels[s[:2]] edge_labels = {(e1, e2): make_label(d['label']) if d['label'] not in ['B53', ''] else '' for e1, e2, d in f.edges.data()} nx.draw_networkx_edge_labels(f, pos, edge_labels=edge_labels) else: nx.draw_networkx_edge_labels(f, pos, edge_labels=edge_labels, font_size=config['font_size']) plt.title(f"GED: {cost} " + title) if save: plt.savefig(save, format="pdf") plt.show() pass
def draw_graph(G): nx.draw(G) plt.show()
""" Exercise 2. Graph (discrete mathematics) """ import networkx as nx import numpy as np import matplotlib.pyplot as plt G = nx.Graph() G.add_edges_from( [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'), ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')]) val_map = {'A': 1.0, 'D': 0.5714285714285714, 'H': 0.0} values = [val_map.get(node, 0.25) for node in G.nodes()] nx.draw(G, cmap = plt.get_cmap('jet'), node_color = values) plt.show()
#this function calculates the weight of the of the function i.e no of subjects common for m,n def we(m, n): q = 0 for p in range(min(len(m), len(n))): if m[p] == 1 and n[p] == 1: q += 1 return q #adding edges to G if the nodes have a common subject for i in range(b): for j in range(i + 1, b): n = we(d[i], d[j]) if (n > 0): G.add_edge(c[i], c[j], weight=n) #drawing the obtained graph nx.draw(G, with_labels=True, node_color='b') plt.show() #finding the shortest path according to number of subjects they have in common for x in itertools.permutations(c, 2): s = [] t = 0 for p in nx.all_shortest_paths(G, source=x[0], target=x[1]): if G[p[0]][p[1]]['weight'] > t: t = G[p[0]][p[1]]['weight'] s = p fin.append(s) #printing all the shortest paths for i in fin: print(i)
('E', 'B', 50), ('E', 'G', 30), ('F', 'C', 10), ('F', 'D', 40), ('G', 'A', 20), ('G', 'D', 20), ]) posicoes = { 'A': (1.5, 1.5), 'B': (0, 2), 'C': (2.2, 3.8), 'D': (2.5, 1.8), 'E': (0.3, 0), 'F': (0.6, 4), 'G': (2, .3), 'H': (2.7, 3.5), } caminhos = nx.single_source_dijkstra_path(G, 'A') # Todos os caminhos do A para todos os outros vértices distancias = nx.single_source_dijkstra_path_length(G, 'A') # Distancias mais curtas para todos os vértices caminhos_od = collections.OrderedDict(sorted(caminhos.items())) print(caminhos_od) print("\nCaminhos a partir do nodo 'A'") for caminho in caminhos.values(): distancia = distancias[caminho[-1]] print(f'Caminho de A até {caminho[-1]:}', caminho, 'Distância:', distancia) rotulos = nx.get_edge_attributes(G, 'weight') nx.draw(G, posicoes, with_labels=True, connectionstyle='arc3, rad=0.1') nx.draw_networkx_edge_labels(G, posicoes, edge_labels=rotulos, label_pos=0.3)
g, 'nacp_c9e4d7dd-d6b7-44b8-9e26-12e756d36e04', 2) # Chart of president + companies + people g_pres_com_node_colors = [] for node in g_pres_com.nodes(data=True): if node[0] == 'nacp_c9e4d7dd-d6b7-44b8-9e26-12e756d36e04': g_pres_com_node_colors.append('red') elif bool(re.search('nacp_', node[0])): g_pres_com_node_colors.append('lightblue') else: g_pres_com_node_colors.append('gold') nx.draw(g_pres_com, node_size=10, node_color=g_pres_com_node_colors, width=0.05) plt.savefig("g_pres_com_2.png", format="PNG", dpi=200, figsize=(8, 6)) del g_pres_com_node_colors # Prepare table for this chart g_pres_com_edges_df = pd.DataFrame(data=list(g_pres_com.edges), columns=['node1', 'node2']) g_pres_com_edges_df['node_person'] = np.where( g_pres_com_edges_df['node1'].str.contains('nacp'), g_pres_com_edges_df['node1'], g_pres_com_edges_df['node2'])
print(graph.get_edge_data(*edge)) pos = nx.circular_layout(graph) #cols = np.log10(j_list) cols = j_list cmap = plt.cm.viridis jmin = 0. #min(cols) jmax = 1.5 #max(cols) fig, ax = plt.subplots(figsize=(8, 8)) nx.draw(graph, pos, node_color='#787878', edge_color=cols, width=4, edge_cmap=cmap, with_labels=False, edge_vmin=jmin, edge_vmax=jmax) nx.draw_networkx_labels(graph, pos, font_color='white') scalarMap = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=jmin, vmax=jmax)) scalarMap._A = [] cbar = fig.colorbar(scalarMap, orientation='horizontal', pad=0.05) cbar.ax.set_title('Bond Strength') txt = 'P(sync) = ({0:.2f} $\pm$ {1:.2f})%' ax.annotate(txt.format(*var), xy=(0., .9),