def draw_graph(counter_total, counter_lives, counter_deaths, n=20): """Draw graph of survival depending on sequence. Parameters: counter_total - Counter object with total number of sequences counter_lives - Counter object with number of sequences without death date counter_deaths - Counter object with number of sequences with death date n - specifies how many of the sequences with highest death rate should be printed to output. If set to 0 then all sequences will be printed """ print 'Creating graph' node_labels = {} edge_labels = {} graph = nx.DiGraph() graph.add_node(0) node_labels[0] = 'End' i = 1 for k, v in counter_total.most_common(n) if n else counter_total.most_common(): lastI = 0 for medicine in reversed(k.split(';')): graph.add_edge(i, lastI) edge_labels[(i, lastI)] = medicine lastI = i i += 1 node_labels[lastI] = '{0}%'.format(100 * counter_deaths[k] / v) print 'Graph created' layout = nx.graphviz_layout(graph) print 'Graph layout created' nx.draw(graph, pos = layout, hold = True, node_color = 'w', node_size = 1000) nx.draw_networkx_labels(graph, layout, labels = node_labels) nx.draw_networkx_edge_labels(graph, layout, edge_labels = edge_labels) plt.show()
def _graph_intelligence_nx(bot, file_path): # TODO: Make BehaviorGraph track the launch node and mark it in the graph output print("Saving Champion Intelligence Graph...") behavior_nodes = bot.behavior.behavior_nodes network = nx.DiGraph() network.add_nodes_from(behavior_nodes) # Add the behavior nodes to the network and link them together for node in behavior_nodes: if node.node_type == NodeRegister.statement: network.add_edge(node, node.next_node, label='') elif node.node_type == NodeRegister.conditional: network.add_edge(node, node.true_node, label='1') network.add_edge(node, node.false_node, label='0') # Draw the network layout = nx.shell_layout(network, scale=3) plt.figure(figsize=(10, 10)) plt.axis('equal') plt.title("%s: Born:%s, Age:%s, Peak Energy:%s, Children:%s" % (str(bot), str(bot.birthday), str(bot.age), str(bot.peak_energy), str(bot.number_children))) nx.draw_networkx_edges(network, layout, width=0.5, alpha=0.75, edge_color='black', arrows=True) statement_color = '#D7E7F7' conditional_color = '#F7D7DA' colors = [statement_color if node.node_type == NodeRegister.statement else conditional_color for node in network.nodes()] nx.draw_networkx_nodes(network, layout, node_size=1800, node_color=colors, alpha=1) # Reformat node names to make them easier to read names = [(node, str(node.function.__name__).replace('_', '\n')) for node in behavior_nodes] labels = {key: value for (key, value) in names} nx.draw_networkx_labels(network, layout, labels, font_size=10, font_family='sans-serif') edge_names = nx.get_edge_attributes(network, 'label') nx.draw_networkx_edge_labels(network, layout, edge_labels=edge_names, label_pos=0.7) plt.axis('off') plt.savefig(file_path + '.png', dpi=80, pad_inches=0.0, bbox_inches='tight')
def draw_graphs(G,edge_pro_dict,Gmp,Ggp,Gadr,Gabm): plt.figure(1) pos=nx.spring_layout(G) # positions for all nodes nx.draw_networkx_nodes(G,pos,noG=800) nx.draw_networkx_edges(G,pos) nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif') nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_pro_dict) plt.figure(2) nx.draw_networkx_nodes(Gmp,pos,noG=800) nx.draw_networkx_edges(Gmp,pos) nx.draw_networkx_labels(Gmp,pos,font_size=10,font_family='sans-serif') plt.figure(3) nx.draw_networkx_nodes(Ggp,pos,noG=800) nx.draw_networkx_edges(Ggp,pos) nx.draw_networkx_labels(Ggp,pos,font_size=10,font_family='sans-serif') plt.figure(4) nx.draw_networkx_nodes(Gadr,pos,noG=800) nx.draw_networkx_edges(Gadr,pos) nx.draw_networkx_labels(Gadr,pos,font_size=10,font_family='sans-serif') plt.figure(5) nx.draw_networkx_nodes(Gabm,pos,noG=800) nx.draw_networkx_edges(Gabm,pos) nx.draw_networkx_labels(Gabm,pos,font_size=10,font_family='sans-serif') plt.show()
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 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 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 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 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 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(self,figure): changed = False for ip in self.stats: if ip is not "127.0.0.1" and not self.graph.has_node(ip): self.graph.add_node(ip,node_size=4000,node_shape="s") self.graph.add_edge(ip,"127.0.0.1",attr_dict={"label":"N/A"}) changed = True for port in self.stats[ip]: #pnode = ip + ":" + port pnode = port if not self.graph.has_node(pnode): statName = ip + ":" + port self.graph.add_node(pnode,attr_dict={"node_size":700,"node_shape":"o","font_size":8}) self.graph.add_edge(pnode ,ip, attr_dict={"label":"N/A"}) changed = True if changed: figure.clf() pos = nx.spring_layout(self.graph, weight=None, iterations=100, scale = 2) #draw ip nodes ipNodeList = list(self.stats) #print(ipNodeList) try: nx.draw_networkx(self.graph, nodelist = ipNodeList, pos = pos, with_labels = True, node_size = 4000 , node_shape = "p", font_size = 8 ) except nx.exception.NetworkXError: # catch some error about a node not having a position yet (we just re-render, that does it) pass #draw port nodes portList = list(self.stats.values()) portNodesList = [ item for sublist in (list(e) for e in portList) for item in sublist ] try: nx.draw_networkx_nodes(self.graph, nodelist = portNodesList, pos = pos , with_labels = True, node_size = 700 , node_shape = "o", font_size=8 ) edges = self.graph.edges(data=True) labels = {} for (a, b, *c) in edges: stats = "N/A" if a in self.stats: if b in self.stats[a]: labels[a,b] = self.stats[a][b] else: if a in self.stats[b]: labels[b,a] = self.stats[b][a] nx.draw_networkx_edge_labels(self.graph, pos = pos, edge_labels=labels,ax=None) except nx.exception.NetworkXError: # catch some error about a node not having a position yet (we just re-render, that does it) pass # draw connStats statNodesList = list(self.statNodes) figure.canvas.draw()
def report_ctg(ctg, filename): """ Reports Clustered Task Graph in the Console and draws CTG in file :param ctg: clustered task graph :param filename: drawing file name :return: None """ print "===========================================" print " REPORTING CLUSTERED TASK GRAPH" print "===========================================" cluster_task_list_dict = {} cluster_weight_dict = {} for node in ctg.nodes(): print ("\tCLUSTER #: "+str(node)+"\tTASKS:"+str(ctg.node[node]['TaskList'])+"\tUTILIZATION: " + str(ctg.node[node]['Utilization'])) cluster_task_list_dict[node] = ctg.node[node]['TaskList'] for edge in ctg.edges(): print ("\tEDGE #: "+str(edge)+"\tWEIGHT: "+str(ctg.edge[edge[0]][edge[1]]['Weight'])) cluster_weight_dict[edge] = ctg.edge[edge[0]][edge[1]]['Weight'] print ("PREPARING GRAPH DRAWINGS...") pos = networkx.shell_layout(ctg) networkx.draw_networkx_nodes(ctg, pos, node_size=2200, node_color='#FAA5A5') networkx.draw_networkx_edges(ctg, pos) networkx.draw_networkx_edge_labels(ctg, pos, edge_labels=cluster_weight_dict) networkx.draw_networkx_labels(ctg, pos, labels=cluster_task_list_dict) plt.savefig("GraphDrawings/"+filename) plt.clf() print ("\033[35m* VIZ::\033[0mGRAPH DRAWINGS DONE, CHECK \"GraphDrawings/"+filename+"\"") return None
def 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 draw_graph(self, H, u, v, flow1, F1, flow2, F2): if not HAVE_PLT: return pos = nx.spring_layout(self.G) plt.subplot(1,2,1) plt.axis('off') nx.draw_networkx_nodes(self.G,pos) nx.draw_networkx_edges(self.G,pos) nx.draw_networkx_labels(self.G,pos) nx.draw_networkx_edge_labels( self.G, pos, edge_labels={(u,v):'{}/{}'.format( F1[u][v], self.G[u][v]['capacity'] ) for (u,v,data) in nx.to_edgelist(self.G)}) plt.title('before: flow={}'.format(flow1)) plt.subplot(1,2,2) plt.axis('off') nx.draw_networkx_nodes(self.G,pos) nx.draw_networkx_edges(self.G,pos) nx.draw_networkx_edges( self.G, pos, edgelist=[(u,v)], width=3.0, edge_color='b') nx.draw_networkx_labels(self.G,pos) nx.draw_networkx_edge_labels( self.G, pos, edge_labels={(u,v):'{}/{}'.format( F2[u][v],H[u][v]['capacity'] ) for (u,v,data) in nx.to_edgelist(self.G)}) plt.title('after: flow={}'.format(flow2))
def show_map(graph_data, node_colors = None): G = nx.Graph(graph_data['graph_dict']) node_colors = node_colors or graph_data['node_colors'] node_positions = graph_data['node_positions'] node_label_pos = graph_data['node_label_positions'] edge_weights= graph_data['edge_weights'] # set the size of the plot plt.figure(figsize=(18,13)) # draw the graph (both nodes and edges) with locations from romania_locations nx.draw(G, pos={k: node_positions[k] for k in G.nodes()}, node_color=[node_colors[node] for node in G.nodes()], linewidths=0.3, edgecolors='k') # draw labels for nodes node_label_handles = nx.draw_networkx_labels(G, pos=node_label_pos, font_size=14) # add a white bounding box behind the node labels [label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in node_label_handles.values()] # add edge lables to the graph nx.draw_networkx_edge_labels(G, pos=node_positions, edge_labels=edge_weights, font_size=14) # add a legend white_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="white") orange_circle = lines.Line2D([], [], color="orange", marker='o', markersize=15, markerfacecolor="orange") red_circle = lines.Line2D([], [], color="red", marker='o', markersize=15, markerfacecolor="red") gray_circle = lines.Line2D([], [], color="gray", marker='o', markersize=15, markerfacecolor="gray") green_circle = lines.Line2D([], [], color="green", marker='o', markersize=15, markerfacecolor="green") plt.legend((white_circle, orange_circle, red_circle, gray_circle, green_circle), ('Un-explored', 'Frontier', 'Currently Exploring', 'Explored', 'Final Solution'), numpoints=1, prop={'size':16}, loc=(.8,.75)) # show the plot. No need to use in notebooks. nx.draw will show the graph itself. plt.show()
def draw(self): g = self.graph pos = nx.spring_layout(self.graph,scale=2) node_colors = [] for node in g.nodes(): if self.is_logical_node(node): node_colors.append('g') else: node_colors.append('r') nx.draw_networkx_nodes(g, pos, nodelist=g.nodes(), node_color=node_colors, node_size=500, alpha=0.8) nx.draw_networkx_edges(g, pos, edgelist=g.edges(), edge_color=[( (float(g[u][v]['capacity'])*0.01)+10000 ) for (u,v) in g.edges()], edge_vmin=100, edge_vmax=1000, width=5, alpha=0.8) #nx.draw(self.graph,pos,font_size=8) #nxd.draw(self.graph) node_labels = {} for node in g.nodes(): node_labels[node] = str(node) nx.draw_networkx_labels(g, pos, node_labels, font_size=10) edge_labels = {} for edge in g.edges(): edge_labels[edge] = g[edge[0]][edge[1]]['capacity'] nx.draw_networkx_edge_labels(g, pos, edge_labels, font_size=10) #nx.draw(g) #plt.draw() plt.axis('off') plt.show()
def plot_graph(wgraph, pos=None): """Conveniently summarize graph visually""" # Plot nodes with size according to count sizes = [] degrees = [] for n, d in wgraph.nodes_iter(data=True): sizes.append(d['count']) degrees.append(wgraph.degree(n)) sizes = rescale_arr(np.array(sizes, dtype=float), 100, 1000) # Compute layout and label edges according to weight pos = nx.spring_layout(wgraph) if pos is None else pos labels = {} width = [] for n1, n2, d in wgraph.edges_iter(data=True): w = d['weight'] labels[n1, n2] = w width.append(w) # remap width to 1-10 range width = rescale_arr(np.array(width, dtype=float), 1, 15) # Create figure fig = plt.figure() ax = fig.add_subplot(111) fig.subplots_adjust(0,0,1) nx.draw_networkx_nodes(wgraph, pos, node_size=sizes, node_color=degrees, alpha=0.8) nx.draw_networkx_labels(wgraph, pos, font_size=15, font_weight='bold') nx.draw_networkx_edges(wgraph, pos, width=width, edge_color=width, edge_cmap=plt.cm.Blues) nx.draw_networkx_edge_labels(wgraph, pos, edge_labels=labels) ax.set_title('Node color:degree, size:count, edge: co-occurrence count')
def TempCvsCgrapher(OriginalDict, DicDic): G = nx.DiGraph() keys1 = DicDic.keys() for item1 in keys1: G.add_node(item1) for item in keys1: Dic2 = DicDic[item] #f.write( item + " has "+ str(len(XMLutility.DicToList(Dic2))) +" " + key1 Keys2 = Dic2.keys() for item2 in Keys2: G.add_weighted_edges_from( [(item, item2, len(Dic2[item2]))] ) #G.add_edge(item, item2, weight = len(Dic2[item2])) #nx.draw(G, with_labels = True) edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) edge_colors = ['black' for edge in G.edges()] pos=nx.spring_layout(G) nx.draw_networkx_edge_labels(G,pos, edge_labels=edge_labels) nx.draw(G ,pos, with_labels = True, edge_color=edge_colors, arrows =True) plt.show()
def hgt_graph(HGT_dict): dict2 = dict() for i in HGT_dict: dict2[i] = len(HGT_dict[i]) G = nx.Graph() li = [] for k in HGT_dict: s,v = k li.append(v) li.append(s) li2 = [] for key in dict2: s,v = key li2.append((s,v,dict2[key])) uniq = [] for node in set(li): uniq.append(node) G.add_nodes_from(uniq) G.add_weighted_edges_from(li2) pos = nx.spring_layout(G) nx.draw(G,pos) nx.draw_networkx_edge_labels(G,pos) plt.savefig("HGT_graph.png")
def dibujarGrafo(nodos): import networkx as nx import matplotlib.pyplot as plt if debug: print "---- DIBUJANDO GRAFO ----" print "Si el grafo sale muy amontonado, volver a ejecutar el python" print "NOTA: El nodo mayor es la raiz" #print "Nodos:\n", nodos G = nx.DiGraph() # Se crea un grafo vacio R = [tupla[0] for tupla in nodos] # Se crean los nodos G.add_edges_from(R) # Se agregan los nodos al grafo vacio pos = nx.spring_layout(G) # diseno y posiciones # dibujamos todo nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) for nodosUnion, valorArista in nodos: nx.draw_networkx_edge_labels(G, pos, { nodosUnion : valorArista } ) plt.savefig("Huffman.png"); # guardamos en archivo plt.show() # abrimos la ventana return
def drawGraph(G): pos = nx.spring_layout(G) edge_labels = dict([((u, v,), d['weight']) for u, v, d in G.edges(data=True)]) nx.draw(G, pos, with_labels=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.show()
def export_graph( graph_in, base_dir=None, show=False, use_execgraph=False, show_connectinfo=False, dotfilename="graph.dot", format="png", simple_form=True, ): """ Displays the graph layout of the pipeline This function requires that pygraphviz and matplotlib are available on the system. Parameters ---------- show : boolean Indicate whether to generate pygraphviz output fromn networkx. default [False] use_execgraph : boolean Indicates whether to use the specification graph or the execution graph. default [False] show_connectioninfo : boolean Indicates whether to show the edge data on the graph. This makes the graph rather cluttered. default [False] """ graph = deepcopy(graph_in) if use_execgraph: graph = generate_expanded_graph(graph) logger.debug("using execgraph") else: logger.debug("using input graph") if base_dir is None: base_dir = os.getcwd() if not os.path.exists(base_dir): os.makedirs(base_dir) outfname = fname_presuffix(dotfilename, suffix="_detailed.dot", use_ext=False, newpath=base_dir) logger.info("Creating detailed dot file: %s" % outfname) _write_detailed_dot(graph, outfname) cmd = "dot -T%s -O %s" % (format, outfname) res = CommandLine(cmd, terminal_output="allatonce").run() if res.runtime.returncode: logger.warn("dot2png: %s", res.runtime.stderr) pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form) outfname = fname_presuffix(dotfilename, suffix=".dot", use_ext=False, newpath=base_dir) nx.write_dot(pklgraph, outfname) logger.info("Creating dot file: %s" % outfname) cmd = "dot -T%s -O %s" % (format, outfname) res = CommandLine(cmd, terminal_output="allatonce").run() if res.runtime.returncode: logger.warn("dot2png: %s", res.runtime.stderr) if show: pos = nx.graphviz_layout(pklgraph, prog="dot") nx.draw(pklgraph, pos) if show_connectinfo: nx.draw_networkx_edge_labels(pklgraph, pos)
def draw_graph(arr_graph): """ Draw a directed graph. """ try: import matplotlib.pyplot as plt except: raise import networkx as nx g = nx.DiGraph() edge_set = {} # Set the edges and nodes for i in range(len(arr_graph)): for j in range(len(arr_graph[i])): if arr_graph[i][j] is not 0 and arr_graph[i][j] is not sys.maxsize: g.add_edge(i, j, weight=0.1) edge_set[(i, j)] = arr_graph[i][j] # Positions for all nodes. pos = nx.spring_layout(g) # Nodes nx.draw_networkx_nodes(g, pos, node_size=700, node_color="white") # Edges nx.draw_networkx_edges(g, pos, width=2, alpha=0.5, edge_color='black') # Labels nx.draw_networkx_labels(g, pos, font_size=15, font_family='sans-serif') # Edges' labels nx.draw_networkx_edge_labels(g, pos, edge_set, label_pos=0.3) plt.axis('off') # plt.savefig("weighted_graph.png") # Save as png. plt.show() # Display
def draw(self, highlight_edges=None, show_weights=False, save_draw=False, map_name = 'duckietown_map'): plt.close('all') nxg = nx.DiGraph() edges = [(e.source, e.target, {'weight':e.weight, 'inv_weight':1.0/e.weight, 'action':e.action}) for node_set in self._edges.values() for e in node_set] nxg.add_edges_from(edges) if len(self.node_positions) < len(self._nodes): # Calculate positions for nodes whose pos is not specified. pos = nx.spring_layout(nxg, weight='inv_weight', pos=self.node_positions, fixed=self.node_positions.keys() if self.node_positions else None) else: pos = self.node_positions f = plt.figure(figsize=(12,20)) plt.gca().set_aspect('auto') nx.draw_networkx_nodes(nxg, pos, node_color='w') nx.draw_networkx_edges(nxg, pos, edges) nx.draw_networkx_labels(nxg, pos) if show_weights: edge_labels=dict([((u,v,),"%s" % (d['weight'])) for u,v,d in nxg.edges(data=True)]) nx.draw_networkx_edge_labels(nxg, pos, edge_labels=edge_labels) if highlight_edges: nx.draw_networkx_edges(nxg, pos, highlight_edges, edge_color='r') plt.axis('off') if not save_draw: plt.show() else: script_dir = os.path.dirname(__file__) map_path = script_dir + '/maps/' + map_name + '.png' plt.savefig(map_path)
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 draw(self, highlight_edges=None): nxg = nx.DiGraph() edges = [(e.source, e.target, {'weight':e.weight, 'inv_weight':1.0/e.weight}) for node_set in self._edges.values() for e in node_set] nxg.add_edges_from(edges) if len(self.node_positions) < len(self._nodes): # Calculate positions for nodes whose pos is not specified. pos = nx.spring_layout(nxg, weight='inv_weight', pos=self.node_positions, fixed=self.node_positions.keys() if self.node_positions else None) else: pos = self.node_positions f = plt.figure(figsize=(12,12)) plt.gca().set_aspect('equal', adjustable='box') nx.draw_networkx_nodes(nxg, pos, node_color='w') nx.draw_networkx_edges(nxg, pos, edges) nx.draw_networkx_labels(nxg, pos) edge_labels=dict([((u,v,),"%s" % d['weight']) for u,v,d in nxg.edges(data=True)]) nx.draw_networkx_edge_labels(nxg, pos, edge_labels=edge_labels) if highlight_edges: nx.draw_networkx_edges(nxg, pos, highlight_edges, edge_color='r') plt.axis('off') plt.show()
def plot_graph(g): pos = nx.spring_layout(g) pylab.figure(1) nx.draw(g, pos) edge_labels = dict([((u, v), d['weight']) for u, v, d in g.edges(data=True)]) nx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels) pylab.show()
def display_graph(graph, edge_width=2): nodes = graph.nodes(data=True) edges = graph.edges(data=True) edgecapwidth = [d['capacity'] for (u,v,d) in edges] edgeloadwidth = [d['load'] for (u,v,d) in edges] max_cap = 1.0 for i in range(len(edgeloadwidth)): # reverse edges for negative load if edgeloadwidth[i] < 0: u,v,d = edges[i] edges[i] = (v,u,d) for cap in edgecapwidth: # get max cap to scale edge drawing if cap > max_cap: max_cap = cap width_mod = edge_width/(1.0*max_cap) for i in range(len(edgecapwidth)): edgecapwidth[i] *= width_mod edgeloadwidth[i]*= width_mod #labels = [str(d['load']) + '/' + str(d['capacity']) for u,v,d in edges] labels = [str(abs(round(d['load'],3))) + '/' + str(round(d['capacity'],3)) for u,v,d in edges] e_labels=dict(zip(graph.edges(), labels)) pos = nx.spring_layout(graph, iterations=100) nx.draw_networkx_nodes(graph, pos, node_size=300) nx.draw_networkx_labels(graph,pos) nx.draw_networkx_edges(graph, pos, edgelist=edges, width=edgecapwidth,edge_color = 'b') nx.draw_networkx_edges(graph, pos, edgelist=edges, width=edgeloadwidth,edge_color = 'r', alpha = 0.9) labels=dict(zip(graph.edges(),[d for u,v,d in graph.edges(data=True)])) nx.draw_networkx_edge_labels(graph, pos, edge_labels=e_labels) plt.show()
def draw_graph(graph, graph_layout='shell', node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif', save=True, filename=None): edge_labels=dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(graph) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(graph) elif graph_layout == 'random': graph_pos=nx.random_layout(graph) elif graph_layout == 'circular': graph_pos=nx.circular_layout(graph) else: graph_pos=nx.shell_layout(graph) # draw graph nx.draw_networkx_nodes(graph, graph_pos, node_size=node_size, alpha=node_alpha, node_color=node_color) nx.draw_networkx_edges(graph, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) nx.draw_networkx_labels(graph, graph_pos, font_size=node_text_size, font_family=text_font) nx.draw_networkx_edge_labels(graph, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos) # show graph if save == True: plt.savefig(filename, dpi=1000) plt.show()
def draw_geograph(g, node_color='r', edge_color='b', node_label_field=None, edge_label_field=None, node_size=200, node_label_x_offset=0, node_label_y_offset=0, node_label_font_size=12, node_label_font_color='k'): """ Simple function to draw a geograph via matplotlib/networkx Uses geograph coords (projects if needed) as node positions """ # transform to projected if not done so flat_coords = g.transform_coords(gm.PROJ4_FLAT_EARTH) node_pos = {nd: flat_coords[nd] for nd in g.nodes()} label_pos = {nd: [flat_coords[nd][0] + node_label_x_offset, flat_coords[nd][1] + node_label_y_offset] for nd in g.nodes()} # Draw nodes nx.draw_networkx(g, pos=node_pos, node_color=node_color, with_labels=False, edge_color=edge_color, node_size=node_size) if node_label_field: if node_label_field != 'ix': label_vals = nx.get_node_attributes(g, node_label_field) nx.draw_networkx_labels(g, label_pos, labels=label_vals, font_size=node_label_font_size, font_color=node_label_font_color) else: # label via ids nx.draw_networkx_labels(g, label_pos, labels=g.nodes(), font_size=node_label_font_size, font_color=node_label_font_color) # handle edge labels if needed if edge_label_field: edge_labels = nx.get_edge_attributes(g, edge_label_field) nx.draw_networkx_edge_labels(g, pos=node_pos, edge_labels=edge_labels)
def show_graph(self): graph = nx.Graph(self.graph) pos = nx.circular_layout(graph) # pos=nx.spectral_layout(graph) nx.draw_networkx_nodes(graph, pos, node_color="r", node_size=500, alpha=0.8) nx.draw_networkx_edges(graph, pos, width=1, alpha=0.5) nx.draw_networkx_edges( graph, pos, edge_labels={}, edgelist=self.get_edgelist(), width=8, alpha=0.5, edge_color="r" ) nx.draw_networkx_edge_labels(graph, pos, self.get_list_weights_edge(), label_pos=0.3) labels = self.set_labels() nx.draw_networkx_labels(graph, pos, labels, font_size=16) plt.title("Dijkstra") plt.text( 0.5, 0.97, "Start: " + str(self.start) + " End: " + str(self.end), horizontalalignment="center", transform=plt.gca().transAxes, ) plt.text( 0.5, 0.94, "Shortest Path: " + str(self.shortest_path), horizontalalignment="center", transform=plt.gca().transAxes, ) plt.text( 0.5, 0.90, "Weights: " + str(self.weights), horizontalalignment="center", transform=plt.gca().transAxes ) plt.text(0.5, 0.86, "Pred: " + str(self.Preds), horizontalalignment="center", transform=plt.gca().transAxes) plt.axis("off") plt.ion() plt.show()
def main(): try: # -h help -t timeline -g graph -s save -i infile_name opts, args = getopt.getopt(sys.argv[1:], "hi:rtgwp", ['inf', 'sup']) except getopt.GetoptError as err: usage() str(err) # will print something like "option -a not recognized" sys.exit(2) data = Data() data_name = '' display_timeline = False display_graph = False write_solution = False read_solution = False print_results = False calc_inf = True for o, a in opts: if o == '-h': usage() sys.exit() elif o == "-i": data_name = a data.read_file('Instances/' + a + '.full') elif o == '-s': read_solution = True elif o == '-t': display_timeline = True elif o == '-g': display_graph = True elif o == '-w': write_solution = True elif o == '-p': print_results = True elif o == '--inf': # inf by default calc_inf = True elif o == '--sup': # if not inf, then sup calc_inf = False else: assert False, "unhandled option" if display_graph: plt.subplot(111) pos = nx.spring_layout(data.graph, scale=0.5) nx.draw_networkx(data.graph, pos=pos) nx.draw_networkx_edge_labels(data.graph, pos=pos, edge_labels=data.get_edges_labels(), label_pos=0.5) plt.show() if read_solution: solution = Solution(data.graph) solution.read_file('Solutions/' + data_name + '.' + solution.name) solution.create_timeline() if solution.is_valid: solution.due_dates_valid = True solution.rates_valid = True else: solution.check_valid() elif calc_inf: solution = borne_inf(data) else: solution = borne_sup(data) solution.create_timeline() if print_results: print('-----' + data_name + '-----') print('Calculated objective:', solution.obj_value) print('Rates verification:', solution.rates_valid) print('Due dates verification:', solution.due_dates_valid) print('Calculation time:', solution.calc_time) if display_timeline: solution.display_timeline() if write_solution: solution.write_file('Solutions/' + data_name + '.' + solution.name)
[2, 3, 2], [2, 4, 2], [2, 5, 4], [3, 4, 5], [4, 6, 3], [5, 4, 2], [5, 6, 2],]) #Drawing the graph G = nx.DiGraph() G.add_nodes_from([1,2,3,4,5,6]) G.add_weighted_edges_from([(1,2, 3),(1,3, 2),(2,3,2),(2,4,2),(2,5,4),(3,4,5),(4,6,3),(5,4,2),(5,6,2)]) shells=[[6,5,2,1,3,4]] pos = nx.shell_layout(G, shells) nx.draw(G,pos=pos, with_labels=True, font_weight='bold') labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos=pos,edge_labels=labels) plt.show() parent, d = FIFO_ShortestPath(FStar, 1) #Draw the shortest path tree G = nx.DiGraph() G.add_nodes_from([1,2,3,4,5,6]) G.add_weighted_edges_from([(1,2, 3),(1,3, 2),(2,4,2),(2,5,4),(4,6,3)]) shells=[[6,5,2,1,3,4]] pos = nx.shell_layout(G, shells) plt.title("Parent = " + str(parent[1:]) + " , Distance, d = " + str(d[1:])) nx.draw(G,pos=pos, with_labels=False, font_weight='bold', node_size=2000) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos=pos,edge_labels=labels) nx.draw_networkx_labels(G, pos, labels={l:"%d, %s"%(l,d[l]) for l in range(1,7)})
def run(self, node, bidir, output_file, edge_label, json): try: import matplotlib.pyplot as plt import networkx as nx except ImportError: print('Drawing topology requires `matplotlib` and `networkx` ' 'libraries. You can install them with following command and ' 'retry. \n' ' pip install matplotlib\n' ' pip install networkx') sys.exit(1) rem_str = { '.facebook.com': '', '.tfbnw.net': '', } rem_str = dict((re.escape(k), v) for k, v in rem_str.items()) rem_pattern = re.compile("|".join(rem_str.keys())) publication = self.client.dump_all_with_prefix(Consts.ADJ_DB_MARKER) nodes = list(self.get_node_to_ips().keys()) if not node else [node] adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir, self.iter_publication) if json: return self.topology_json_dump(adjs_map.items()) G = nx.Graph() adj_metric_map = {} node_overloaded = {} for this_node_name, db in adjs_map.items(): node_overloaded[rem_pattern.sub( lambda m: rem_str[re.escape(m.group(0))], this_node_name)] = db['overloaded'] for adj in db['adjacencies']: adj_metric_map[(this_node_name, adj['ifName'])] = adj['metric'] for this_node_name, db in adjs_map.items(): for adj in db['adjacencies']: adj['color'] = 'r' if adj['isOverloaded'] else 'b' adj['adjOtherIfMetric'] = adj_metric_map[(adj['otherNodeName'], adj['otherIfName'])] G.add_edge( rem_pattern.sub(lambda m: rem_str[re.escape(m.group(0))], this_node_name), rem_pattern.sub(lambda m: rem_str[re.escape(m.group(0))], adj['otherNodeName']), **adj) # hack to get nice fabric # XXX: FB Specific pos = {} eswx = 0 sswx = 0 fswx = 0 rswx = 0 blue_nodes = [] red_nodes = [] for node in G.nodes(): if (node_overloaded[node]): red_nodes.append(node) else: blue_nodes.append(node) if 'esw' in node: pos[node] = [eswx, 3] eswx += 10 elif 'ssw' in node: pos[node] = [sswx, 2] sswx += 10 elif 'fsw' in node: pos[node] = [fswx, 1] fswx += 10 elif 'rsw' in node: pos[node] = [rswx, 0] rswx += 10 maxswx = max(eswx, sswx, fswx, rswx) if maxswx > 0: # aesthetically pleasing multiplier (empirically determined) plt.figure(figsize=(maxswx * 0.5, 8)) else: plt.figure(figsize=(min(len(G.nodes()) * 2, 150), min(len(G.nodes()) * 2, 150))) pos = nx.spring_layout(G) plt.axis('off') edge_colors = [] for _, _, d in G.edges(data=True): edge_colors.append(d['color']) nx.draw_networkx_nodes(G, pos, ax=None, alpha=0.5, node_color='b', nodelist=blue_nodes) nx.draw_networkx_nodes(G, pos, ax=None, alpha=0.5, node_color='r', nodelist=red_nodes) nx.draw_networkx_labels(G, pos, ax=None, alpha=0.5, font_size=8) nx.draw_networkx_edges(G, pos, ax=None, alpha=0.5, font_size=8, edge_color=edge_colors) edge_labels = {} if node: if edge_label: edge_labels = { (u, v): '<' + str(d['otherIfName']) + ', ' + str(d['metric']) + ' > <' + str(d['ifName']) + ', ' + str(d['adjOtherIfMetric']) + '>' for u, v, d in G.edges(data=True) } nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=6) print('Saving topology to file => {}'.format(output_file)) plt.savefig(output_file)
def draw_gragh(node_wlibnames, file_name): """ :param node_models: :return: """ g = nx.DiGraph() g.add_nodes_from(node_wlibnames) edge_list_s = [] edge_list_d = [] res = [] user = User.objects.get(id=1) operator1 = ('*', '◇','~') operator2 = ('∪', '∩', '✱', 'ㄨ') # ================== for each wlibnames , check relation ============================ for ind_1, t1 in enumerate(node_wlibnames): for ind_2, t2 in enumerate(node_wlibnames[ind_1 + 1:]): try: nexus = Nexus.objects.get(r_name='<=') except: nexus = Nexus.objects.create(r_name='<=') #A <= A∪B #A∩B <= A #A✱B <= A #AㄨB <= A if any([x in t1 for x in operator2]): if any([x in t2 for x in operator2]): edge_list_d.append((t1, t2)) else: thisoper = '' for oper in operator2: if oper in t1: thisoper = oper t11 = t1.split(thisoper)[0] t12 = t1.split(thisoper)[1] obj_1 = Wlibrary.objects.filter(name=t11).values('id', 'name').first() obj_2 = Wlibrary.objects.filter(name=t2).values('id', 'name').first() obj_3 = Wlibrary.objects.filter(name=t12).values('id', 'name').first() if thisoper == '∪': if t2 == t11 or t2 == t12: r = Relation2.objects.filter(t11= obj_2['id'], operator1='default',t12=0, t21=obj_1['id'],operator2=thisoper,t22=obj_3['id']).values('id').first() if r: rid = r['id'] else: exp = t2 + '<=' + t1 r = Relation2.objects.create(t11= obj_2['id'], operator1='default',t12=0, t21=obj_1['id'],operator2=thisoper,t22=obj_3['id'], user=user, relationship=nexus,exp=exp) rid = r.id edge_list_s.append((t2, t1)) res.append((t2,t1, '<=', rid)) else: edge_list_d.append((t1, t2)) else: if t2 == t11 or t2 == t12: r = Relation2.objects.filter(t11= obj_1['id'], operator1=thisoper,t12=obj_3['id'], t21=obj_2['id'],operator2='default',t22=0).values('id').first() if r: rid = r['id'] else: exp = t1 + '<=' + t2 r = Relation2.objects.create(t11= obj_1['id'], operator1=thisoper,t12=obj_3['id'], t21=obj_2['id'],operator2='default',t22=0, user=user, relationship=nexus,exp=exp) rid = r.id edge_list_s.append((t1, t2)) res.append((t1,t2, '<=', rid)) else: edge_list_d.append((t1, t2)) elif any([x in t2 for x in operator2]): thisoper = '' for oper in operator2: if oper in t2: thisoper = oper t21 = t2.split(thisoper)[0] t22 = t2.split(thisoper)[1] obj_1 = Wlibrary.objects.filter(name=t1).values('id', 'name').first() obj_2 = Wlibrary.objects.filter(name=t21).values('id', 'name').first() obj_3 = Wlibrary.objects.filter(name=t22).values('id', 'name').first() if thisoper == '∪': if t1 == t21 or t1 == t22: r = Relation2.objects.filter(t11= obj_1['id'], operator1='default',t12=0, t21=obj_2['id'],operator2=thisoper,t22=obj_3['id']).values('id').first() if r: rid = r['id'] else: exp = t1 + '<=' + t2 r = Relation2.objects.create(t11= obj_2['id'], operator1='default',t12=0, t21=obj_1['id'],operator2=thisoper,t22=obj_3['id'], user=user, relationship=nexus,exp=exp) rid = r.id edge_list_s.append((t1, t2)) res.append((t1,t2, '<=', rid)) else: edge_list_d.append((t1, t2)) else: if t1 == t21 or t1 == t22: r = Relation2.objects.filter(t11= obj_2['id'], operator1=thisoper,t12=obj_3['id'], t21=obj_1['id'],operator2='default',t22=0).values('id').first() if r: rid = r['id'] else: exp = t2 + '<=' + t1 r = Relation2.objects.create(t11= obj_2['id'], operator1=thisoper,t12=obj_3['id'], t21=obj_1['id'],operator2='default',t22=0, user=user, relationship=nexus,exp=exp) rid = r.id edge_list_s.append((t2, t1)) res.append((t2,t1, '<=', rid)) else: edge_list_d.append((t1, t2)) else: #A <= A* <= A◇ A <= A︿ if t1.endswith(operator1) and not t2.endswith(operator1): oper = t1[-1] t11 = t1.replace(oper, '') obj_1 = Wlibrary.objects.filter(name=t11).values('id', 'name').first() obj_2 = Wlibrary.objects.filter(name=t2).values('id', 'name').first() if t11 == t2: r = Relation2.objects.filter(t11= obj_2['id'], operator1='default',t12=0, t21=obj_1['id'],operator2=oper,t22=0).values('id').first() if r: rid = r['id'] else: exp = t2 + '<=' + t1 r = Relation2.objects.create(t11= obj_2['id'], operator1='default',t12=0, t21=obj_1['id'],operator2=oper,t22=0, user=user, relationship=nexus,exp=exp) rid = r.id edge_list_s.append((t2, t1)) res.append((t2,t1, '<=', rid)) else: edge_list_d.append((t1, t2)) elif not t1.endswith(operator1) and t2.endswith(operator1): oper = t2[-1] t21 = t2.replace(oper, '') obj_1 = Wlibrary.objects.filter(name=t1).values('id', 'name').first() obj_2 = Wlibrary.objects.filter(name=t21).values('id', 'name').first() if t1 == t21: r = Relation2.objects.filter(t11=obj_1['id'], operator1='default', t12=0, t21=obj_2['id'], operator2=oper, t22=0).values('id').first() if r: rid = r['id'] else: exp = t1 + '<=' + t2 r = Relation2.objects.create(t11=obj_1['id'], operator1='default', t12=0, t21=obj_2['id'], operator2=oper, t22=0, user=user, relationship=nexus, exp=exp) rid = r.id edge_list_s.append((t1, t2)) res.append((t1, t2, '<=', rid)) else: edge_list_d.append((t1, t2)) elif t1.endswith(operator1) and t2.endswith(operator1): oper1 = t1[-1] oper2 = t2[-1] t11 = t1.replace(oper1, '') t21 = t2.replace(oper2, '') obj_1 = Wlibrary.objects.filter(name=t11).values('id', 'name').first() obj_2 = Wlibrary.objects.filter(name=t21).values('id', 'name').first() if t11 == t21: if oper1 == '*' and oper2 == '◇': r = Relation2.objects.filter(t11=obj_1['id'], operator1=oper1, t12=0, t21=obj_2['id'], operator2=oper2, t22=0).values('id').first() if r: rid = r['id'] else: exp = t1 + '<=' + t2 r = Relation2.objects.create(t11=obj_1['id'], operator1=oper1, t12=0, t21=obj_2['id'], operator2=oper2, t22=0, user=user, relationship=nexus, exp=exp) rid = r.id edge_list_s.append((t1, t2)) res.append((t1,t2, '<=', rid)) elif oper1 == '◇' and oper2 == '*': r = Relation2.objects.filter(t11=obj_2['id'], operator1=oper2, t12=0, t21=obj_1['id'], operator2=oper1, t22=0).values('id').first() if r: rid = r['id'] else: exp = t2 + '<=' + t1 r = Relation2.objects.create(t11=obj_2['id'], operator1=oper2, t12=0, t21=obj_1['id'], operator2=oper1, t22=0, user=user, relationship=nexus, exp=exp) rid = r.id edge_list_s.append((t2, t1)) res.append((t2,t1, '<=', 1)) else: edge_list_d.append((t1, t2)) else: edge_list_d.append((t1, t2)) else: obj_1 = Wlibrary.objects.get(name=t1) obj_2 = Wlibrary.objects.get(name=t2) r1 = Relation2.objects.filter(t11=obj_1.id, operator1='default', t12=0, t21=obj_2.id, operator2='default', t22=0).values('id','relationship').first() r2 = Relation2.objects.filter(t11=obj_2.id, operator1='default', t12=0, t21=obj_1.id, operator2='default', t22=0).values('id','relationship').first() if r1 != None: # relation exists if r1['relationship'] == 1: edge_list_s.append((t1, t2)) res.append((t1, t2, '<=', r1['id'])) elif r2 != None: # relation exists if r2['relationship'] == 1: edge_list_d.append((t2, t1)) res.append((t2, t1, '!<=', r2['id'])) else: # relation not exists step = 0 if obj_1.mcdc_1.isnumeric() and obj_2.mcdc_2.isnumeric(): if int(obj_1.mcdc_1) > int(obj_2.mcdc_2): step = 1 if int(obj_1.mcdc_1) < int(obj_2.mcdc_2): step = 2 elif obj_1.mcdc_1 == 'omega' and obj_2.mcdc_2.isnumeric(): step = 1 elif obj_1.mcdc_1.isnumeric() and obj_2.mcdc_2 == 'omega': step = 2 elif obj_1.mcdc_1 == 'infinity': if obj_2.mcdc_2 == 'omega' or obj_2.mcdc_2.isnumeric(): step = 1 elif obj_2.mcdc_2 == 'infinity': if obj_1.mcdc_1 == 'omega' or obj_1.mcdc_1.isnumeric(): step = 2 else: step = 0 print(step) if step == 1: # check mcdc exp = t2 + '!<=' + t1 r = Relation2.objects.create(t11=obj_2.id, operator1='default', t12=0, t21=obj_1.id, operator2='default', t22=0, user=user, relationship=nexus, exp=exp) res.append((t2, t1, "!<=", r.id)) else: pass #edge_list_d.append((t1, t2)) # ========== draw image =================== pos = nx.spring_layout(g) nx.draw_networkx_nodes(g, pos, node_size=700, label=True) nx.draw_networkx_edges(g, pos, edgelist=edge_list_s, edge_color='k', style='solid', width=3, label=True) nx.draw_networkx_edges(g, pos, edgelist=edge_list_d, width=3, edge_color='b', style='dashed') nx.draw_networkx_labels(g, pos) nx.draw_networkx_edge_labels(g, pos) plt.axis('off') plt.savefig(file_name + ".png") # save as png plt.close() return res
nx.draw_networkx(g_cpp, pos=node_positions, node_size=10, node_color='black', edge_color=edge_colors, with_labels=False, alpha=0.5) bbox = { 'ec': [1, 1, 1, 0], 'fc': [1, 1, 1, 0] } # hack to label edges over line (rather than breaking up line) edge_labels = nx.get_edge_attributes(g_cpp, 'sequence') nx.draw_networkx_edge_labels(g_cpp, pos=node_positions, edge_labels=edge_labels, bbox=bbox, font_size=6) plt.axis('off') plt.show() # Create scene file # visit_colors = {1:'black', 2:'red', 3:'yellow', 4:'lightblue', 5:'green'} # edge_center = {} # g_i_edge_colors = [] # for i, e in enumerate(euler_circuit, start=1): # # edge = frozenset([e[0], e[1]]) # if edge in edge_center: # edge_center[edge] += 1
def test_axes(self): fig, ax = plt.subplots() nx.draw(self.G, ax=ax) nx.draw_networkx_edge_labels(self.G, nx.circular_layout(self.G), ax=ax)
print(value) print('------------------------------------') #calculate the degree centrality for each number_of_edges centrality_dictionary = nx.degree_centrality(G) for key, value in centrality_dictionary.iteritems(): print(key) print('degree centrality:') print(value) print('------------------------------------') #calculate the clustering coefficient for each node clustering_co_dictionary = nx.clustering(G) for key, value in centrality_dictionary.iteritems(): print(key) print('clustering coefficient:') print(value) pos = nx.circular_layout(G, scale=.5) nx.draw(G, pos, node_color='blue') edge_labels = nx.get_edge_attributes(G, 'r') edge_labels = nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif', font_color='red') plt.axis('off') plt.show()
def plot_network(wn, node_attribute=None, link_attribute=None, title=None, node_size=20, node_range=[None, None], node_cmap=plt.cm.jet, node_labels=False, link_width=1, link_range=[None, None], link_cmap=plt.cm.jet, link_labels=False, add_colorbar=True, directed=False, ax=None): """ Plot network graphic using networkx. Parameters ---------- wn : WaterNetworkModel A WaterNetworkModel object node_attribute : str, list, pd.Series, or dict, optional (default = None) - If node_attribute is a string, then a node attribute dictionary is created using node_attribute = wn.query_node_attribute(str) - If node_attribute is a list, then each node in the list is given a value of 1. - If node_attribute is a pd.Series, then it should be in the format {(nodeid,time): x} or {nodeid: x} where nodeid is a string and x is a float. The time index is not used in the plot. - If node_attribute is a dict, then it should be in the format {nodeid: x} where nodeid is a string and x is a float link_attribute : str, list, pd.Series, or dict, optional (default = None) - If link_attribute is a string, then a link attribute dictionary is created using edge_attribute = wn.query_link_attribute(str) - If link_attribute is a list, then each link in the list is given a value of 1. - If link_attribute is a pd.Series, then it should be in the format {(linkid,time): x} or {linkid: x} where linkid is a string and x is a float. The time index is not used in the plot. - If link_attribute is a dict, then it should be in the format {linkid: x} where linkid is a string and x is a float. title : str, optional Plot title (default = None) node_size : int, optional Node size (default = 10) node_range : list, optional Node range (default = [None,None], autoscale) node_cmap : matplotlib.pyplot.cm colormap, optional Node colormap (default = jet) node_labels: bool, optional If True, the graph will include each node labelled with its name. (default = False) link_width : int, optional Link width (default = 1) link_range : list, optional Link range (default = [None,None], autoscale) link_cmap : matplotlib.pyplot.cm colormap, optional Link colormap (default = jet) link_labels: bool, optional If True, the graph will include each link labelled with its name. (default = False) add_colorbar : bool, optional Add colorbar (default = True) directed : bool, optional If True, plot the directed graph (default = False, converts the graph to undirected) ax : matplotlib axes object, optional Axes for plotting (default = None, creates a new figure with a single axes) Returns ------- nodes, edges Notes ----- For more network draw options, see nx.draw_networkx """ if ax is None: # create a new figure plt.figure(facecolor='w', edgecolor='k') ax = plt.gca() # Graph G = wn.get_graph_deep_copy() if not directed: G = G.to_undirected() # Position pos = nx.get_node_attributes(G, 'pos') if len(pos) == 0: pos = None # Node attribute if isinstance(node_attribute, str): node_attribute = wn.query_node_attribute(node_attribute) if isinstance(node_attribute, list): node_attribute = dict(zip(node_attribute, [1] * len(node_attribute))) if isinstance(node_attribute, pd.Series): if node_attribute.index.nlevels == 2: # (nodeid, time) index # drop time node_attribute.reset_index(level=1, drop=True, inplace=True) node_attribute = dict(node_attribute) # Define node list, color, and colormap if node_attribute is None: nodelist = None nodecolor = 'k' else: nodelist, nodecolor = zip(*node_attribute.items()) # Link attribute if isinstance(link_attribute, str): link_attribute = wn.query_link_attribute(link_attribute) if isinstance(link_attribute, list): link_attribute = dict(zip(link_attribute, [1] * len(link_attribute))) if isinstance(link_attribute, pd.Series): if link_attribute.index.nlevels == 2: # (linkid, time) index # drop time link_attribute.reset_index(level=1, drop=True, inplace=True) link_attribute = dict(link_attribute) # Replace link_attribute dictionary defined as # {link_name: attr} with {(start_node, end_node, link_name): attr} if link_attribute is not None: attr = {} for link_name, value in link_attribute.items(): link = wn.get_link(link_name) attr[(link.start_node, link.end_node, link_name)] = value link_attribute = attr if type(link_width) is dict: attr = {} for link_name, value in link_width.items(): link = wn.get_link(link_name) attr[(link.start_node, link.end_node, link_name)] = value link_width = attr # Define link list, color, and colormap if link_attribute is None: linklist = None linkcolor = 'k' else: linklist, linkcolor = zip(*link_attribute.items()) if type(link_width) is dict: linklist2, link_width = zip(*link_width.items()) if not linklist == linklist2: logger.warning('Link color and width do not share the same \ indexes, link width changed to 1.') link_width = 1 if title is not None: ax.set_title(title) nodes = nx.draw_networkx_nodes(G, pos, with_labels=False, nodelist=nodelist, node_color=nodecolor, node_size=node_size, cmap=node_cmap, vmin=node_range[0], vmax=node_range[1], linewidths=0, ax=ax) edges = nx.draw_networkx_edges(G, pos, edgelist=linklist, edge_color=linkcolor, width=link_width, edge_cmap=link_cmap, edge_vmin=link_range[0], edge_vmax=link_range[1], ax=ax) if node_labels: labels = dict(zip(wn.node_name_list, wn.node_name_list)) nx.draw_networkx_labels(G, pos, labels, font_size=7, ax=ax) if link_labels: labels = {} for link_name in wn.link_name_list: link = wn.get_link(link_name) labels[(link.start_node, link.end_node)] = link_name nx.draw_networkx_edge_labels(G, pos, labels, font_size=7, ax=ax) if add_colorbar and node_attribute: plt.colorbar(nodes, shrink=0.5, pad=0, ax=ax) if add_colorbar and link_attribute: plt.colorbar(edges, shrink=0.5, pad=0.05, ax=ax) ax.axis('off') return nodes, edges
def plot(model, pos=None, scale=1, figsize=(15, 8), verbose=3): """Plot the learned stucture. Parameters ---------- model : dict Learned model from the .fit() function.. pos : graph, optional Coordinates of the network. If there are provided, the same structure will be used to plot the network.. The default is None. scale : int, optional Scaling parameter for the network. A larger number will linearily increase the network.. The default is 1. figsize : tuple, optional Figure size. The default is (15,8). verbose : int, optional Print progress to screen. The default is 3. 0: None, 1: ERROR, 2: WARN, 3: INFO (default), 4: DEBUG, 5: TRACE Returns ------- dict containing pos and G pos : list Positions of the nodes. G : Graph Graph model """ out = {} G = nx.DiGraph() # Directed graph layout = 'fruchterman_reingold' # Extract model if in dict if 'dict' in str(type(model)): model = model.get('model', None) # Bayesian model if 'BayesianModel' in str(type(model)) or 'pgmpy' in str(type(model)): if verbose >= 3: print('[BNLEARN][plot] Making plot based on BayesianModel') # positions for all nodes pos = network.graphlayout(model, pos=pos, scale=scale, layout=layout) # Add directed edge with weigth # edges=model.edges() edges = [*model.edges()] for i in range(len(edges)): G.add_edge(edges[i][0], edges[i][1], weight=1, color='k') elif 'networkx' in str(type(model)): if verbose >= 3: print('[BNLEARN][plot] Making plot based on networkx model') G = model pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout) else: if verbose >= 3: print('[BNLEARN][plot] Making plot based on adjacency matrix') G = network.adjmat2graph(model) # Get positions pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout) # Bootup figure plt.figure(figsize=figsize) # nodes nx.draw_networkx_nodes(G, pos, node_size=500, alpha=0.85) # edges colors = [G[u][v].get('color', 'k') for u, v in G.edges()] weights = [G[u][v].get('weight', 1) for u, v in G.edges()] nx.draw_networkx_edges(G, pos, arrowstyle='->', edge_color=colors, width=weights) # Labels nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif') # Get labels of weights # labels = nx.get_edge_attributes(G,'weight') # Plot weights nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes( G, 'weight')) # Making figure nice ax = plt.gca() ax.set_axis_off() plt.show() # Store out['pos'] = pos out['G'] = G return (out)
def markov_chain(states=['XSS', 'SQL', 'PHP'], transition_name=[['XX', 'XS', 'XP'], ['SX', 'SS', 'SP'], ['PX', 'PS', 'PP']], transition_matrix=[[0.6, 0.3, 0.1], [0.5, 0.4, 0.1], [0.6, 0.2, 0.2]], start_state='XSS', end_state='SQL', iterations_count=10000, steps_count=2, lang='eng', is_table=False, is_chain=False): """ Creating a Markov chain and calculating the probability of states. Keyword arguments: states -- Array of possible states transition_name -- Array of transitions transition_matrix -- Array of transitions probability start_state -- Start state end_state -- End state iterations_count -- Number of iterations steps_count -- Number of steps lang -- Language is_table -- Conclusion of the table of transitions with probabilistic values """ import numpy as np import random as rm import pandas as pd import pydot import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt from functools import reduce if len(states) != len(transition_name) or len(states) != len( transition_matrix) or len(transition_matrix) != len( transition_name): raise Exception( 'Check the lists of states and transitions. Their lengths should be equal.' ) possibility_ckeck = 0 cheker = 0 while cheker < len(transition_matrix): possibility_ckeck += sum(transition_matrix[cheker]) cheker += 1 if possibility_ckeck != len(transition_matrix): raise Exception('Transition Matrix compiled incorrectly.') G = nx.DiGraph() def states_forecast(steps_count): state_type = start_state states_list = [state_type] step = 0 prob = 1 while step != steps_count: for i in range(len(states)): if is_chain == True: G.add_node(states[i], pos=(rm.random() * 100, rm.random() * 100)) if state_type == states[i]: change = np.random.choice(transition_name[i], replace=True, p=transition_matrix[i]) for j in range(len(transition_name)): if is_chain == True: G.add_edge(states[i], states[j], weight=transition_matrix[i][j], arrowstyle='->', arrowsize=15, width=3) if change == transition_name[i][j]: prob = prob * transition_matrix[i][j] state_type = states[j] states_list.append(states[j]) step += 1 return states_list list_states = [] count = 0 for iterations in range(1, iterations_count): list_states.append(states_forecast(steps_count)) for smaller_list in list_states: if (smaller_list[2] == end_state): count += 1 # считаем процентики percentage = (count / iterations_count) * 100 if lang == 'rus': print("Вероятность начала в состоянии:{0} и конца в состоянии:{1}= ". format(start_state, end_state) + str(percentage) + '%') else: print( "The probability of starting at state:{0} and ending at state:{1}= " .format(start_state, end_state) + str(percentage) + '%') if is_table == True: df = pd.DataFrame( transition_matrix, columns=states, index=states, ) print('----') print(df) print('----') if is_chain == True: pos = nx.get_node_attributes(G, 'pos') labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx(G, pos, node_color='w') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, node_size=500) ax = plt.gca() ax.set_axis_off() plt.show()
def _draw_network(self): """Draws the NetworkX object representing the underlying graph.""" plt.clf() if self.num_populations == 1: node_sizes = 5000 node_border_width = 1. else: node_sizes = 15000 node_border_width = 3. vmin, vmax = 0, np.max(self.pi) + 0.1 nx.draw_networkx_nodes(self.g, self.pos, node_size=node_sizes, node_color=self.node_colors, edgecolors="k", cmap=plt.cm.Blues, vmin=vmin, vmax=vmax, linewidths=node_border_width) nx.draw_networkx_edges(self.g, self.pos, node_size=node_sizes, arrowstyle="->", arrowsize=10, edge_color=self.edge_colors, edge_cmap=plt.cm.Blues, width=5) nx.draw_networkx_edge_labels(self.g, self.pos, edge_labels=self.edge_labels) if self.num_populations > 1: subnode_separation = 0.1 subgraph = nx.Graph() for i_population in range(self.num_populations): subgraph.add_node(i_population) for i_strat_profile in self.g: x, y = self.pos[i_strat_profile] if self.num_populations == 1: node_text = "$\\pi_{" + self.state_labels[ i_strat_profile] + "}=$" node_text += str(np.round(self.pi[i_strat_profile], decimals=2)) else: node_text = "" # No text for multi-population case as plot gets messy txt = plt.text(x, y, node_text, horizontalalignment="center", verticalalignment="center", fontsize=12) txt.set_path_effects( [PathEffects.withStroke(linewidth=3, foreground="w")]) if self.num_populations > 1: sub_pos = nx.circular_layout(subgraph) subnode_labels = dict() strat_profile = utils.get_strat_profile_from_id( self.num_strats_per_population, i_strat_profile) for i_population in subgraph.nodes(): i_strat = strat_profile[i_population] subnode_labels[i_population] = "$s^{" + str(i_population + 1) + "}=" subnode_labels[i_population] +=\ self.state_labels[i_population][i_strat] + "$" # Adjust the node positions generated by NetworkX's circular_layout(), # such that the node for the 1st strategy starts on the left. sub_pos[i_population] = ( -sub_pos[i_population] * subnode_separation + self.pos[i_strat_profile]) nx.draw(subgraph, pos=sub_pos, with_labels=True, width=0., node_color="w", labels=subnode_labels, node_size=2500)
def make(self, edge_words, dir='', text=None): '''Runs the whole KG creation process. Outputs a pickled representation of the graph, summarized graph, and raw text dictionaries of entities and relations. edge_words: True if want to output graph edges as words, False if indexes dir : str - directory containing documents as seperate text files. ex: dir='data/politics/' return : networkx MultiDiGraph of summarized KG ''' if text != None: self.add_docs_from_text(text) else: self.add_docs_from_dir(dir) print("calling entity detection") self.entity_detection() print("number of entities now: {}".format(len(self.entities))) print("calling coreference detection") self.coreference_detection() # print("number of entities now: {}".format(len(self.entities))) print("calling merge entities") self.condense_entities() print("number of entities now: {}".format(len(self.entities))) self.filter_entities() print("filter...number of entities now: {}".format(len(self.entities))) print("calling triple extraction") self.triple_extraction() print("number of entities now: {}".format(len(self.entities))) print("#######PRINTING ENTITIES#######") #for i in self.entities: #print(self.entities[i].name) #print(self.entities[i].doc_appearances) print("#######PRINTING TRIPLES#######") #for tup in self.triples: #print(tup) print("making graph......") self.construct_graph() print("graph has {} nodes and {} edges".format(self.graph.number_of_nodes(),\ self.graph.number_of_edges())) print("summarizing graph......") self.sum_graph = cp.greedy_summarize(self.graph, 8, 0.05, self.max_weight * 0.7) print("summarized graph has {} nodes and {} edges".format(self.sum_graph.number_of_nodes(),\ self.sum_graph.number_of_edges())) self.pickle_kg(dir) print("constructing word graph") self.construct_wordGraph(self.sum_graph, edge_words) # plt.figure() # nx.draw_networkx(self.graph) # # plt.figure() # nx.draw_networkx(self.sum_graph) pos = nx.spring_layout(G=self.word_graph, dim=2, k=10, scale=20) edge_labels = nx.get_edge_attributes(self.word_graph, 'r') #print(edge_labels.items()) #nx.draw_networkx(G = kg.word_graph, vmin = 1000, edge_vmin= 1000) new_labels = {} for entry in edge_labels.items(): tup = (entry[0][0], entry[0][1]) rel = entry[1] new_labels[tup] = rel #print(new_labels) plt.figure() nx.draw(self.word_graph, pos, with_labels=True) nx.draw_networkx_edge_labels(G=self.word_graph, pos=pos, edge_labels=new_labels) return self.word_graph, new_labels
def draw_pattern_graph(self, pattern_list, support_thrshld=None): for lst in pattern_list: # Todo: each in one subplot try: G = nx.DiGraph() one_pattern = ["\n".join(el) for el in lst[0] ] # list of strings = nodelabels support = float("{0:.2f}".format(lst[1])) if support_thrshld != None: if support < support_thrshld: continue if len(one_pattern) < 2: print("Pattern " + str(one_pattern) + " too short! Skipped it!") continue # set edges edges = [] node_labels = {} val_map = {} prev = one_pattern[0] w_elements = list(np.linspace(0, 1, len(one_pattern))) i = 0 first = True # same_items same = [] for el in one_pattern: if str(el) in same: el = "1_" + el same.append(el) if first: first = False else: # Edges edges.append((prev, el)) prev = el # values val_map[el] = w_elements[ i] # Vorteil identische Elemente bekommen hier identische Zuordnung! node_labels[el] = "\n".join( [i.split("=")[1] for i in el.split("\n")]) if len(node_labels[el]) > 13: n = 13 cur = node_labels[el] node_labels[el] = "-\n".join( [cur[i:i + n] for i in range(0, len(cur), n)]) #node_labels[el] = node_labels[el][:13] + "-\n" + node_labels[el][13:] i += 1 except: print("Problematicz") continue print("EDGES: " + str(one_pattern)) # Set stuff G.add_edges_from(edges, weight=support) values = [val_map.get(node, 0.45) for node in G.nodes()] edge_labels = dict([(( u, v, ), d['weight']) for u, v, d in G.edges(data=True)]) # For later use: colors #red_edges = [('C','D'),('D','A')] #edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()] pos = nx.spring_layout( G ) # circular_layout random_layout shell_layout spring_layout spectral_layout nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw(G, pos, node_color=values, node_size=1500) nx.draw_networkx_labels(G, pos, node_labels, font_size=10) plt.show()
distribution = mimic.Distribution(samples) print('distribution', distribution) distribution._generate_bayes_net() for node_ind in distribution.bayes_net.nodes(): print(distribution.bayes_net.node[node_ind]) pos = nx.spring_layout(distribution.spanning_graph) edge_labels = dict([(( u, v, ), d['weight']) for u, v, d in distribution.spanning_graph.edges(data=True)]) nx.draw_networkx(distribution.spanning_graph, pos) nx.draw_networkx_edge_labels(distribution.spanning_graph, pos, edge_labels=edge_labels) plt.show() ''' for model in models: title = model cv = ShuffleSplit(n_splits=5, test_size=0.33) print(title) #plot_learning_curve(models[model], title, train, target, cv=cv, n_jobs=1) plot_complexity_curve(models[model], title, train, target, list(params1[model].keys())[0], list(params1[model].values())[0], cv=3, n_jobs=-1) plt.show() '''
def plot_graph(g): layout = nx.shell_layout(g) nx.draw_networkx(g, pos=layout) nx.draw_networkx_edge_labels(g, pos=layout) plt.show()
node_color='b', node_size=300, alpha=0.7) nx.draw_networkx_nodes(G, pos, nodelist=fog_nodes, node_color='r', node_size=500, node_shape='s', alpha=0.7) nx.draw_networkx_labels(G, pos, edge_labels=node_name_labels) edge_weight_labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edges(G, pos) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_weight_labels) plt.savefig(filepath + "/device_layout.png") ###Draw job graph plt.figure(2, figsize=(20, 20)) jobs_labels = nx.get_node_attributes(H, "name") nx.draw_networkx_nodes(H, pos, alpha=0.7) nx.draw_networkx_labels(H, pos, labels=jobs_labels) nx.draw_networkx_edges(H, pos) plt.savefig(filepath + "/jobs_layout.png") plt.show(block=False)
def visualize_graph(pp_idx, pp_weight, pd_idx, pd_weight, pp_adj, d1, d2, out_path, protein_name_dict=None, drug_name_dict=None, hiden=True, size=(40, 40)): """ :param pp_idx: integer tensor of the shape (2, n_pp_edges) :param pp_weight: float tensor of the shape (1, n_pp_edges), values within (0,1) :param pd_idx: integer tensor of the shape (2, n_pd_edges) :param pd_weight: float tensor of the shape (1, n_pd_edges), values within (0,1) :param protein_name_dict: store elements {protein_index -> protein name} :param drug_name_dict: store elements {drug_index -> drug name} 1. use different color for pp and pd edges 2. annotate the weight of each edge near the edge (or annotate with the tranparentness of edges for each edge) 3. annotate the name of each node near the node, if name_dict=None, then annotate with node's index """ G = nx.Graph() pp_edge, pd_edge, pp_link = [], [], [] p_node, d_node = set(), set() if not protein_name_dict: tmp = set(pp_idx.flatten()) | set(pd_idx[0]) protein_name_dict = {i: 'p-' + str(i) for i in tmp} if not drug_name_dict: drug_name_dict = {i: 'd-' + str(i) for i in set(pd_idx[1])} # add pp edges for e in zip(pp_idx.T, pp_weight.T): t1, t2 = protein_name_dict[e[0][0]], protein_name_dict[e[0][1]] G.add_edge(t1, t2, weights=e[1]) pp_edge.append((t1, t2)) p_node.update([t1, t2]) # add pd edges for e in zip(pd_idx.T, pd_weight.T): t1, t2 = protein_name_dict[e[0][0]], drug_name_dict[e[0][1]] G.add_edge(t1, t2, weights=e[1]) pd_edge.append((t1, t2)) p_node.add(t1) d_node.add(t2) # add dd edges dd_edge = [] for e in zip(d1, d2): t1, t2 = drug_name_dict[int(e[0])], drug_name_dict[int(e[1])] G.add_edge(t1, t2, weights=999) dd_edge.append((t1, t2)) if hiden: # add underline pp edges pp_edge_idx = pp_idx.tolist() pp_edge_idx = set(zip(pp_edge_idx[0], pp_edge_idx[1])) p_node_idx = list(set(pp_idx.flatten().tolist())) pp_adj_idx = pp_adj.tolist() pp_adj_idx = set(zip(pp_adj_idx[0], pp_adj_idx[1])) combins = [c for c in combinations(p_node_idx, 2)] for i, j in combins: if (i, j) in pp_adj_idx or (j, i) in pp_adj_idx: if (i, j) not in pp_edge_idx and (j, i) not in pp_edge_idx: G.add_edge(protein_name_dict[i], protein_name_dict[j], weights='0') pp_link.append( (protein_name_dict[i], protein_name_dict[j])) print(len(pp_link)) # draw figure plt.figure(figsize=size) # draw nodes pos = nx.spring_layout(G) for p in d_node: # raise drug nodes positions pos[p][1] += 1 nx.draw_networkx_nodes(G, pos, nodelist=p_node, node_size=500, node_color='y') nx.draw_networkx_nodes(G, pos, nodelist=d_node, node_size=500, node_color='blue') # draw edges and edge labels nx.draw_networkx_edges(G, pos, edgelist=pp_edge, width=2) if hiden: nx.draw_networkx_edges(G, pos, edgelist=pp_link, width=2, edge_color='gray', alpha=0.5) nx.draw_networkx_edges(G, pos, edgelist=pd_edge, width=2, edge_color='g') nx.draw_networkx_edges(G, pos, edgelist=dd_edge, width=2, edge_color='black', alpha=0.5) nx.draw_networkx_edge_labels(G, pos, font_size=10, edge_labels={(u, v): str(d['weights'])[:4] for u, v, d in G.edges(data=True) }) # draw node labels for p in pos: # raise text positions pos[p][1] += 0.02 nx.draw_networkx_labels(G, pos, font_size=14) if out_path is not None: plt.savefig(out_path) print(f"DONE --> save figure to path: \"{out_path}\" ") return G, plt.gcf()
def minimum_cost_partial_tree(self): # a new window where the tree is plotted is created here root = Tk() root.geometry("300x450+400+50") root.title("Graph Editor") root.wm_iconbitmap('Graph_Hero_Icon.ico') root.configure(bg='#424242') if self.is_directed: # if the graph is directed, the minimum cost partial tree can't be found by the program # a message will be displayed, it is written that it can't be found text_box = Text(root, width=500, height=1.2, font=('consolas', 10, 'bold'), bg='#424242', foreground='#FFFFFF') text_box.place(x=0, y=0) text_box2 = Text(root, width=500, height=1.2, font=('consolas', 10, 'bold'), bg='#424242', foreground='#FFFFFF') text_box2.place(x=0, y=20) text_box.insert(END, "This option is not available") text_box.configure(state='disable') text_box2.insert(END, "for directed graph") text_box2.configure(state='disable') return # in the edges_tree are the edges of the tree self.edges_tree = algorithms.partial_tree(self.G, self.is_weighted) self.prepare_the_canvas() figure2 = self.figure a = self.a plt.axis('off') if not self.is_weighted: # the edges are added to the Tree(graph) # and it is displayed self.Tree.clear() self.Tree.add_edges_from(self.edges_tree) nx.draw_networkx(self.Tree, pos=nx.spring_layout(self.Tree), ax=a) else: # the edges are added to the Tree self.Tree.clear() for i in self.edges_tree: self.Tree.add_edge(i[0], i[1], weight=i[2]) # and it is displayed pos = nx.spring_layout(self.Tree) nx.draw(self.Tree, pos) edge_labels = dict([((u, v,), d['weight']) for u, v, d in self.Tree.edges(data=True)]) nx.draw_networkx_edge_labels(self.Tree, pos, edge_labels=edge_labels) nx.draw_networkx(self.Tree, pos, edge_labels=edge_labels) canvas = FigureCanvasTkAgg(figure2, master=root) canvas.draw() canvas.get_tk_widget().place(x=0, y=30) # when this button is pressed, the image of the tree will be saved save_tree_image_button = Button(root, text="Save image", font=('consolas', 10, 'bold'), foreground='#FFFFFF', activebackground='#FFFFFF', activeforeground='darkblue', bg='#716C6A', command=self.save_tree_image).place(x=0, y=0) # this save the list of edges of the tree save_tree_button = Button(root, text="Save tree", font=('consolas', 10, 'bold'), foreground='#FFFFFF', activebackground='#FFFFFF', activeforeground='darkblue', bg='#716C6A', command=self.save_the_tree).place(x=81, y=0) root.mainloop()
def _run( self, client: OpenrCtrl.Client, node: str, bidir: bool, output_file: str, edge_label: Any, json: bool, ) -> None: area = self.get_area_id() try: import matplotlib.pyplot as plt import networkx as nx except ImportError: print( "Drawing topology requires `matplotlib` and `networkx` " "libraries. You can install them with following command and " "retry. \n" " pip install matplotlib\n" " pip install networkx" ) sys.exit(1) rem_str = {".facebook.com": "", ".tfbnw.net": ""} rem_str = dict((re.escape(k), v) for k, v in rem_str.items()) rem_pattern = re.compile("|".join(rem_str.keys())) keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER) publication = None if area is None: publication = client.getKvStoreKeyValsFiltered(keyDumpParams) else: publication = client.getKvStoreKeyValsFilteredArea(keyDumpParams, area) nodes = list(self.get_node_to_ips(client, area).keys()) if not node else [node] adjs_map = utils.adj_dbs_to_dict( publication, nodes, bidir, self.iter_publication ) if json: return self.topology_json_dump(adjs_map.items()) G = nx.Graph() adj_metric_map = {} node_overloaded = {} for this_node_name, db in adjs_map.items(): node_overloaded[ rem_pattern.sub( lambda m: rem_str[re.escape(m.group(0))], this_node_name ) ] = db["overloaded"] for adj in db["adjacencies"]: adj_metric_map[(this_node_name, adj["ifName"])] = adj["metric"] for this_node_name, db in adjs_map.items(): for adj in db["adjacencies"]: adj["color"] = "r" if adj["isOverloaded"] else "b" adj["adjOtherIfMetric"] = adj_metric_map[ (adj["otherNodeName"], adj["otherIfName"]) ] G.add_edge( rem_pattern.sub( lambda m: rem_str[re.escape(m.group(0))], this_node_name ), rem_pattern.sub( lambda m: rem_str[re.escape(m.group(0))], adj["otherNodeName"] ), **adj, ) # hack to get nice fabric # XXX: FB Specific pos = {} eswx = 0 sswx = 0 fswx = 0 rswx = 0 blue_nodes = [] red_nodes = [] for node in G.nodes(): if node_overloaded[node]: red_nodes.append(node) else: blue_nodes.append(node) if "esw" in node: pos[node] = [eswx, 3] eswx += 10 elif "ssw" in node: pos[node] = [sswx, 2] sswx += 10 elif "fsw" in node: pos[node] = [fswx, 1] fswx += 10 elif "rsw" in node: pos[node] = [rswx, 0] rswx += 10 maxswx = max(eswx, sswx, fswx, rswx) if maxswx > 0: # aesthetically pleasing multiplier (empirically determined) plt.figure(figsize=(maxswx * 0.5, 8)) else: plt.figure( figsize=(min(len(G.nodes()) * 2, 150), min(len(G.nodes()) * 2, 150)) ) pos = nx.spring_layout(G) plt.axis("off") edge_colors = [] for _, _, d in G.edges(data=True): edge_colors.append(d["color"]) nx.draw_networkx_nodes( G, pos, ax=None, alpha=0.5, node_color="b", nodelist=blue_nodes ) nx.draw_networkx_nodes( G, pos, ax=None, alpha=0.5, node_color="r", nodelist=red_nodes ) nx.draw_networkx_labels(G, pos, ax=None, alpha=0.5, font_size=8) nx.draw_networkx_edges( G, pos, ax=None, alpha=0.5, font_size=8, edge_color=edge_colors ) edge_labels = {} if node: if edge_label: edge_labels = { (u, v): "<" + str(d["otherIfName"]) + ", " + str(d["metric"]) + " > <" + str(d["ifName"]) + ", " + str(d["adjOtherIfMetric"]) + ">" for u, v, d in G.edges(data=True) } nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=6) print("Saving topology to file => {}".format(output_file)) plt.savefig(output_file)
def plot(g, weight='length', pos=None, realization=None, hidden_state=None, s=None, t=None, with_egde_labels=True, cut=None, pruned=None, **kwargs): from matplotlib import pyplot as plt if pos is None: try: pos_g = g.pos.tolist() except AttributeError: pos_g = {n: d.get('pos', n) for n, d in g.nodes(data=True)} else: pos_g = pos cs = [ 1 if (len(d.get('observe', {})) > 0) else 0 for n, d in g.nodes(data=True) ] ecs = _edge_colors(g, realization, hidden_state) nx.draw_networkx(g, pos_g, node_color=cs, edge_color=ecs, node_size=10, cmap='coolwarm', **kwargs) if with_egde_labels: nx.draw_networkx_edge_labels( g, pos_g, {(x, y): round(data.get(weight, 0), 1) for x, y, data in g.edges(data=True)}) if s is not None: plt.plot(*pos_g[s], 'go') if t is not None: plt.plot(*pos_g[t], 'bo') if pruned is not None: if pos is None: pos_p = {n: d.get('pos', n) for n, d in pruned.nodes(data=True)} else: pos_p = pos nx.draw_networkx(pruned, pos_p, edge_color='grey', node_size=2, alpha=0.2, **kwargs) if cut is not None: if pos is None: pos_c = {n: d.get('pos', n) for n, d in cut.nodes(data=True)} else: pos_c = pos nx.draw_networkx(cut, pos_c, edge_color='red', node_size=2, alpha=0.2, **kwargs) plt.axis('off')
node_color='pink') nx.draw_networkx_labels(G, pos, font_size=20) # nx.draw_networkx_edges(G, pos, edge_color='red', style='dashed') # nx.draw_networkx_edges(G, pos, edge_color='black', edgelist=[('a4', 'a7'), ('a5', 'a7'), ('a6', 'a7'), ('a1', 'a4'), ('a4', 'a2'), ('a5', 'a3')]) edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=12, rotate=False) print(G.edges()) # , edgelist=[('a', 'b'),('b', 'c'), ('c', 'd')] # # nx.draw_networkx_edges(G, pos, edge_color='red') # edge_labels = nx.get_edge_attributes(G, 'weight') # nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=20, rotate=False) plt.xlim(0, 300) plt.ylim(-0, 300) plt.axis('off')
def plot_graph(self, ax=None, figsize=None, max_size=1000, directed=True, edge_labels=False, draw_neg=False): if self.normalized_difference.ndim > 2: raise MarkovError("You can only graph one-step chains.") try: import networkx as nx except ImportError: nx = None if nx is None: print("Please install networkx with `pip install networkx`.") return G = self.as_graph(directed=directed) return_ax = True if ax is None: fig, ax = plt.subplots(figsize=figsize) return_ax = False e_neg = {(u, v): round(d['weight'], 1) for (u, v, d) in G.edges(data=True) if d['weight'] <= -1.0} e_small = {(u, v): round(d['weight'], 1) for (u, v, d) in G.edges(data=True) if -1.0 < d['weight'] <= 1.0} e_med = {(u, v): round(d['weight'], 1) for (u, v, d) in G.edges(data=True) if 1.0 < d['weight'] <= 2.0} e_large = {(u, v): round(d['weight'], 1) for (u, v, d) in G.edges(data=True) if d['weight'] > 2.0} pos = nx.spring_layout(G) sizes = max_size * (self._state_counts / max(self._state_counts)) nx.draw_networkx_nodes(G, pos, ax=ax, node_size=sizes, node_color='orange') nx.draw_networkx_edges(G, pos, ax=ax, edgelist=e_large, width=10, arrowsize=40, splines='curved') nx.draw_networkx_edges(G, pos, ax=ax, edgelist=e_med, width=4, arrowsize=20) nx.draw_networkx_edges(G, pos, ax=ax, edgelist=e_small, width=3, alpha=0.1, edge_color='k') if draw_neg: nx.draw_networkx_edges(G, pos, ax=ax, edgelist=e_neg, width=2, alpha=0.1, edge_color='k') if edge_labels: nx.draw_networkx_edge_labels(G, pos, edge_labels=e_large) nx.draw_networkx_edge_labels(G, pos, edge_labels=e_med) labels = nx.get_node_attributes(G, 'state') ax = nx.draw_networkx_labels(G, pos, labels=labels, font_size=20, font_family='sans-serif', font_color='blue') if return_ax: return ax else: plt.axis('off') plt.show() return
print(attr) for attr in arc_road_1: print(attr) print('Nodes of graph: ') print(G.nodes()) print('Edges of graph: ') print(G.edges()) # Отрисовывем вершины nx.draw_networkx(G, nodes_pos, node_size=1000) # Отрисовываем ребра nx.draw_networkx_edges(G, nodes_pos) # Подписываем вершины, ребра и веса nx.draw_networkx_edge_labels(G, nodes_pos, edge_labels=arc_weigth) # Удалим координатные оси plt.axis('off') # nx.draw_networkx(G) plt.show() # 3. Задайте ребрам аттрибут ЖД или автодорога # (если между городами существует прямое ЖД сообщение, то ЖД, иначе автодорога) # 4. Добавьте ребрам аттрибут с названием маршрута или трассы # наикратчайший путь print( nx.shortest_path(G,
def minspantree(): mstOutput = [] mstalgo = request.form.getlist('mstalgo') pattern = re.compile(r'\s+') inputvertices = re.sub(pattern, '', request.form['inputVertex']) inputedges = re.sub(pattern, '', request.form['inputEdges']) numbercheck = all(item.isnumeric() for item in inputvertices.split(',')) if (len(mstalgo) == 0): return "Please select the Algorithm" else: if (numbercheck): verticies = [int(item) for item in inputvertices.split(',')] verticies.sort() edges = [tuple(item) for item in literal_eval(inputedges)] else: verticies = inputvertices.split(',') verticies.sort() edges = [(item.split(',')[0], item.split(',')[1], int(item.split(',')[-1])) for item in inputedges.replace('),(', '*').replace( '(', '').replace(')', '').split('*')] for algo in mstalgo: if (algo.lower() == "prim"): prims = PrimAlgo(verticies, edges) start_time = time.perf_counter() result = prims.getMinSpanTree() totalcost = sum([pair[2] for pair in result]) primsExecutionTime = time.perf_counter() - start_time output = { "Algorithm": "Prims", "Input Verticies": verticies, "Input Edges": edges, "Number of Input Verticies": len(verticies), "Number of Input Edges": len(edges), "Minimum SpanningTree": result, "Total Cost": totalcost, "Execution Time in Seconds": str(primsExecutionTime) } G = nx.Graph() element = 0 for node in verticies: if (element % 2 == 0): G.add_node(node, pos=(element, element + 2)) else: G.add_node(node, pos=(element + 1, element - 1)) element += 1 for edge in result: G.add_edge(edge[0], edge[1], weight=edge[2]) pos = nx.get_node_attributes(G, 'pos') nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=5) primsFileName = 'primsoutput' + str(time.time()) + '.jpg' mstOutput.append((primsFileName, output)) plt.savefig('./Images/' + primsFileName) plt.cla() plt.clf() del G del prims else: krushkal = KrushkalAlgo(verticies, edges) start_time = time.perf_counter() result = krushkal.getMinSpanTree() totalcost = sum([pair[2] for pair in result]) krushkalExecutionTime = time.perf_counter() - start_time output = { "Algorithm": "Krushkal", "Input Verticies": verticies, "Input Edges": edges, "Number of Input Verticies": len(verticies), "Number of Input Edges": len(edges), "Minimum SpanningTree": result, "Total Cost": totalcost, "Execution Time in Seconds": str(krushkalExecutionTime) } G = nx.Graph() element = 0 for node in verticies: if (element % 2 == 0): G.add_node(node, pos=(element + 1, element)) else: G.add_node(node, pos=(element - 1, element + 2)) element += 1 for edge in result: G.add_edge(edge[0], edge[1], weight=edge[2]) pos = nx.get_node_attributes(G, 'pos') nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=5) krushkalFileName = 'krushkaloutput' + str(time.time()) + '.jpg' mstOutput.append((krushkalFileName, output)) krushkalResult = './Images/' + krushkalFileName plt.savefig(krushkalResult) plt.cla() plt.clf() del G del krushkal algo = [item[1]['Algorithm'] for item in mstOutput] executionTime = [ float(item[1]['Execution Time in Seconds']) for item in mstOutput ] plt.bar(algo, executionTime, width=0.6) plt.title('Algorithm VS Execution Time') plt.xlabel('Algorithms') plt.ylabel('Execution Time in Seconds') perfGraphname = 'algobarchart' + str(time.time()) + '.jpg' bargraphPath = './Images/' + perfGraphname plt.savefig(bargraphPath) plt.cla() plt.clf() return render_template("output.html", mstoutput=mstOutput, perfGraphname=perfGraphname)
def draw_scenegraph_data(scene_graph): for i_rel, rel in enumerate(scene_graph.relationships): graph = nx.DiGraph() sub, rel_type, obj = rel #Node for the subject sub_idx = graph.number_of_nodes() graph.add_node(sub_idx, descr=sub.label) #Node for the object obj_idx = graph.number_of_nodes() graph.add_node(obj_idx, descr=obj.label) #The relationship edge graph.add_edge(sub_idx, obj_idx, descr=rel_type) # Color and Corner for subject sub_color_idx = graph.number_of_nodes() graph.add_node(sub_color_idx, descr=sub.color) graph.add_edge(sub_color_idx, sub_idx, descr='attr') sub_corner_idx = graph.number_of_nodes() graph.add_node(sub_corner_idx, descr=sub.corner) graph.add_edge(sub_corner_idx, sub_idx, descr='attr') # Color and Corner for object obj_color_idx = graph.number_of_nodes() graph.add_node(obj_color_idx, descr=obj.color) graph.add_edge(obj_color_idx, obj_idx, descr='attr') obj_corner_idx = graph.number_of_nodes() graph.add_node(obj_corner_idx, descr=obj.corner) graph.add_edge(obj_corner_idx, obj_idx, descr='attr') #Draw plt.subplot(f'22{i_rel+1}') node_labels = nx.get_node_attributes(graph, 'descr') edge_labels = nx.get_edge_attributes(graph, 'descr') #pos = nx.spring_layout(graph) pos = { sub_idx: (0, 0.25), sub_color_idx: (-1, 0), sub_corner_idx: (1, 0), obj_idx: (0, 0.75), obj_color_idx: (-1, 1), obj_corner_idx: (1, 1) } nx.draw(graph, pos, labels=node_labels, node_size=1200, arrowsize=30, font_size=24) nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels, font_size=24) fig = plt.gcf() fig.set_size_inches(20, 15) fig.savefig('tmp.png') img = cv2.imread('tmp.png') return img
def draw_genome_graph(genome: Genome, draw_labels=True, plot: bool = False) -> None: """ Parse the genome into a networkx graph, which can be plotted with matplotlib, if the command plt.show() is invoked after this method :param genome: the genome that should be displayed :param draw_labels: True if the labels of the connections should be printed :param plot: draw the genome directly :return: None """ graph = nx.DiGraph() node_colors = [] for x_position, node_list in sorted(_sort_nodes_in_layers(genome).items()): size = len(node_list) step_size = 1 / (size + 2) for node, i in zip(node_list, range(1, len(node_list) + 1)): y_position = i * step_size # Store color for later drawing node_colors.append(_get_color_for_node_type(node.node_type)) # Add node graph.add_node(node.innovation_number, pos=(x_position, y_position)) disabled_connections = [] enabled_connections = [] for connection in genome.connections: graph.add_edge(connection.input_node, connection.output_node, label=round(connection.weight, 4)) if connection.enabled: enabled_connections.append( (connection.input_node, connection.output_node)) else: disabled_connections.append( (connection.input_node, connection.output_node)) # Extract required fields node_positions = nx.get_node_attributes(graph, 'pos') connection_labels = nx.get_edge_attributes(graph, 'label') # Draw graph edges nx.draw_networkx_edges(graph, node_positions, edgelist=enabled_connections, connectionstyle='arc3, rad=0.1') collection = nx.draw_networkx_edges(graph, node_positions, edgelist=disabled_connections, alpha=0.5, edge_color='b', connectionstyle='arc3, rad=0.1') # Bug in the library, can't set the line style.: # https://stackoverflow.com/questions/51138059/no-dotted-line-with-networkx-drawn-on-basemap/51148746#51148746?s=e8a8f3c423e84da9aa77b1259b3ad829 if collection is not None: for patch in collection: patch.set_linestyle('dashed') # Draw graph edges labels if draw_labels: nx.draw_networkx_edge_labels(graph, node_positions, edge_labels=connection_labels, label_pos=0.7, rotate=False) # Draw graph node labels nx.draw_networkx_labels(graph, node_positions) # Draw graph nodes # nx.draw_net(graph, pos=node_positions, node_color=node_colors, connectionstyle='arc3, rad=0.1', with_labels=True) nx.draw_networkx_nodes(graph, pos=node_positions, node_color=node_colors, with_labels=True) plt.title("Neural Network") font = {'family': 'normal', 'size': 13} plt.rc('font', **font) if plot: plt.show()
} #draw nodes and edges nx.draw_networkx_nodes(G, pos, node_size=300, nodelist=pos.keys(), node_color='w') nx.draw_networkx_edges(G, pos, alpha=0.5, width=3, edgelist=city_edges, edge_color='w') #draw lables on nodes and edges nx.draw_networkx_labels(G, pos, labels=label_dictionary, font_color='purple', font_size=16, font_family='sans-serif') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=12, label_pos=0.5) plt.axis('off') #plt.savefig("europe.png") # save as png plt.show() # display
#number of nodes in the Graph n = 10 #create a random network G = randomRelationNetwork(n) #stabilzes the random network created stabilizeNetwork(G) pos = nx.circular_layout(G) nx.draw(G, pos, with_labels=True, node_size=5000) edgeLabels = nx.get_edge_attributes(G, 'sign') nx.draw_networkx_edge_labels(G, pos, edge_labels=edgeLabels, font_size=20, font_color='red') plt.show(block=False) minError = 0.001 #adding Error in the graph epsilon = 0 edgeLabels = nx.get_edge_attributes(G, 'sign') pivotNode = 0 GroupA = [] GroupB = []
def draw_graph(grph, edge_labels=True, node_color='#AFAFAF', edge_color='#CFCFCF', plot=True, node_size=2000, with_labels=True, arrows=True, layout='neato'): """ Draw a graph. This function will be removed in future versions. Parameters ---------- grph : networkxGraph A graph to draw. edge_labels : boolean Use nominal values of flow as edge label node_color : dict or string Hex color code oder matplotlib color for each node. If string, all colors are the same. edge_color : string Hex color code oder matplotlib color for edge color. plot : boolean Show matplotlib plot. node_size : integer Size of nodes. with_labels : boolean Draw node labels. arrows : boolean Draw arrows on directed edges. Works only if an optimization_model has been passed. layout : string networkx graph layout, one of: neato, dot, twopi, circo, fdp, sfdp. """ if type(node_color) is dict: node_color = [node_color.get(g, '#AFAFAF') for g in grph.nodes()] # set drawing options options = { 'prog': 'dot', 'with_labels': with_labels, 'node_color': node_color, 'edge_color': edge_color, 'node_size': node_size, 'arrows': arrows } # draw graph pos = nx.drawing.nx_agraph.graphviz_layout(grph, prog=layout) nx.draw(grph, pos=pos, **options) # add edge labels for all edges if edge_labels is True and plt: labels = nx.get_edge_attributes(grph, 'weight') nx.draw_networkx_edge_labels(grph, pos=pos, edge_labels=labels) # show output if plot is True: plt.show()
('LinhaAzul', 'LinhaRoxa'): 1, ('LinhaVerde', 'LinhaVermelha'): 1, ('LinhaVerde', 'LinhaAmarela'): 1, ('LinhaVermelha', 'LinhaAmarela'): 1, ('LinhaRoxa', 'LinhaAmarela'): 1} G.add_edges_from(numero_conexoes) G.edges() nx.draw(G, pos, node_color=COLORS[0], node_shape='s', node_size=2500, with_labels=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=numero_conexoes) plt.axis('equal') plt.savefig('chap02-2.pdf') #Attempt 2 from __future__ import print_function, division %matplotlib inline import warnings warnings.filterwarnings('ignore')