def plot_co_x(cox, start, end, size = (20,20), title = '', weighted=False, weight_threshold=10): """ Plotting function for keyword graphs Parameters -------------------- cox: the coword networkx graph; assumes that nodes have attribute 'topic' start: start year end: end year """ plt.figure(figsize=size) plt.title(title +' %s - %s'%(start,end), fontsize=18) if weighted: elarge=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] >weight_threshold] esmall=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] <=weight_threshold] pos=nx.graphviz_layout(cox) # positions for all nodes nx.draw_networkx_nodes(cox,pos, node_color= [s*4500 for s in nx.eigenvector_centrality(cox).values()], node_size = [s*6+20 for s in nx.degree(cox).values()], alpha=0.7) # edges nx.draw_networkx_edges(cox,pos,edgelist=elarge, width=1, alpha=0.5, edge_color='black') #, edge_cmap=plt.cm.Blues nx.draw_networkx_edges(cox,pos,edgelist=esmall, width=0.3,alpha=0.5,edge_color='yellow',style='dotted') # labels nx.draw_networkx_labels(cox,pos,font_size=10,font_family='sans-serif') plt.axis('off') else: nx.draw_graphviz(cox, with_labels=True, alpha = 0.8, width=0.1, fontsize=9, node_color = [s*4 for s in nx.eigenvector_centrality(cox).values()], node_size = [s*6+20 for s in nx.degree(cox).values()])
def plot_graph(self, run_name, condor_path): # Graph one plots the memory utilization of various steps plt.figure(1, figsize=(30, 30)) plt.axis("off") plt.title(run_name + "/" + "Condor Memory Utilization Scheme") pos = nx.graphviz_layout(self.G) nx.draw_networkx(self.G, pos, k=10, with_labels=False, node_size=1500, node_color=self.memory_colors()) nx.draw_networkx_labels(self.G, pos, labels=self.memory_labels()) plt.savefig(condor_path + run_name + "/" + "CondorMemoryUtilization.png") plt.clf() # Graph two plots the CPU utilization of various steps plt.figure(2, figsize=(30, 30)) plt.axis("off") plt.title("Condor CPU Utilization Scheme") pos = nx.graphviz_layout(self.G) nx.draw_networkx(self.G, pos, k=10, with_labels=False, node_size=1500, node_color=self.cpu_colors()) nx.draw_networkx_labels(self.G, pos, self.cpu_labels()) plt.savefig(condor_path + run_name + "/" + "CondorCpuUtilization.png") plt.clf() # Graph three plots the GPU utilization of various steps plt.figure(3, figsize=(30, 30)) plt.axis("off") plt.title("Condor GPU Utilization Scheme") pos = nx.graphviz_layout(self.G) nx.draw_networkx(self.G, pos, k=10, with_labels=False, node_size=1500, node_color=self.gpu_colors()) nx.draw_networkx_labels(self.G, pos, self.gpu_labels()) plt.savefig(condor_path + run_name + "/" + "CondorGpuUtilization.png") plt.clf()
def position_friends(request, engine, width, height, widthoffset=0, auto = False): print "Positioning friends" width = width-widthoffset ratio = float(width)/float(height) dajax = Dajax() s = request.session user = s['fbuser'] print "Got fbuser object" p = Person.objects.get(id = user.id) print "AJAX checking if connections_ready = " +str(p.connections_ready) #Check if the connections are ready to be returned; if not tell client to wait 5s if (not p.connections_ready): print "Connections not ready" dajax.add_data({'time':3000, 'auto':auto}, 'grapher.waitToPosition') return dajax.json() nodes = user.get_friend_ids() print "Got nodes" links = user.get_friends_links() print "Got links" #print links G_wrapper = GraphWrapper(nodes, links) G = G_wrapper.G print "Producing layout" if (engine=="sfdp"): layout=nx.graphviz_layout(G, prog='sfdp', args="-Gratio=%f -GK=1.5" % (ratio)) elif (engine=="twopi"): layout=nx.graphviz_layout(G, prog='twopi', args="-Gratio=%f" % ratio) else: #Invalid layout engine? return dajax.json() x_coords = [p[0] for p in layout.values()] y_coords = [p[1] for p in layout.values()] min_x = min(x_coords) max_x = max(x_coords) min_y = min(y_coords) max_y = max(y_coords) x_shift = -1 * min_x y_shift = -1*min_y x_scale = float(width-20)/float(max_x-min_x) y_scale = float(height-20)/float(max_y-min_y) scaled_layout = {} for node in layout: x = int((layout[node][0] + x_shift) * x_scale)+10+widthoffset y = int((layout[node][1] + y_shift) * y_scale)+10 scaled_layout[node] = (x,y) #print scaled_layout if auto: dajax.add_data(scaled_layout, 'grapher.auto_set_positions') else: dajax.add_data(scaled_layout, 'grapher.set_positions') return dajax.json()
def draw_communities(community_graph, filename): def get_color(value): value *= 1000 return "#" + format(int(value * 99999999999999), 'x')[:6] size = float(len(set(community_graph.partition.values()))) g_layout = community_graph.graph.copy() # print community_graph.partition # g_layout.remove_edges_from([ # e for e in g_layout.edges_iter() # if (community_graph.partition[e[0]] != community_graph.partition[e[1]] and random.random()<.997) # ]) pos = nx.graphviz_layout(g_layout, prog='sfdp') # pos = nx.spring_layout(g_layout) # print [(community_graph.partition[n1], community_graph.partition[n2]) for n1,n2 in g_layout.edges_iter()] count = 0. for com in set(community_graph.partition.values()): count = count + 1. list_nodes = [ nodes for nodes in community_graph.partition.keys() if community_graph.partition[nodes] == com ] # print get_color(count/ size) nx.draw_networkx_nodes(community_graph.graph, pos, list_nodes, node_size=100, node_color=get_color(count / size)) nx.draw_networkx_edges(community_graph.graph, pos, alpha=0.2) fig.savefig(filename + '.png')
def draw(self): if os.path.exists(self.service_dep_file_path): graph = nx.DiGraph() service_dep_file_handle = open(self.service_dep_file_path, 'r') try: raw_connection_instance = service_dep_file_handle.readline() while raw_connection_instance: connection_instance = raw_connection_instance.strip('\n') sub_str = connection_instance.split(' ') source_sub_str = sub_str[0] destination_sub_str = sub_str[1] localhost = sub_str[0].split(',') if len(destination_sub_str) == 0: destination_sub_str = 'remote process' graph.add_node(source_sub_str) graph.add_node(destination_sub_str) graph.add_edge(source_sub_str, destination_sub_str) graph.add_edge(source_sub_str, localhost[0]) raw_connection_instance = service_dep_file_handle.readline( ) # Set the attributes of the grpah # pos=nx.spring_layout(graph,dim=2,iterations=5) pos = nx.graphviz_layout(graph, prog='dot') nx.draw(graph, pos, edge_color='b', font_size=15) plt.show() finally: service_dep_file_handle.close()
def draw(self, figsize=None): """Draw game tree.""" plt.figure(figsize=figsize) try: pos = nx.graphviz_layout(self.tree, prog='dot') except AttributeError: pos = nx.nx_pydot.graphviz_layout(self.tree, prog='dot') # leaf (terminal) nodes leaf_nodes = [node for node in self.tree.nodes() if self.is_leaf(node)] nx.draw_networkx_nodes(self.tree, pos, nodelist=leaf_nodes, enode_shape='s', node_color="k") # decision nodes dec_nodes = [node for node in self.tree.nodes() if not self.is_leaf(node)] nx.draw_networkx_nodes( self.tree, pos, nodelist=dec_nodes, node_shape='o', node_color=[self.PLAYER_COLORS[self.tree.node[node]["player"]] for node in dec_nodes]) # labelled edges nx.draw_networkx_edges(self.tree, pos, arrows=False) nx.draw_networkx_edge_labels(self.tree, pos, edge_labels=self.edge_labels)
def latLonNxGraph(inGraph, labels=False, neatoLayout=False, showPlot=False): ''' Draw a networkx graph representing a feeder.''' plt.axis('off') plt.tight_layout() # Layout the graph via GraphViz neato. Handy if there's no lat/lon data. if neatoLayout: # HACK: work on a new graph without attributes because # graphViz tries to read attrs. cleanG = nx.Graph(inGraph.edges()) # HACK2: might miss nodes without edges without the following. cleanG.add_nodes_from(inGraph) pos = nx.graphviz_layout(cleanG, prog='neato') else: pos = {n: inGraph.node[n].get('pos', (0, 0)) for n in inGraph} # Draw all the edges. for e in inGraph.edges(): eType = inGraph.edge[e[0]][e[1]].get('type', 'underground_line') ePhases = inGraph.edge[e[0]][e[1]].get('phases', 1) standArgs = { 'edgelist': [e], 'edge_color': _obToCol(eType), 'width': 2, 'style': { 'parentChild': 'dotted', 'underground_line': 'dashed' }.get(eType, 'solid') } if ePhases == 3: standArgs.update({'width': 5}) nx.draw_networkx_edges(inGraph, pos, **standArgs) standArgs.update({'width': 3, 'edge_color': 'white'}) nx.draw_networkx_edges(inGraph, pos, **standArgs) standArgs.update({'width': 1, 'edge_color': _obToCol(eType)}) nx.draw_networkx_edges(inGraph, pos**standArgs) if ePhases == 2: standArgs.update({'width': 3}) nx.draw_networkx_edges(inGraph, pos, **standArgs) standArgs.update({'width': 1, 'edge_color': 'white'}) nx.draw_networkx_edges(inGraph, pos, **standArgs) else: nx.draw_networkx_edges(inGraph, pos, **standArgs) # Draw nodes and optional labels. nx.draw_networkx_nodes(inGraph, pos, nodelist=pos.keys(), node_color=[ _obToCol(inGraph.node[n].get( 'type', 'underground_line')) for n in inGraph ], linewidths=0, node_size=40) if labels: nx.draw_networkx_labels(inGraph, pos, font_color='black', font_weight='bold', font_size=0.25) if showPlot: plt.show()
def plot_cell_topology(cell, label=False): g = cell_to_graph(cell, label=label) axon, sd = axon_dendrites(g) node_size = node_sizes(g) weights = np.array([g.edge[e[0]][e[1]]['weight'] for e in g.edges()]) try: pos = nx.graphviz_layout(g, prog='twopi', root=cell.path + '/comp_1') except (NameError, AttributeError) as e: # this is the best networkx can do by itself. Its Furchtman # Reingold layout ends up with overlapping edges even for a # tree. igraph does much better. pos = nx.spectral_layout(g) nx.draw_networkx_edges(g, pos, width=10 * weights / max(weights), edge_color='gray', alpha=0.8) nx.draw_networkx_nodes( g, pos, with_labels=False, nnode_size=node_size * 500, node_color=['k' if x in axon else 'gray' for x in g.nodes()], linewidths=[1 if n.endswith('comp_1') else 0 for n in g.nodes()], alpha=0.8) if label: labels = dict([(n, g.node[n]['label']) for n in g.nodes()]) nx.draw_networkx_labels(g, pos, labels=labels) plt.title(cell.__class__.__name__)
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 draw_adjacency_graph(adjacency_matrix, node_color=None, size=10, layout='graphviz', prog='neato', node_size=80, colormap='autumn'): graph = nx.from_scipy_sparse_matrix(adjacency_matrix) plt.figure(figsize=(size, size)) plt.grid(False) plt.axis('off') if layout == 'graphviz': pos = nx.graphviz_layout(graph, prog=prog) else: pos = nx.spring_layout(graph) if len(node_color) == 0: node_color = 'gray' nx.draw_networkx_nodes(graph, pos, node_color=node_color, alpha=0.6, node_size=node_size, cmap=plt.get_cmap(colormap)) nx.draw_networkx_edges(graph, pos, alpha=0.5) plt.show()
def plot(self): if self.pos == None: self.pos = nx.graphviz_layout(self) NODE_SIZE = 500 plt.clf() nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.normal, node_color=NORMAL_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.contam, node_color=CONTAM_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.immune, node_color=IMMUNE_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.dead, node_color=DEAD_COLOR, node_size=NODE_SIZE) nx.draw_networkx_edges(self, pos=self.pos, edgelist=self.nondead_edges(), width=2, edge_color='0.2') nx.draw_networkx_labels(self, pos=self.pos, font_color='0.95', font_size=11) plt.gca().get_xaxis().set_visible(False) plt.gca().get_yaxis().set_visible(False) plt.draw()
def datatypes(self, pattern='*', save=None): graph = self.get_graph.datatypes(pattern) plt.figure(figsize=(8, 8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') cost = lambda v: float(graph.degree(v)) ** 3 + \ graph.weights[v] ** 2 node_size = [cost(v) for v in graph] # node_size = [graph.weights[v] ** 2 for v in graph] # node_color = [float(graph.degree(v)) for v in graph] node_color = [cost(v) for v in graph] nx.draw(graph, pos, node_size=node_size, node_color=node_color, font_size=13, font_color='green', font_weight='bold', with_labels=True) plt.axis('off') if save is not None: plt.savefig(save) plt.show()
def field_values(self, field_name, save=None): graph = self.get_graph.field_values(field_name) plt.figure(figsize=(8, 8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') cost = lambda v: graph.weights[v] graph.weights[field_name] = max([cost(v) for v in graph]) / 2.0 costs = norm_costs([cost(v) for v in graph], 10000) nx.draw(graph, pos, node_size=costs, node_color=costs, font_size=13, font_color='black', font_weight='bold', with_labels=True) plt.axis('off') if save is not None: plt.savefig(save) plt.show()
def _draw_rest_resource(self, graph, save=None): plt.figure(figsize=(8, 8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') cost = lambda v: float(graph.degree(v)) ** 3 + \ graph.weights[v] ** 2 node_size = [cost(v) for v in graph] # node_size = [graph.weights[v] ** 2 for v in graph] # node_color = [float(graph.degree(v)) for v in graph] node_color = [cost(v) for v in graph] nx.draw(graph, pos, node_size=node_size, node_color=node_color, font_size=13, font_color='green', font_weight='bold') plt.axis('off') if save is not None: plt.savefig(save) plt.show()
def prettyPlotter(self, l=None, filename=None): """ Metod służy do rysowania grafu reprezentującego sieć, w którym węzły należące do tej samej grupy są oznaczone jednym kolorem. @type l: list @param l: lista list węzłów podzielonych na grupy @param filename: nazwa pliku PNG z wynikowym obrazem """ nodeList = l colorList = [0] * self.graph.number_of_nodes() for nbunch in nodeList: for n in nbunch: colorList[self.graph.nodes().index(n)] = nodeList.index(nbunch) import matplotlib.pyplot as plt pos = nx.graphviz_layout(self.graph, prog='neato') plt.figure() plt.axis('off') nx.draw(self.graph, pos, node_color=colorList, with_labels=False) if filename: import config filename = config.PLOT_OUT_DIR+filename plt.savefig(filename) else: plt.show()
def image_from_graph(graph, layout_prog='dot', outpath=None): """ Create an image from a :class:`NetworkX.DiGraph`. The standard image is a PNG image, with a standard *tree* look. The image type is based on the extension of the file specified by outpath. :param root_node: The root of the Hierarchy. :type root_node: GSGroup or GSHierarchy :param layout_prog: The graphviz layout program to use to layout the Hierarchy AGraph before drawing. :type layout_prog: string """ if outpath is None: outpath = "%s_nxgraph.svg" % root_node.get_name() # # Commented out here is the code that creates the Image # by using the graphviz backend of NetworkX. # # agraph = nx.to_agraph(graph) # agraph.graph_attr.update(**graph_wide_settings) # agraph.node_attr.update(**node_settings) # agraph.edge_attr.update(**edge_settings) # agraph.layout(prog=layout_prog) # agraph.draw('other_'+outpath) pos=nx.graphviz_layout(graph, prog=layout_prog) plt.figure(**figure_settings) nx.draw(graph, pos, node_color=range(graph.number_of_nodes()), **drawing_settings) plt.savefig(outpath)
def draw_graph(self, my_list=None): # pos = nx.spring_layout(self.G, iterations=20) pos = nx.graphviz_layout(self.G, prog='sfdp', root='downlod_0', args="-Grankdir=LR") #pos = nx.spring_layout(self.G,fixed = ['r1_c1'], scale=2) #print(pos) #pos = self.h_recur(self.G, 'download_0') #nx.draw(self.G, pos=pos, with_labels=True) for node in self.G.nodes(): self.G.node[node]['category'] = 'type_A' if my_list: for my_nodes2 in my_list: self.G.node[my_nodes2]['category'] = 'critical_path' color_map = {'type_A':'y', 'critical_path':'#FFC266'} ## construct a list of colors then pass to node_color if my_list: nx.draw(self.G, pos=pos, node_size=200, node_color=[color_map[self.G.node[node]['category']] for node in self.G]) else: nx.draw(self.G, pos=pos, node_size=200, node_color='y') node_labels = nx.get_node_attributes(self.G, 'id') nx.draw_networkx_labels(self.G, pos, labels=node_labels, font_size=8, font_color='r', font_weight='bold', font_family='sans-serif') """edge_labels = nx.get_edge_attributes(self.G, 'weight') for key, value in edge_labels.items(): edge_labels[key] = round(value, 4)""" #print('edge lbl', edge_labels) #nx.draw_networkx_edge_labels(self.G, pos, labels=edge_labels) plt.show()
def KernelQuickShiftTreeEmbedding(X, knn=10, knn_density=None, k_threshold=0.9, metric='linear', **args): if knn_density is None: knn_density = knn n_instances = X.shape[0] # extract pairwise similarity matrix with desired kernel from sklearn import metrics K = metrics.pairwise.pairwise_kernels(X, metric=metric, **args) # compute instance density as average pairwise similarity import numpy as np density = np.sum(K, 0) / n_instances # compute list of nearest neighbors Ka = np.argsort(-K) # make matrix of densities ordered by nearest neighbor Kad = density[Ka] parent_dict = {} # for all instances determine parent link for i, row in enumerate(Kad): i_density = row[0] # if a densed neighbor cannot be found then assign parent to the instance itself parent_dict[i] = i # for all neighbors from the closest to the furthest for jj, d in enumerate(row): # proceed until k neighbors have been explored if jj > knn_density: break j = Ka[i, jj] if jj > 0: j_density = d # if the density of the neighbor is higher than the density of the instance assign parent if j_density > i_density: parent_dict[i] = j break # make a graph with instances as nodes import networkx as nx G = nx.Graph() G.add_nodes_from(range(n_instances)) # add edge between instance and parent for i in range(n_instances): j = parent_dict[i] G.add_edge(i, j, weight=1) # determine threshold as k-th quantile on pairwise similarity on the knn similarity knn_similarities = K[Ka[:, knn]] # vectorized_pairwise_similarity = np.ravel(K) k_quantile = np.percentile(knn_similarities, k_threshold * 100) # add edge between instance and k-th nearest neighbor if similarity > threshold for i in range(n_instances): # id of k-th nearest neighbor jd = Ka[i, knn] # similarity of k-th nearest neighbor kd = K[i, jd] if kd > k_quantile: G.add_edge(i, jd, weight=1) # use graph layout algorithm to determine coordinates X_ = nx.graphviz_layout(G, prog='sfdp', args='-Goverlap=scale') X_2D = [] for i in range(K.shape[0]): X_2D.append(list(X_[i])) X_emb = np.array(X_2D) from sklearn.preprocessing import scale return scale(X_emb)
def generate_network(G, output_path, network_data): initial_pos = nx.graphviz_layout(G, prog='neato') pos = forceatlas2.forceatlas2_networkx_layout( G, pos=initial_pos, niter=100, gravity=.12, strongGravityMode=True, scalingRatio=5.0) # Optionally specify iteration count probable_reservoirs = [] min_x = min_y = float('inf') max_x = max_y = float('-inf') for node in pos: if (min_x > pos[node][0]) and (G.degree(node) == 1): min_x = pos[node][0] probable_reservoirs.append(node) if (max_x < pos[node][0]) and (G.degree(node) == 1): max_x = pos[node][0] probable_reservoirs.append(node) if (min_y > pos[node][1]) and (G.degree(node) == 1): min_y = pos[node][1] probable_reservoirs.append(node) if (max_y < pos[node][1]) and (G.degree(node) == 1): max_y = pos[node][1] probable_reservoirs.append(node) random_index = randrange(int(len(probable_reservoirs) / 2), len(probable_reservoirs)) reservoir = probable_reservoirs[random_index] node_colors = [ 'blue' if node == reservoir else 'red' for node in G.nodes() ] nx.draw(G, pos, with_labels=False, node_color=node_colors, node_size=50) plt.show() write_inp_file(G, pos, output_path, network_data, output_path)
def displayGraph(self, g, label=False): axon, sd = axon_dendrites(g) sizes = node_sizes(g) * 50 if len(sizes) == 0: print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections') return weights = np.array([g.edge[e[0]][e[1]]['weight'] for e in g.edges()]) pos = nx.graphviz_layout(g, prog='twopi') xmin, ymin, xmax, ymax = 1e9, 1e9, -1e9, -1e9 for p in list(pos.values()): if xmin > p[0]: xmin = p[0] if xmax < p[0]: xmax = p[0] if ymin > p[1]: ymin = p[1] if ymax < p[1]: ymax = p[1] edge_widths = 10.0 * weights / max(weights) node_colors = ['k' if x in axon else 'gray' for x in g.nodes()] lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()] self.axes.clear() try: nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw) except (NameError, AttributeError) as e: nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
def architecture(self, with_datatypes=True, save=None): graph = self.get_graph.architecture(with_datatypes) plt.figure(figsize=(8,8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') # node_size = [(float(graph.degree(v)) * 5)**3 for v in graph] # node_size = [graph.weights[v] ** 2 for v in graph] # node_color = [float(graph.degree(v)) for v in graph] # node_color = [graph.weights[v] ** 2 for v in graph] cost = lambda v: float(graph.degree(v)) ** 3 + \ graph.weights[v] ** 2 costs = norm_costs([cost(v) for v in graph], 10000) nx.draw(graph, pos, labels=graph.labels, node_size=costs, node_color=costs, font_size=13, font_color='orange', font_weight='bold' ) plt.axis('off') if save is not None: plt.savefig(save) plt.show()
def plot(self, graph_type): # pypy doesn't support matplotlib and networkx, :( import matplotlib.pyplot as plt import networkx as nx nx_graph = nx.Graph() for node in self.get_nodes().values(): nx_graph.add_node(node.get_id(), type=node.get_type()) for node in self.get_nodes().values(): for link in node.get_links(): end_point = link.get_end_points() neighbor = end_point[0] if node.get_id() != end_point[0] else end_point[1] nx_graph.add_edge(node.get_id(), neighbor, weight=100) hosts = [(u) for (u, v) in nx_graph.nodes(data = True) if v["type"] == "host"] switches = [(u) for (u, v) in nx_graph.nodes(data = True) if v["type"] == "switch"] pos = nx.graphviz_layout(nx_graph) # draw graph nx.draw_networkx_nodes(nx_graph, pos, nodelist=switches, node_size=100, label="x") nx.draw_networkx_nodes(nx_graph, pos, nodelist=hosts, node_size=50, node_color='b') nx.draw_networkx_edges(nx_graph, pos) plt.savefig("graphs/" + graph_type + '.png') plt.clf()
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 __init__(self, pipeline): self.pipeline = pipeline self.graph = pipeline.graph type2color = dict(file = "orange", topic="red", program="blue") self.colors = [type2color[self.graph.node[node]["type"]] for node in self.graph.nodes()] self.positions = nx.graphviz_layout(self.graph, prog="dot") self.labels = dict(zip(self.graph.nodes(), self.graph.nodes()))
def colorSubcomps(self, G, prog="neato", layout=None): C = nx.connected_component_subgraphs(G) pos = nx.graphviz_layout(G, prog=prog) if layout == None else layout for g in C: c = [random.random()] * nx.number_of_nodes(g) # random color... nx.draw(g, pos, node_size=40, node_color=c, vmin=0.0, vmax=1.0, with_labels=False)
def make_tree_figure(wanted_seqs, trop_dict, tree_file): mat_data = get_pairwise_distances(wanted_seqs, tree_file = tree_file) tree = Phylo.read(open(tree_file), 'newick') net = Phylo.to_networkx(tree) node_mapping = {} clade = 1 for node in net.nodes(): if node.name is None: node_mapping[node] = 'Clade-%i' % clade clade += 1 else: node_mapping[node] = node.name new_net = networkx.relabel_nodes(net, node_mapping) colors = [] for node in new_net.nodes(): if node.startswith('Clade'): colors.append('w') elif trop_dict[node]: colors.append('g') elif not trop_dict[node]: colors.append('r') else: print node #print colors, len(colors), len(new_net.nodes()) pos = networkx.graphviz_layout(new_net, 'twopi') networkx.draw_networkx(new_net, pos, with_labels = False, node_color = colors)
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 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 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 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 renameSrcDst(orig_g, s, d, layout=None): ''' currently only undirected "g" are supported. change the nodes s and d into nodes "Src" and "Dst". of course edges are preserved. TODO: make sure that attributes of nodes and their edges are preserved, too. return a new g and its updated (if "layout" was specified) layout. ''' g = orig_g.copy() if layout: import copy g_layout = copy.copy(layout) pass else: g_layout = nx.graphviz_layout(g) pass for oldlabel, newlabel in ((s, 'Src'), (d, 'Dst')): for neighbor in g.neighbors(oldlabel): g.add_edge(newlabel, neighbor) pass g.remove_node(oldlabel) g_layout[newlabel]=g_layout[oldlabel] del g_layout[oldlabel] pass return g, g_layout
def erd(self, subset=None, prog='dot'): """ plot the schema's entity relationship diagram (ERD). The layout programs can be 'dot' (default), 'neato', 'fdp', 'sfdp', 'circo', 'twopi' """ if not subset: g = self.graph else: g = self.graph.copy() for i in g.nodes(): if i not in subset: g.remove_node(i) def tableList(tier): return [i for i in g if self.tables[i].tier==tier] pos=nx.graphviz_layout(g,prog=prog,args='') plt.figure(figsize=(8,8)) nx.draw_networkx_edges(g, pos, alpha=0.3) nx.draw_networkx_nodes(g, pos, nodelist=tableList('manual'), node_color='g', node_size=200, alpha=0.3) nx.draw_networkx_nodes(g, pos, nodelist=tableList('computed'), node_color='r', node_size=200, alpha=0.3) nx.draw_networkx_nodes(g, pos, nodelist=tableList('imported'), node_color='b', node_size=200, alpha=0.3) nx.draw_networkx_nodes(g, pos, nodelist=tableList('lookup'), node_color='gray', node_size=120, alpha=0.3) nx.draw_networkx_labels(g, pos, nodelist = subset, font_weight='bold', font_size=9) nx.draw(g,pos,alpha=0,with_labels=False) plt.show()
def startGame(self): print "starting game", self.configuration self.startNode = [loadGame(self.configuration).toString()] threads = [] for i in range(10): t = threading.Thread(target=self.ant, args=(i,)) threads.append(t) t.start() print "Waiting..." for t in threads: t.join() print "Waiting done" # nx.draw(self.stateSpace) myBoard = loadGame(self.configuration).toString() pos=nx.graphviz_layout(self.stateSpace,prog='neato') nx.draw(self.stateSpace,pos=pos,node_size=20) nx.draw_networkx_nodes(self.stateSpace,pos, nodelist=[myBoard], node_color='g', node_size=100) nx.draw_networkx_nodes(self.stateSpace,pos, nodelist=list(self.winNodes), node_color='b', node_size=100) # A = nx.to_agraph(self.stateSpace) # A.layout(prog='neato', color='red') # A.draw('color.png') plt.show()
def draw_adjacency_graph(adjacency_matrix, node_color=None, size=10, layout='graphviz', prog='neato', node_size=80, colormap='autumn'): """draw_adjacency_graph.""" graph = nx.from_scipy_sparse_matrix(adjacency_matrix) plt.figure(figsize=(size, size)) plt.grid(False) plt.axis('off') if layout == 'graphviz': pos = nx.graphviz_layout(graph, prog=prog) else: pos = nx.spring_layout(graph) if len(node_color) == 0: node_color = 'gray' nx.draw_networkx_nodes(graph, pos, node_color=node_color, alpha=0.6, node_size=node_size, cmap=plt.get_cmap(colormap)) nx.draw_networkx_edges(graph, pos, alpha=0.5) plt.show()
def Main(): G = kw2Jd(searchterm) H = nx.Graph(G) font = {'fontname': 'Arial', 'color': 'k', 'fontweight': 'bold', 'fontsize': 14} plt.rcParams['text.usetex'] = False plt.figure(figsize=(8, 8)) plt.title("PZ", font) plt.axis('off') plt.text(0.5, .95, searchterm, horizontalalignment='center', transform=plt.gca().transAxes) try: pos = nx.graphviz_layout(H) except: pos = nx.spring_layout(H, iterations=20) nx.draw_networkx_edges( H, pos, alpha=0.1, node_size=0, edge_color='w', width=3) nx.draw_networkx_labels(H, pos, fontsize=12) nodesize = [salary.get(v, 0) ** 2 for v in H] colorcoding = [supply.get(v, 10000) / (openings.get(v, 1) + 1) for v in H] linewidths = [ (abs(trends.get(v, 0)) - trends.get(v, 10000)) / 10 for v in H] nodes = H.nodes() nx.draw_networkx_nodes(H, pos, nodelist=nodes, node_size=nodesize, linewidths=linewidths, cmap=plt.cm.Blues, vmin=min( colorcoding), vmax=100, node_color=colorcoding) plt.savefig("pz-networkx.png", dpi=75) plt.show()
def draw(self): if os.path.exists(self.service_dep_file_path): graph=nx.DiGraph() service_dep_file_handle=open(self.service_dep_file_path,'r') try: raw_connection_instance=service_dep_file_handle.readline() while raw_connection_instance: connection_instance=raw_connection_instance.strip('\n') sub_str=connection_instance.split(' ') source_sub_str=sub_str[0] destination_sub_str=sub_str[1] localhost=sub_str[0].split(',') if len(destination_sub_str)==0: destination_sub_str='remote process' graph.add_node(source_sub_str) graph.add_node(destination_sub_str) graph.add_edge(source_sub_str,destination_sub_str) graph.add_edge(source_sub_str,localhost[0]) raw_connection_instance=service_dep_file_handle.readline() # Set the attributes of the grpah # pos=nx.spring_layout(graph,dim=2,iterations=5) pos=nx.graphviz_layout(graph,prog='dot') nx.draw(graph,pos,edge_color='b',font_size=15) plt.show() finally: service_dep_file_handle.close()
def getRandom(): try: mydata = request.json n=mydata["n"] binary=mydata["binary"] nested_taxa=mydata["nested_taxa"] taxa = [str(i+1) for i in range(n)] offsetId = mydata["offsetId"] offsetx = mydata["offsetx"] offsety = mydata["offsety"] tg = tgr(taxa, binary=binary, nested_taxa=nested_taxa, id_offset=offsetId) net = tg.next() #net = pn() #net._lastlabel = offsetId #net.from_eNewick(eNewick) #session['eNewick'] = eNewick pos = nx.graphviz_layout(net, 'dot') minx = min([pos[u][0] for u in net.nodes()]) miny = min([pos[u][1] for u in net.nodes()]) offsettoapplyx = minx - offsetx - 50 offsettoapplyy = miny - offsety nodes = [{'id':u,'label': net.label(u), 'x':pos[u][0]-offsettoapplyx, 'y':-pos[u][1]+offsettoapplyy} for u in net.nodes()] edges = [{'source':edge[0],'target':edge[1], 'type': 'arrow'} for edge in net.edges()] dict = {'nodes':nodes,'edges':edges} return jsonify(response=dict) except Exception, err: return jsonify(response={'error':'Some error occurred. Please chech your data. If you think this is a bug, please contact us (see About section)\n Error message: %s' % err})
def get(self, request, name="root", *args, **kwargs): import networkx as nx import matplotlib as mpl mpl.use("Agg") import matplotlib.pyplot as plt import nxedges plt.figure(figsize=(10, 8)) g = nx.DiGraph() labels = {} for service in Service.objects.all(): g.add_node(service.id) if len(service.name) > 8: labels[service.id] = service.name[:8] + "\n" + service.name[8:] else: labels[service.id] = service.name for tenant in CoarseTenant.objects.all(): if (not tenant.provider_service) or (not tenant.subscriber_service): continue g.add_edge(tenant.subscriber_service.id, tenant.provider_service.id) pos = nx.graphviz_layout(g) nxedges.xos_draw_networkx_edges(g, pos, arrow_len=30) nx.draw_networkx_nodes(g, pos, node_size=5000) nx.draw_networkx_labels(g, pos, labels, font_size=12) # plt.axis('off') plt.savefig("/tmp/foo.png") return HttpResponse(open("/tmp/foo.png", "r").read(), content_type="image/png")
def show_py(nodes, edges, width, height, outfile): g = nx.Graph() labels = dict() colors = list() sizes = list() for e in nodes: g.add_node(e["id"]) g.node[e["id"]]['color'] = e["color"] g.node[e["id"]]['size'] = e["size"] labels[e["id"]] = e["label"] for e in edges: g.add_edge(e["source"], e["target"]) for n in g.nodes(): colors.append(g.node[n]["color"]) sizes.append(g.node[n]["size"]) print "XXX 0" plt.figure(figsize=(width,height)); print "XXX 1" pos = nx.graphviz_layout(g) print "XXX 2" gx = nx.draw_networkx(g, pos, labels=labels, node_size=sizes, node_color=colors, font_size=7, font_color="black", edge_color="grey") #gx = nx.draw_networkx(g, labels=labels, node_size=sizes, node_color=colors, font_size=7, font_color="black", edge_color="grey") print "XXX 3" s = plt.savefig(outfile, bbox_inches="tight") #s = plt.savefig(outfile) print "XXX 4"
def visualize(tree, custom_alpha=0.5, labels=False): G = nx.Graph(tree) pos = nx.graphviz_layout(G, prog='twopi', args='', root='root') plt.figure(figsize=(10, 10)) nx.draw(G, pos, node_size=0, alpha=custom_alpha, node_color="blue", with_labels=labels) plt.axis('equal') plt.show()
def datatypes(self, pattern='*', save=None): graph = self.get_graph.datatypes(pattern) plt.figure(figsize=(8,8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') cost = lambda v: float(graph.degree(v)) ** 3 + \ graph.weights[v] ** 2 node_size = [cost(v) for v in graph] # node_size = [graph.weights[v] ** 2 for v in graph] # node_color = [float(graph.degree(v)) for v in graph] node_color = [cost(v) for v in graph] nx.draw(graph, pos, node_size=node_size, node_color=node_color, font_size=13, font_color='green', font_weight='bold' ) plt.axis('off') if save is not None: plt.savefig(save) plt.show()
def architecture(self, with_datatypes=True, save=None): graph = self.get_graph.architecture(with_datatypes) plt.figure(figsize=(8, 8)) pos = nx.graphviz_layout(graph, prog='twopi', args='') # node_size = [(float(graph.degree(v)) * 5)**3 for v in graph] # node_size = [graph.weights[v] ** 2 for v in graph] # node_color = [float(graph.degree(v)) for v in graph] # node_color = [graph.weights[v] ** 2 for v in graph] cost = lambda v: float(graph.degree(v)) ** 3 + \ graph.weights[v] ** 2 costs = norm_costs([cost(v) for v in graph], 10000) nx.draw(graph, pos, labels=graph.labels, node_size=costs, node_color=costs, font_size=13, font_color='orange', font_weight='bold', with_labels=True) plt.axis('off') if save is not None: plt.savefig(save) 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.drawing.nx_pydot.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(self): pos = nx.graphviz_layout(self.G, prog='dot') nx.draw(self.G, pos, node_size=100, alpha=0.4, edge_color='r', font_size=16)
def _set_layout(nx_graph, scores, labels): positions = _nx.graphviz_layout(nx_graph, prog="neato") # prog options: neato, dot, fdp, sfdp, twopi, circo centered_positions = _center_positions(positions) for node in nx_graph.nodes(): nx_graph.node[node]['viz'] = _get_viz_data(node, centered_positions, scores) label = labels[node] if labels is not None and node in labels else node nx_graph.node[node]['label'] = " ".join(label.split()[0:2]) nx_graph.node[node]['id'] = label
def _layout_force(self, graph): two_dimensional_data_matrix = nx.graphviz_layout( graph, prog=self.layout_prog, args=self.layout_prog_args) two_dimensional_data_list = [ list(two_dimensional_data_matrix[i]) for i in range(len(graph)) ] embedded_data_matrix = scale(np.array(two_dimensional_data_list)) return embedded_data_matrix
def _graph_embedding(self, graph): two_dimensional_data_matrix = nx.graphviz_layout( graph, prog='sfdp', args='-Goverlap=scale') two_dimensional_data_list = [ list(two_dimensional_data_matrix[i]) for i in range(len(graph)) ] embedded_data_matrix = scale(np.array(two_dimensional_data_list)) return embedded_data_matrix
def do_plot(self, line): "Plot topology colored by node placement" # Import networkx if needed global nx, plt if not nx: try: import networkx as nx import matplotlib.pyplot as plt import pygraphviz assert pygraphviz # silence pyflakes except: error('plot requires networkx, matplotlib and pygraphviz - ' 'please install them and try again\n') return # Make a networkx Graph g = nx.Graph() mn = self.mn servers, hosts, switches = mn.servers, mn.hosts, mn.switches nodes = hosts + switches g.add_nodes_from(nodes) links = [(link.intf1.node, link.intf2.node) for link in self.mn.links] g.add_edges_from(links) # Pick some shapes and colors # shapes = hlen * [ 's' ] + slen * [ 'o' ] color = dict(zip(servers, self.colorsFor(servers))) # Plot it! pos = nx.graphviz_layout(g) opts = { 'ax': None, 'font_weight': 'bold', 'width': 2, 'edge_color': 'darkblue' } hcolors = [color[getattr(h, 'server', 'localhost')] for h in hosts] scolors = [color[getattr(s, 'server', 'localhost')] for s in switches] nx.draw_networkx(g, pos=pos, nodelist=hosts, node_size=800, label='host', node_color=hcolors, node_shape='s', **opts) nx.draw_networkx(g, pos=pos, nodelist=switches, node_size=1000, node_color=scolors, node_shape='o', **opts) # Get rid of axes, add title, and show fig = plt.gcf() ax = plt.gca() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.canvas.set_window_title('Mininet') plt.title('Node Placement', fontweight='bold') plt.show()
def draw_graph(graph): pos = nx.graphviz_layout(graph, prog='dot') nx.draw(graph, pos, node_color='#A0CBE2', edge_color='#BB0000', width=2, edge_cmap=plt.cm.Blues, with_labels=True)
def drawRootedDAG(g): labels=dict((n,d['label']) for n,d in g.nodes(data=True)) labels={k:str(k)+':'+v for (k,v) in labels.items()} nx.write_dot(g, 'tmp.dot') pos = nx.graphviz_layout(g, prog='dot') # same layout using matplotlib with no labels nx.draw(g, pos, labels=labels) pylab.show()
def draw_trait_network_for_culture(self, culture, node_list): trait_subgraph = self.graph.subgraph(node_list) pos = nx.graphviz_layout(trait_subgraph, prog='dot') nx.draw(trait_subgraph, pos, with_labels=True, arrows=False, label=culture) plt.show()
def show_graph(graph): m = graph.copy() pos = nx.graphviz_layout(m) nx.draw_networkx_edge_labels(m, pos) nx.draw_networkx_nodes(m, pos) nx.draw_networkx_labels(m, pos) nx.write_dot(m, "m.dot") os.system("dot -Tps m.dot -o m.ps") nx.draw(m, pos)
def _plot_sub_plot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.graphviz_layout(graph, prog=prog) green_nodes = [] yellow_nodes = [] red_nodes = [] blue_nodes = [] for node, values in graph.nodes(data=True): shape = 'o' if values['type'] in type_format: shape = type_format[values['type']] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) if node in new_nodes: blue_nodes.append(node) elif 'rank' in values and values['rank'] > 7: red_nodes.append(node) elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: yellow_nodes.append(node) else: green_nodes.append(node) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes)
def drawTreeGraph(myGraph): pos = networkx.spring_layout(myGraph) try: from networkx import graphviz_layout pos = networkx.graphviz_layout(myGraph, prog='twopi', args='') except: try: pos = networkx.graphviz_layout(myGraph, prog='dot', args='') except: pos = networkx.spring_layout(myGraph) print "fall back to spring layout. Nicer graphs might result if either compatible PyGraphviz or Pydot packages were available" networkx.draw_networkx(myGraph, pos, with_labels=True, arrows=True, node_color='#667766', node_size=10, alpha=0.2)
def simple_undirected(G, fname=''): ug = nx.Graph(G.edges()) sg = sorted(nx.connected_component_subgraphs(ug), key=len, reverse=True) pos = nx.graphviz_layout(sg[0]) nx.draw_networkx_edges(sg[0], pos, alpha=0.2) if fname == '': plt.show() else: plt.savefig(fname)
def plot_celltype_graph(self, filename='celltype_graph.png'): """Display the celltype connectivity graph """ try: pos = nx.graphviz_layout(self.__celltype_graph) except Exception, e: print e pos = nx.spring_layout(self.__celltype_graph)
def plot_selected_groups(g, selected_groups, filename=None): """ Display the ImageNet DAG and highlight the selected groups in different colors. Parameters ---------- g : networkx.DiGraph selected_groups : list of ('node', list of leaf nodes) tuples filename : string, optional If given, write plot out to filename. """ fig = plt.figure(figsize=(12, 12)) gray = (0.85, 0.85, 0.85, 1) graydark = (0.5, 0.5, 0.5, 1) ns = 30 pos = nx.graphviz_layout(g, prog='sfdp') nx.draw_networkx_nodes(g, pos, with_labels=False, node_size=ns, node_color=gray, linewidth=None).set_edgecolor(graydark) root = [n for n in g.nodes() if g.predecessors(n) == []] nx.draw_networkx_nodes(g, pos, nodelist=root, with_labels=False, node_size=ns * 2, node_color=gray, linewidth=None).set_edgecolor(graydark) nx.draw_networkx_edges(g, pos, arrows=False, edge_color=[gray] * len(g.edges())) cmap = plt.get_cmap('Accent') colors = np.linspace(0, 1, len(selected_groups)) darken = lambda c, r: (c[0] * r, c[1] * r, c[2] * r, c[3]) for i, group in enumerate(selected_groups): nx.draw_networkx_nodes(g, pos, node_size=ns, nodelist=group[-1], node_color=cmap(colors[i])).set_edgecolor( darken(cmap(colors[i]), 0.75)) plt.axis('equal') plt.axis('off') if filename is not None: plt.savefig(filename, dpi=300, facecolor='none') return fig
def draw_graph(thisGraph, graphTitle, MAIN_DIRECTORY, edgeWeight=None): ''' Purpose:: Utility function to draw graph in the hierachial format Input:: thisGraph: a Networkx directed graph representing a subgraph of connected cloud elements graphTitle: a string representing the graph title MAIN_DIRECTORY: a string representing the path to the main directory where the data generated is saved edgeWeight: (optional) a list of integers representing the edge weights in the graph Returns:: None Generates:: A plot of the thisGraph ''' imgFilename = MAIN_DIRECTORY + '/images/' + graphTitle + '.gif' fig = plt.figure(facecolor='white', figsize=(16, 12)) edge95 = [(u, v) for (u, v, d) in thisGraph.edges(data=True) if d['weight'] == edgeWeight[0]] edge90 = [(u, v) for (u, v, d) in thisGraph.edges(data=True) if d['weight'] == edgeWeight[1]] edgeOverlap = [(u, v) for (u, v, d) in thisGraph.edges(data=True) if d['weight'] == edgeWeight[2]] nx.write_dot(thisGraph, 'test.dot') plt.title(graphTitle) pos = nx.graphviz_layout(thisGraph, prog='dot') # Draw graph in parts # nodes nx.draw_networkx_nodes(thisGraph, pos, with_labels=True, arrows=False) # edges nx.draw_networkx_edges(thisGraph, pos, edgelist=edge95, alpha=0.5, arrows=False) nx.draw_networkx_edges(thisGraph, pos, edgelist=edge90, edge_color='b', style='dashed', arrows=False) nx.draw_networkx_edges(thisGraph, pos, edgelist=edgeOverlap, edge_color='y', style='dashed', arrows=False) # labels nx.draw_networkx_labels(thisGraph, pos, arrows=False) plt.axis('off') plt.savefig(imgFilename, facecolor=fig.get_facecolor(), transparent=True) # Do some clean up...and ensure that we are in the right dir os.chdir((MAIN_DIRECTORY + '/')) subprocess.call('rm test.dot', shell=True)
def draw_graph(graph, node_labels=None, labels=None, graph_layout='neato', node_size=400, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='red', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # create networkx graph G = nx.Graph() # add edges for edge in graph: G.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos = nx.spring_layout(G) else: graph_pos = nx.graphviz_layout(G, prog='neato') # draw graph nx.draw_networkx_nodes(G, graph_pos, node_size=node_size, alpha=node_alpha, node_color=node_color) nx.draw_networkx_edges(G, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) nx.draw_networkx_labels(G, graph_pos, labels=node_labels, font_size=node_text_size, font_family=text_font) if labels is None: labels = range(len(graph)) edge_labels = dict(zip(graph, labels)) nx.draw_networkx_edge_labels(G, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos) # show graph plt.show()
def draw_graph(ctx, dataset, root, gp): """Draw a directed graph of forwarding""" import networkx as nx import matplotlib.pyplot as plt from graphviz import Digraph def edges_to_adj_map(edges): from collections import defaultdict map = defaultdict(list) for vertex, neighbour in edges: map[vertex].append(neighbour) return dict(map) def visit_children(G, adj_map, root, add_edge): stack = [root] while stack: node = stack.pop() neighbours = adj_map.get(node, []) stack.extend(neighbours) for neighbour in neighbours: add_edge(G, node, neighbour) if gp == "nx": G = nx.DiGraph() add_edge = lambda G, a, b: G.add_edge(a, b) elif gp == "gv": G = Digraph() add_edge = lambda G, a, b: G.edge(a, b) else: raise Exception if dataset == "desired": for vertex, neighbours in forwarders.items(): for neighbour in neighbours: if root is None or vertex == root: add_edge(G, vertex, neighbour) elif dataset == "current": existing_forwarders = get_existing_forwarders(ctx.obj[FORWARDERS_HTML]) if root is None: for vertex, neighbour in existing_forwarders: add_edge(G, vertex, neighbour) else: adj_map = edges_to_adj_map(existing_forwarders) visit_children(G, adj_map, root, add_edge) if gp == "nx": # pos = nx.spring_layout(G, k=0.2) # positions for all nodes pos = nx.graphviz_layout(G) nx.draw_networkx_nodes(G, pos, node_size=200) nx.draw_networkx_edges(G, pos, width=0.5, alpha=1) nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif') plt.axis('off') plt.show() elif gp == "gv": G.render("graph.gv", view=True)