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 drawgraph(graph,fixed): pos=nx.spring_layout(graph) nx.draw_networkx_nodes(graph,pos,with_labels=True,node_size=100) nx.draw_networkx_nodes(graph,pos,with_labels=True,nodelist=fixed,node_size=100,node_color="yellow") nx.draw_networkx_edges(graph,pos,with_labels=True,width=0.3) nx.draw_networkx_labels(graph,pos,fontsize=10) plt.show()
def drawFactorGraph(self,var_color='w',factor_color=(.2,.2,.8),**kwargs): """Draw a factorgraph using networkx function calls Args: var_color (str, tuple): networkx color descriptor for drawing variable nodes factor_color (str, tuple): networkx color for drawing factor nodes var_labels (dict): variable id to label string for variable nodes factor_labels (dict): factor id to label string for factor nodes ``**kwargs``: remaining keyword arguments passed to networkx.draw() Example: >>> model.drawFactorGraph( var_labels={0:'0', ... } ) # keyword args passed to networkx.draw() """ # TODO: specify var/factor shape,size, position, etc.; return G? silent mode? import networkx as nx G = nx.Graph() vNodes = [v.label for v in self.X if v.states > 1] # list only non-trivial variables fNodes = [-i-1 for i in range(len(self.factors))] # use negative IDs for factors G.add_nodes_from( vNodes ) G.add_nodes_from( fNodes ) for i,f in enumerate(self.factors): for v1 in f.vars: G.add_edge(v1.label,-i-1) pos = nx.spring_layout(G) # so we can use same positions multiple times... kwargs['var_labels'] = kwargs.get('var_labels',{n:n for n in vNodes}) kwargs['labels'] = kwargs.get('var_labels',{}) nx.draw_networkx(G,pos, nodelist=vNodes,node_color=var_color,**kwargs) kwargs['labels'] = kwargs.get('factor_labels',{}) # TODO: need to transform? nx.draw_networkx_nodes(G,pos, nodelist=fNodes,node_color=factor_color,node_shape='s',**kwargs) nx.draw_networkx_edges(G,pos,**kwargs) return G
def main(): G=nx.Graph() G.add_edge('a','b',weight=0.6) G.add_edge('a','c',weight=0.2) G.add_edge('c','d',weight=0.1) G.add_edge('c','e',weight=0.7) G.add_edge('c','f',weight=0.9) G.add_edge('a','d',weight=0.3) elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5] esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5] pos=nx.spring_layout(G) # positions for all nodes # nodes nx.draw_networkx_nodes(G,pos,node_size=700) # edges nx.draw_networkx_edges(G,pos,edgelist=elarge,width=6) nx.draw_networkx_edges(G,pos,edgelist=esmall,width=6,alpha=0.5,edge_color='b',style='dashed') # labels nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif') plt.axis('off') #plt.savefig("weighted_graph.png") # save as png plt.show() # display return
def draw_graph(G): # an example using Graph as a weighted network. # __author__ = """Aric Hagberg ([email protected])""" try: import matplotlib.pyplot as plt except: raise elarge = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] > 0.5] esmall = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] <= 0.5] pos = nx.spring_layout(G) # positions for all nodes # nodes nx.draw_networkx_nodes(G, pos, node_size = 200) # edges nx.draw_networkx_edges(G, pos, edgelist = elarge, width = 0.4) nx.draw_networkx_edges(G, pos, edgelist = esmall, width = 0.4, alpha = 0.6, style = 'dashed') # labels nx.draw_networkx_labels(G, pos, font_size = 6, font_family = 'sans-serif') print 'number of cliques/clusters:', nx.graph_number_of_cliques(G) print 'time:', time.time() - start 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 draw_network(self, m=2, pos=None): edgelist = [] probdict = {} nodesizes = {} position = {} observations = {} for i, node in enumerate(self.nodes[::-1]): l, u = node.ppf(.1), node.ppf(.9) c, w = .5 * (l + u), .5 * (u - l) edgelist += [(node.name, x.name) for x in node.children] probdict[node.name] = c nodesizes[node.name] = 100 + 5000 * w position[node.name] = (i / m, i % m) if pos is None else pos[node.name] observations[node.name] = '%.2f+/-%.2f' % (c, w) G = nx.DiGraph() G.add_edges_from(edgelist) values = [probdict.get(node) for node in G.nodes()] sizes = [nodesizes.get(node) for node in G.nodes()] plt.figure(figsize=(16,8)) nx.draw_networkx_nodes(G, position, node_size=sizes, cmap=plt.get_cmap('Blues'), node_color=values, vmin=-0.1, vmax=1) nx.draw_networkx_labels(G, position, {x: x for x in G.nodes()}, font_size=12, font_color='r') nx.draw_networkx_labels(G, {key: (x[0] , x[1]+.3) for key, x in position.iteritems()}, observations, font_size=12, font_color='k') nx.draw_networkx_edges(G, position, edgelist=edgelist, edge_color='r', arrows=True, alpha=0.5) # plt.xlim((-.15,.9)) plt.show()
def plot(self): """ Plots an entity relation diagram (ERD) among all nodes that is part of the current graph. """ if not self.nodes(): # There is nothing to plot logger.warning('Nothing to plot') return if pygraphviz_layout is None: logger.warning('Failed to load Pygraphviz - plotting not supported at this time') return pos = pygraphviz_layout(self, prog='dot') fig = plt.figure(figsize=[10, 7]) ax = fig.add_subplot(111) nx.draw_networkx_nodes(self, pos, node_size=200, node_color='g') text_dict = nx.draw_networkx_labels(self, pos, self.node_labels) trans = ax.transData + \ transforms.ScaledTranslation(12/72, 0, fig.dpi_scale_trans) for text in text_dict.values(): text.set_horizontalalignment('left') text.set_transform(trans) # draw primary key relations nx.draw_networkx_edges(self, pos, self.pk_edges, arrows=False) # draw non-primary key relations nx.draw_networkx_edges(self, pos, self.non_pk_edges, style='dashed', arrows=False) apos = np.array(list(pos.values())) xmax = apos[:, 0].max() + 200 # TODO: use something more sensible than hard fixed number xmin = apos[:, 0].min() - 100 ax.set_xlim(xmin, xmax) ax.axis('off') # hide axis
def plot(CG): """ Plot the call graph using matplotlib For larger graphs, this should not be used, as it is very slow and probably you can not see anything on it. :param CG: A networkx graph to plot """ pos = nx.spring_layout(CG) internal = [] external = [] for n in CG.node: if isinstance(n, ExternalMethod): external.append(n) else: internal.append(n) nx.draw_networkx_nodes(CG, pos=pos, node_color='r', nodelist=internal) nx.draw_networkx_nodes(CG, pos=pos, node_color='b', nodelist=external) nx.draw_networkx_edges(CG, pos, arrow=True) nx.draw_networkx_labels(CG, pos=pos, labels={x: "{} {}".format(x.get_class_name(), x.get_name()) for x in CG.edge}) plt.draw() plt.show()
def display_retweet_network(network, outfile=None, show=False): """ Take a DiGraph (retweet network?) and display+/save it to file. Nodes must have a 'color' property, represented literally and indicating their type Edges must have a 'weight' property, represented as edge width """ import networkx as nx import matplotlib.pyplot as plt # Create a color list corresponding to nodes. node_colors = [ n[1]["color"] for n in network.nodes(data=True) ] # Get edge weights from graph edge_weights = [ e[2]["weight"] for e in network.edges(data=True) ] # Build up graph figure #pos = nx.random_layout(network) pos = nx.spring_layout(network) nx.draw_networkx_edges(network, pos, alpha=0.3 , width=edge_weights, edge_color='m') nx.draw_networkx_nodes(network, pos, node_size=400, node_color=node_colors, alpha=0.4) nx.draw_networkx_labels(network, pos, fontsize=6) plt.title("Retweet Network", { 'fontsize': 12 }) plt.axis('off') if outfile: print "Saving network to file: {0}".format(outfile) plt.savefig(outfile) if show: print "Displaying graph. Close graph window to resume python execution" plt.show()
def plotsolution(numnodes,coordinates,routes): plt.ion() # interactive mode on G=nx.Graph() nodes = range(1,numnodes+1) nodedict = {} for i in nodes: nodedict[i] = i nodecolorlist = ['b' for i in nodes] nodecolorlist[0] = 'r' # nodes nx.draw_networkx_nodes(G, coordinates, node_color=nodecolorlist, nodelist=nodes) # labels nx.draw_networkx_labels(G,coordinates,font_size=9,font_family='sans-serif',labels = nodedict) edgelist = defaultdict(list) colors = ['Navy','PaleVioletRed','Yellow','Darkorange','Chartreuse','CadetBlue','Tomato','Turquoise','Teal','Violet','Silver','LightSeaGreen','DeepPink', 'FireBrick','Blue','Green'] for i in (routes): edge1 = 1 for j in routes[i][1:]: edge2 = j edgelist[i].append((edge1,edge2)) edge1 = edge2 nx.draw_networkx_edges(G,coordinates,edgelist=edgelist[i], width=6,alpha=0.5,edge_color=colors[i]) #,style='dashed' plt.savefig("path.png") plt.show()
def calcMetrics(): print('\nTrips:') for trip in trips: trip.display() print('\nPairs:') for a, b in itertools.combinations(trips, 2): # if isTimeTestFail(): continue bestDist = getBestDist(a, b) sumDist = a.dist + b.dist if bestDist > sumDist: continue minDist = min(a.dist, b.dist) maxDist = max(a.dist, b.dist) delta = sumDist - bestDist coPathCoeff = maxDist / bestDist effect = delta / bestDist weight = effect * coPathCoeff G.add_edge(a, b, weight=weight) print('edge is added', weight) pos = nx.random_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos, width=weight,) plt.axis('off') plt.savefig("weighted_graph.png") # save as png plt.show() # display
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 _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 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 plot_networkx_topology_graph(topology): import matplotlib.pyplot as plt import networkx as nx G = nx.Graph() top_graph = topology.get_graph() labels = {} types = {} n_types = 0 colors = [] for v in top_graph.get_vertices(): G.add_node(v.particle_index) labels[v.particle_index] = v.label if not v.particle_type() in types: types[v.particle_type()] = n_types n_types += 1 colors.append(types[v.particle_type()]) for v in top_graph.get_vertices(): for vv in v: G.add_edge(v.particle_index, vv.get().particle_index) pos = nx.spring_layout(G) # positions for all nodes nx.draw_networkx_nodes(G, pos, node_size=700, node_color=colors, cmap=plt.cm.summer) nx.draw_networkx_edges(G, pos, width=3) nx.draw_networkx_labels(G, pos, font_size=20, labels=labels, font_family='sans-serif') plt.show()
def quickVisual(G, showLabel = False): """Just makes a simple _matplotlib_ figure and displays it, with each node coloured by its type. You can add labels with _showLabel_. This looks a bit nicer than the one provided my _networkx_'s defaults. # Parameters _showLabel_ : `optional [bool]` > Default `False`, if `True` labels will be added to the nodes giving their IDs. """ colours = "brcmykwg" f = plt.figure(1) ax = f.add_subplot(1,1,1) ndTypes = [] ndColours = [] layout = nx.spring_layout(G, k = 4 / math.sqrt(len(G.nodes()))) for nd in G.nodes(data = True): if 'type' in nd[1]: if nd[1]['type'] not in ndTypes: ndTypes.append(nd[1]['type']) ndColours.append(colours[ndTypes.index(nd[1]['type']) % len(colours)]) elif len(ndColours) > 1: raise RuntimeError("Some nodes do not have a type") if len(ndColours) < 1: nx.draw_networkx_nodes(G, pos = layout, node_color = colours[0], node_shape = '8', node_size = 100, ax = ax) else: nx.draw_networkx_nodes(G, pos = layout, node_color = ndColours, node_shape = '8', node_size = 100, ax = ax) nx.draw_networkx_edges(G, pos = layout, width = .7, ax = ax) if showLabel: nx.draw_networkx_labels(G, pos = layout, font_size = 8, ax = ax) plt.axis('off') f.set_facecolor('w')
def draw_fault_scenario(title, fault_edge, pp, dp, fwp): nx.draw(G, pos, node_size=300, font_size=10, node_color='w', alpha=1, with_labels=True) if title is not None: plt.text(0.5, 0.5, title, fontsize=12) if pp is not None: draw_edge_node(pp, 0.8, 'b') # Source nx.draw_networkx_nodes(G, pos, nodelist=[pp[0]], node_color='black', node_size=500, label='S', font_size=10, node_shape='s', alpha=0.5) # Detour path if dp is not None: draw_edge_node(dp, 0.8, 'g') # Fault edge if fault_edge is not None: nx.draw_networkx_edges(G, pos, edgelist=[fault_edge], width=4, alpha=0.8, edge_color='r') # FW Back path if fwp is not None: draw_edge_node(fwp, 0.8, 'y', 'dashed')
def draw_graph(graph2): plt.clf() nodes = set([n1 for n1, n2 in graph2] + [n2 for n1, n2 in graph2]) # Extract nodes from graph G = nx.Graph() # Graph - No Edges for node in nodes: #Nodes G.add_node(node) for edge in graph2: #Edges G.add_edge(edge[0], edge[1]) pos = nx.spring_layout(G) # Layout settings nx.draw_networkx_nodes(G,pos,node_size=1500, node_color='w', font_size=6) nx.draw_networkx_edges(G,pos,alpha=0.75,width=3) nx.draw_networkx_labels(G,pos, font_color='b') plt.title('Twitter Hashtag Graph') plt.axis('off') # Show graph plt.savefig(".\\images\\graph.png") # Calculate average degree average_degree = np.mean(nx.degree(G).values()) ft2 = open(sys.argv[2], 'a') # Write to ft2.txt if np.isnan(average_degree): # NaN for no hashtags ft2.write('0.00'+'\n') else: aver_deg = format(average_degree, '.2f') ft2.write(str(aver_deg)+'\n') ft2.close() return
def run(figures): network = dict() with open(figures+"TFs.txt") as F: for line in F: line = line.strip().split() TF = line[0] weights = line[1].split(',') network[TF] = weights[:-1] cut = 0.00000000000001 G = nx.Graph() for TF in network: for i in range(0, (int(len(network[TF])-5)), 6): if float(network[TF][i+1]) < cut and float(network[TF][i+2]) < cut and float(network[TF][i+3]) < cut and float(network[TF][i+4]) < cut: G.add_edge(TF,network[TF][i],weight=0.1) edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)] #elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.6] pos=nx.spring_layout(G) plt.figure() plt.subplot(111) plt.axis('off') nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos, edge_color=edgewidth) nx.draw_networkx_labels(G,pos,font_size=8,font_family='sans-serif') plt.savefig(figures+'network.png')
def draw_graph(self): import matplotlib.pyplot as plt elarge = [(u, v) for (u, v, d) in self._graph.edges(data=True) if d['type'] == 'audio_source'] esmall = [(u, v) for (u, v, d) in self._graph.edges(data=True) if d['type'] == 'data_source'] pos = nx.shell_layout(self._graph) # positions for all nodes # nodes nx.draw_networkx_nodes(self._graph, pos, node_size=700) # edges nx.draw_networkx_edges(self._graph, pos, edgelist=elarge, arrows=True) nx.draw_networkx_edges(self._graph, pos, edgelist=esmall, alpha=0.5, edge_color='b', style='dashed', arrows=True) # labels labels = {node: repr(self._graph.node[node]['processor']) for node in self._graph.nodes()} nx.draw_networkx_labels(self._graph, pos, labels, font_size=20, font_family='sans-serif') plt.axis('off') plt.show() # display
def drawEdges(self, alpha=0.2): """Draw a set of edges on the graph.""" nx.draw_networkx_edges(self.G, pos = nx.get_node_attributes(self.G, 'pos'), edgelist=self.G.edges(), arrows=False, alpha=0.2)
def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40): """Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net""" print "Generating graph..." try: with open(filename, 'r') as f: G = p.load(f) except: G = getgraph(username, password) with open(filename, 'w') as f: p.dump(G, f) #nx.draw(G) # Judge whether remove the isolated point from graph if remove_isolated is True: H = nx.empty_graph() for SG in nx.connected_component_subgraphs(G): if SG.number_of_nodes() > iso_level: H = nx.union(SG, H) G = H # Ajust graph for better presentation if different_size is True: L = nx.degree(G) G.dot_size = {} for k, v in L.items(): G.dot_size[k] = v node_size = [G.dot_size[v] * 10 for v in G] pos = nx.spring_layout(G, iterations=50) nx.draw_networkx_edges(G, pos, alpha=0.2) nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3) # Judge whether shows label if label_flag is True: nx.draw_networkx_labels(G, pos, alpha=0.5) #nx.draw_graphviz(G) plt.show() return G
def draw_graph(edges, up_words, down_words, node_size, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=2, text_font='sans-serif', file_name="graph"): plt.clf() g = nx.Graph() for edge in edges: g.add_edge(edge[0], edge[1]) graph_pos = nx.shell_layout(g) # layout for the network # up_words = map(lambda x: translate_node(x), up_words) # down_words = map(lambda x: x + "(" + translate_node(x) + ")", down_words) # add translated nodes to graph try: nx.draw_networkx_nodes(g, graph_pos, nodelist=up_words, node_size=node_size, alpha=node_alpha, node_color='red') nx.draw_networkx_nodes(g, graph_pos, nodelist=down_words, 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) except: print 'draw error' plt.savefig(result_path + file_name, format="PNG")
def plot(self, show_labels=False): nodes = nx.draw_networkx_nodes(self, self.pos, node_size=NODE_SIZE_NORMAL, node_color=NODE_COLOR_NORMAL, linewidths=NODE_LINEWIDTH_NORMAL, alpha=NODE_ALPHA_NORMAL) if nodes != None: nodes.set_edgecolor(NODE_BORDER_COLOR_NORMAL) ws = nx.get_node_attributes(self, 'w') sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE for v in self.photo_nodes()] nodes = nx.draw_networkx_nodes(self, self.pos, nodelist=self.photo_nodes(), node_shape=NODE_SHAPE_PHOTO, node_size=sizes, node_color=NODE_COLOR_PHOTO) if nodes != None: nodes.set_edgecolor(NODE_BORDER_COLOR_PHOTO) if show_labels: nx.draw_networkx_labels(self, self.pos, font_color=LABEL_COLOR_NORMAL, font_size=LABEL_FONT_SIZE_NORMAL) nx.draw_networkx_edges(self, self.pos, width=EDGE_WIDTH_NORMAL, edge_color=EDGE_COLOR_NORMAL, alpha=EDGE_ALPHA_NORMAL)
def graph_terms_to_topics(lda, num_terms=num_top): #topic names: select appropriate "t" based on number of topics #Use line below for num_top = 15. t = ['0','1', '2','3','4','5','6','7','8','9','10','11','12','13','14'] #Use line below for num_top = 25. #t = ['0','1', '2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24'] #Use line below for num_top = 35. #t = ['0','1', '2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34'] #Use line below for num_top = 45. #t = ['0','1', '2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44'] #Create a network graph and size it. G = nx.Graph() plt.figure(figsize=(16,16)) # generate the edges for i in range(0, lda.num_topics): topicLabel = t[i] terms = [term for term, val in lda.show_topic(i, num_terms+1)] for term in terms: G.add_edge(topicLabel, term, edge_color='red') pos = nx.spring_layout(G) # positions for all nodes #Plot topic labels and terms labels separately to have different colours g = G.subgraph([topic for topic, _ in pos.items() if topic in t]) nx.draw_networkx_labels(g, pos, font_size=20, font_color='r') #If network graph is difficult to read, don't plot ngrams titles. #g = G.subgraph([term for term, _ in pos.items() if str(term) not in t]) #nx.draw_networkx_labels(g, pos, font_size=12, font_color='orange') #Plot edges nx.draw_networkx_edges(G, pos, edgelist=G.edges(), alpha=0.3) #Having trouble saving graph to file automatically; below code not working. Must manually save. plt.axis('off') plt.show(block=False) plt.savefig('/Users/Marcia/OneDrive/UNCC General/DSBA_6880/Misc_Analysis_Files/TopicNetwork'+num+'.png', bbox_inches='tight')
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 draw_comm_detection_res(graph): pos = graphviz_layout(graph) color_list = ['r', 'g', 'b', 'y'] comm_dict, partition = get_comm_dict_and_partition() # nodes for comm_id in comm_dict: nx.draw_networkx_nodes(graph, pos, nodelist=comm_dict[comm_id], node_color=color_list[comm_id], node_size=500, alpha=0.8) nx.draw_networkx_nodes(graph, pos, nodelist=[9, 11], node_color='w', node_size=500, alpha=0.8) nx.draw_networkx_nodes(graph, pos, nodelist=[31], node_color='y', node_size=500, alpha=0.8) nx.draw_networkx_nodes(graph, pos, nodelist=[0], node_color='magenta', node_size=500, alpha=0.8) nx.draw_networkx_edges(graph, pos, width=4.0, alpha=0.5, edge_color='grey') # labels nx.draw_networkx_labels(graph, pos, font_size=16) plt.axis('off') plt.savefig('./clique_percolation_karate_partition.pdf', bbox_inches='tight', pad_inches=0, transparent=True) plt.savefig('./clique_percolation_karate_partition.png', bbox_inches='tight', pad_inches=0, transparent=True) plt.show()
def hidden_image_maze(fname, style='jittery'): """ Supported styles: jittery, smooth, sketch""" H = models.image_grid_graph(fname) # get a subgraph of the grid corresponding to edges between black pixels G = H.base_graph # for every edge in H, make the corresponding edge in H have weight 0 for u,v in H.edges(): G[u][v]['weight'] = 0 # find a minimum spanning tree on G (which will include the maze solution) T = nx.minimum_spanning_tree(G) # find the maze solution in the spanning tree P = models.my_path_graph(nx.shortest_path(T, (0,0), max(H.nodes()))) # generate the dual graph, including edges not crossed by the spanning tree D = models.dual_grid(G, T) views.add_maze_boundary(D, max(G.nodes())) views.make_entry_and_exit(D, max(G.nodes())) pos = views.layout_maze(D, fast=(style == 'jittery')) views.plot_maze(D, pos, P, G.pos) # make it stylish if requested if style == 'sketch': plt.figure(1) D_pos = views.layout_maze(D, fast=True) nx.draw_networkx_edges(D, D_pos, width=1, edge_color='k') D_pos = views.layout_maze(D, fast=True) nx.draw_networkx_edges(D, D_pos, width=1, edge_color='k') # show the pixel colors loaded from the file, for "debugging" plt.figure(2) for v in G: plt.plot([G.pos[v][0]], [G.pos[v][1]], '.', alpha=.5, color=G.node[v]['color'])
def plot_path(self, path): if path == None: edgelist = [] else: edgelist = zip(path[:-1], path[1:]) if edgelist == []: return nodes = nx.draw_networkx_nodes(self, self.pos, nodelist=path, node_size=NODE_SIZE_PATH, node_color=NODE_COLOR_PATH) if nodes != None: nodes.set_edgecolor(NODE_BORDER_COLOR_PATH) ws = nx.get_node_attributes(self, 'w') photo_path_nodes = self.photo_nodes(path) if photo_path_nodes != []: sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE for v in photo_path_nodes] nodes = nx.draw_networkx_nodes(self, self.pos, nodelist=photo_path_nodes, node_shape=NODE_SHAPE_PHOTO, node_size=sizes, node_color=NODE_COLOR_PHOTO_PATH) if nodes != None: nodes.set_edgecolor(NODE_BORDER_COLOR_PATH) nx.draw_networkx_edges(self, self.pos, edgelist=edgelist, width=EDGE_WIDTH_PATH, edge_color=EDGE_COLOR_PATH)
def exampleDistance(self, data, genEmb, explained_var, M, p_from=2, p_to=10, imgs=None, features=None, feature_names=None): G, weights = self.calcDistance(data, genEmb, explained_var, M) n = M.shape[2] # see path with images #pos = nx.spring_layout(G,weight='euc_dist') #p_to = 100 #p_from = 10 p_to = 20 pp_sets = [] pp_sets.append([2, 20]) pp_sets.append([5, 30]) pp_sets.append([10, 30]) pp_sets.append([10, 60]) pp_sets.append([30, 80]) for p_from, p_to in pp_sets: print 'CURRENT: p_from,p_to=', p_from, p_to save_fname = lambda x, ext: 'res_geometry/%d_%d_%s.%s' % ( p_from, p_to, x, ext) plt.figure(2).clf() plt.figure(3).clf() plt.figure(4).clf() plt.figure(1) plt.clf() pos = dict(zip(range(n), genEmb[:, :2])) # 2D for display nx.draw(G, pos, node_color='k', width=0.3, node_size=2) # draw path in red colors = ['r', 'b'] styles = ['solid', 'dashed'] use_imgs = imgs is not None if use_imgs: path_imgs = [] path_feats = [] for i in colors: path_imgs.append([]) path_feats.append([]) paths = [] for w, c, s in zip(weights, colors, styles): path = nx.shortest_path(G, source=p_from, target=p_to, weight=w) paths.append(path) path_edges = zip(path, path[1:]) nx.draw_networkx_nodes(G, pos, nodelist=path, node_color=c, width=1.2, node_size=8, style=s) nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color=c, width=1.2, node_size=8, style=s) plt.axis('equal') #plt.title('int dist=r, euc_dist=b') plt.savefig(save_fname('graph', 'pdf')) plt.rcParams['axes.labelsize'] = 'xx-large' plt.rcParams['ytick.labelsize'] = 'xx-large' plt.rcParams['xtick.labelsize'] = 'xx-large' plt.rcParams['lines.linewidth'] = 4 plt.rcParams['lines.markersize'] = 15 if use_imgs: tot_feats = 3 prev_stacked = None for i, (path, w) in enumerate(zip(paths, weights)): path_im = imgs[path] feats = features[path] emb = genEmb[path, :] #print emb stacked_im = np.hstack(path_im) stacked_im[:, ::path_im[0].shape[1]] = 255.0 if prev_stacked is None: prev_stacked = stacked_im elif prev_stacked.shape[1] - stacked_im.shape[1] > 0: stacked_im = np.pad( stacked_im, ((0, 0), (0, prev_stacked.shape[1] - stacked_im.shape[1])), mode='constant', constant_values=(0., 0.)) imsave(save_fname('imgs_%s' % w, 'png'), stacked_im) feats = np.array(feats) plt.figure(2) plt.subplot(len(weights), 1, i + 1) plt.imshow(stacked_im, cmap=plt.cm.gray) plt.title(w[:3]) plt.figure(3) for sel, feat in enumerate(feature_names[:tot_feats]): plt.subplot(tot_feats, 1, sel + 1) feats_inc = features[paths[0]] feats_euc = features[paths[1]] plt.plot(feats_inc[:, sel], 'r.-') plt.plot(feats_euc[:, sel], 'b.--') plt.title(feat) # save plt.figure(10) plt.plot(feats_inc[:, sel], 'r.-') plt.plot(feats_euc[:, sel], 'b.--') plt.savefig(save_fname('feats_%s' % feat, 'pdf')) plt.tight_layout() plt.close(10) plt.figure(4) for sel in range(tot_feats): plt.subplot(tot_feats, 1, sel + 1) emb_int = genEmb[paths[0], :] emb_euc = genEmb[paths[1], :] plt.plot(emb_int[:, sel], 'r.-') plt.plot(emb_euc[:, sel], 'b.--') plt.title('PC %d (explained var: %1.2f)' % (sel, explained_var[sel])) # save plt.figure(10) plt.plot(emb_int[:, sel], 'r.-') plt.plot(emb_euc[:, sel], 'b.--') plt.savefig(save_fname('pcs_%d' % sel, 'pdf')) plt.tight_layout() plt.close(10) with open(save_fname('expvar', 'txt'), 'w') as f: f.write(str(explained_var)) plt.show()
import numpy as np import pylab as plt # map cell to cell, add circular cell to goal point points_list = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), (2, 3), (2, 7)] goal = 7 import networkx as nx G = nx.Graph() G.add_edges_from(points_list) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) plt.show() # how many points in graph? x points MATRIX_SIZE = 8 # create matrix x*y R = np.matrix(np.ones(shape=(MATRIX_SIZE, MATRIX_SIZE))) R *= -1 # assign zeros to paths and 100 to goal-reaching point for point in points_list: print(point) if point[1] == goal: R[point] = 100 else: R[point] = 0
def visualize_graph(im, graph, show_graph=False, save_graph=True, \ num_nodes_each_type=None, custom_node_color=None, \ tp_edges=None, fn_edges=None, fp_edges=None, \ save_path='graph.png'): plt.figure(figsize=VIS_FIG_SIZE) if im.dtype == np.bool: bg = im.astype(int) * 255 else: bg = im if len(bg.shape) == 2: plt.imshow(bg, cmap='gray', vmin=0, vmax=255) elif len(bg.shape) == 3: plt.imshow(bg) #plt.imshow(bg, cmap='gray', vmin=0, vmax=255) plt.axis('off') pos = {} node_list = list(graph.nodes) for i in node_list: pos[i] = [graph.nodes[i]['x'], graph.nodes[i]['y']] if custom_node_color is not None: node_color = custom_node_color else: if num_nodes_each_type is None: node_color = 'b' else: if not (graph.number_of_nodes() == np.sum(num_nodes_each_type)): raise ValueError('Wrong number of nodes') node_color = [VIS_NODE_COLOR[0]] * num_nodes_each_type[0] + [ VIS_NODE_COLOR[1] ] * num_nodes_each_type[1] nx.draw(graph, pos, node_color='green', edge_color='blue', width=1, node_size=10, alpha=VIS_ALPHA) #nx.draw(graph, pos, node_color='darkgreen', edge_color='black', width=3, node_size=30, alpha=VIS_ALPHA) #nx.draw(graph, pos, node_color=node_color, node_size=VIS_NODE_SIZE, alpha=VIS_ALPHA) if tp_edges is not None: nx.draw_networkx_edges(graph, pos, edgelist=tp_edges, width=3, alpha=VIS_ALPHA, edge_color=VIS_EDGE_COLOR[0]) if fn_edges is not None: nx.draw_networkx_edges(graph, pos, edgelist=fn_edges, width=3, alpha=VIS_ALPHA, edge_color=VIS_EDGE_COLOR[1]) if fp_edges is not None: nx.draw_networkx_edges(graph, pos, edgelist=fp_edges, width=3, alpha=VIS_ALPHA, edge_color=VIS_EDGE_COLOR[2]) if save_graph: plt.savefig(save_path, bbox_inches='tight', pad_inches=0) if show_graph: plt.show() plt.cla() plt.clf() plt.close()
edges = [(0, 1), (0, 2), (1, 2), (3, 2), (3, 0)] edges_values = [] nodes = [0, 1, 2, 3] equation = [] for n in nodes: eqn = [] for e in edges: if e[0] == n: eqn.append(-1.0) if e[1] == n: eqn.append(1.0) if e[0] != n and e[1] != n: eqn.append(0.0) eqn.append(cars_out[n] + cars_in[n] * (-1)) equation.append(eqn) print(equation) print(gauss_jordan(equation)) print(equation) G = nx.DiGraph() G.add_edges_from(edges) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, node_size=500) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, edgelist=edges, edge_color='r', arrows=True) plt.show()
'CRT': (400, 100), 'ST': (1800, 250), 'FST': (-1400, 400), 'PS': (2500, 400), 'RTH': (1000, 200), 'FP': (2000, 200) } node_sizes = [1000 + 10 * i for i in range(len(graph))] M = graph.number_of_edges() edge_alphas = [(5 + i) / (M + 4) for i in range(M)] nodes = nx.draw_networkx_nodes(graph, pos, nodelist=nodelist, node_size=node_sizes, node_color="red", label='true') edges = nx.draw_networkx_edges(graph, pos, node_size=node_sizes, arrowstyle='->', arrowsize=15, edge_color="blue", edge_cmap=plt.cm.Blues, width=2) labels = nx.draw_networkx_labels(graph, pos) ax = plt.gca() ax.set_axis_off() plt.show()
if isinstance(fac, Source): outdf.at[0, fac.energyType] = model.facilities[fac].value elif isinstance(fac, Transformer): outdf.at[0, fac.name + 'Production'] = model.facilities[fac].value for con in fac.outcons: outdf.at[0, fac.name + '-' + con.energyType] = model.connections[con].value else: outdf.at[0, fac.name + 'Usage'] = model.facilities[fac].value outdf.to_excel('output.xlsx', sheet_name='Sheet1') plt.figure(figsize = (15,9)) plt.axis('off') for con in ConnList: if model.connections[con].value > 0.000001: G.add_edge(con.inp, con.out) nx.draw_networkx_edges(G, pos = posits, edgelist = [(con.inp, con.out)], width = model.connections[con].value/60) else: G.add_edge(con.inp, con.out) nx.draw_networkx_labels(G, pos = labelpos) for node in G.nodes(): nx.draw_networkx_nodes(G, pos = posits, nodelist = [node], node_color = G.node[node]['color'], node_shape = G.node[node]['shape']) plt.show() plt.figure(figsize = (9, 5)) nx.draw(G, pos = posits, with_labels = True, node_shape = 's') checkModel(ConnList, EnergyList)
def main(argv): graf = nx.DiGraph() size = len(argv) if size >= 1: imput_file = argv[0] else: print('imput_file necessario') return i = open(imput_file) csv_imput = csv.DictReader(i) for row in csv_imput: p1 = row['person1'] p2 = row['person2'] peso = int(row['weight']) conecao = int(row['conection']) graf.add_edge(p1, p2, weight=peso, conection=conecao) print(nx.info(graf)) #medidas de centralidade print('\n\tmedidas de centralidade') #centralidade do grau (o número de conecções de um grau para todos os outros) print('Grau de centralidade') print(nx.degree_centrality(graf)) print('\n') #eigenvector centrality (o quão importante é um nodo em função de quão bem conectado está) print('Eigenvector centrality') print(nx.eigenvector_centrality(graf)) print('\n') #closeness centralidade (importância de um nodo em função da sua proximidade com os outros da rede) print('Closeness centrality') print(nx.closeness_centrality(graf)) print('\n') #betweeness centralidade (quantifica quantas vezes um nodo aparece nos caminhos mais curtos entre dois nodos) print('Betweeness centrality') print(nx.betweenness_centrality(graf)) print('Average clustering') print(nx.average_clustering(graf)) print('\n\n') elarge = [(u, v) for (u, v, d) in graf.edges(data=True) if d['weight'] >= 3] esmall = [(u, v) for (u, v, d) in graf.edges(data=True) if d['weight'] < 3] forte = [(u, v) for (u, v, d) in graf.edges(data=True) if d['conection'] == 1] fraca = [(u, v) for (u, v, d) in graf.edges(data=True) if d['conection'] == 3] pos = nx.circular_layout(graf) # posições para todos os nodos # nodos nx.draw_networkx_nodes(graf, pos, node_size=70) # arestas nx.draw_networkx_edges(graf, pos, edgelist=elarge, width=0.5) nx.draw_networkx_edges(graf, pos, edgelist=esmall, width=0.5, alpha=0.5, edge_color='b', style='dashed') nx.draw_networkx_edges(graf, pos, edgelist=forte, width=0.5, alpha=0.5, edge_color='r', style='dotted') nx.draw_networkx_edges(graf, pos, edgelist=fraca, width=0.5, alpha=0.5, edge_color='#FFFFCC', style='dotted') # labels nx.draw_networkx_labels(graf, pos, font_size=6, font_family='sans-serif') plt.axis('off') plt.show()
f.close() print("Generating graph...") # Generate graph edge_list = [] for key in imports_dict: for ims in imports_dict[key]: edge_list.append((key.strip("/"), ims.strip("/"))) red_nodes = [] other_nodes = [] for key in all_packages: if "cmd" in key and key not in red_nodes: red_nodes.append(key) elif key not in other_nodes: other_nodes.append(key) graph = nx.DiGraph() # Directional graph graph.add_edges_from(edge_list) pos = nx.kamada_kawai_layout(graph) nx.draw_networkx_nodes(graph, pos, nodelist=other_nodes) nx.draw_networkx_nodes(graph, pos, nodelist=red_nodes, node_color="r") nx.draw_networkx_labels(graph, pos) nx.draw_networkx_edges(graph, pos, edgelist=graph.edges(), arrows=True, arrowstyle="-|>") if OUTPUT_FILE is None: plt.show() else: print(f"Saving to {OUTPUT_FILE}...") plt.savefig(OUTPUT_FILE)
def save_graph(self, Graph, path, testCase, test, config_parameters, cost, cost_cities, cost_ps, show): figure, axes = plt.subplots() cities = {} electricity = {} edges_electricity = {} edges_cities = {} keysC = set() keysE = set() for node in Graph.nodes(): if node >= 0: cities.update( {node: (Graph.node[node]['x'], Graph.node[node]['y'])}) else: electricity.update( {node: (Graph.node[node]['x'], Graph.node[node]['y'])}) for edge in Graph.edges(): if edge[0] < 0 or edge[1] < 0: # edges_electricity.update({edge: ((Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), # (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']))}) edges_electricity.update({ (Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']): (Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']): (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']) }) keysE.add( ((Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']))) else: # edges_cities.update({edge[0]: ((Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), # (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']))}) edges_cities.update({ (Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']): (Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']): (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']) }) keysC.add( ((Graph.node[edge[0]]['x'], Graph.node[edge[0]]['y']), (Graph.node[edge[1]]['x'], Graph.node[edge[1]]['y']))) nx.draw_networkx_nodes(Graph, cities, cities.keys(), node_color='red', node_size=150, label='Miasto', ax=axes) nx.draw_networkx_nodes(Graph, electricity, electricity.keys(), node_color='blue', node_size=150, node_shape='h', label='\nElektrownia\n', ax=axes) # nx.draw_networkx_edges(Graph, edges_cities, edge_color="black" ) nx.draw_networkx_edges(Graph, edges_cities, keysC, label="Rail network cost:" + str(format(cost_cities, '.7f')) + '\nK: ' + config_parameters[0], ax=axes) nx.draw_networkx_edges(Graph, edges_electricity, keysE, edge_color="red", label="Power grid cost:" + str(format(cost_ps, '.7f')) + '\nKe: ' + config_parameters[1], ax=axes) empty = {(0, 0): (0, 0)} nx.draw_networkx_nodes(Graph, empty, empty.keys(), node_color='white', node_size=0, label='\n\nCAPEX: ' + str(format(cost, '.7f')) + '\nPopulation: ' + str(config_parameters[2]) + '\nSelection: ' + str(config_parameters[3]) + '\nIterations: ' + str(config_parameters[4]), ax=axes) # nx.draw_networkx(Graph) handles, labels = axes.get_legend_handles_labels() legend = axes.legend(handles, labels, loc='upper center', ncol=3, bbox_to_anchor=(0.5, -0.1)) # legend.get_frame().set_alpha(0.5) plt.gca().set_aspect('equal', adjustable='box') plt.title("Najlepsze uzyskane rozwiązanie") if show: plt_copy = plt plt_copy.show() # plt.imsave(path+ folder_out+"/"+ testCase + "_" + test + '_bestIm.png', format='png') plt.savefig(path + "/" + testCase + "_" + test + '_theBest.png', bbox_extra_artists=(legend, ), bbox_inches='tight', format='png') plt.close(figure)
displays graph """ nx.draw_networkx(self.graph,with_labels=False,node_size=10,node_color='blue',edge_color='green',alpha=) plt.show() def stats(self): print(nx.info(self.graph)) print(f'Transitivity: \t{nx.transitivity(self.graph)}') print(f'Density: \t{nx.density(self.graph)}') widths=np.exp(weights) widths[0]=20 fig = plt.figure(figsize=(25, 15)) plt.axis('off') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw_networkx_nodes(G, pos, nodelist=G.nodes(), node_color='r', node_size=750) nx.draw_networkx_edges(G, pos, edgelist=G.edges(), alpha=0.5, edge_color='#5cce40', width=widths) nx.draw_networkx_labels(G, pos, font_size=16, font_color='white') fig.set_facecolor("#262626") plt.savefig('results/graph2.png') plt.show()
def draw_org_dependencies(self): """ Draws Orgs dependencies using the specified config :param uuid: The UUID of the config to be used. If not specified, the most recent config will be used :return: True if draw is successful, False otherwise """ def parse_org(org, current_list, G): if hasattr(org, "orgs"): if org.orgs is not None: for suborg in org.orgs: current_list.append({suborg.name: []}) parse_org(suborg, current_list[-1][suborg.name], G) G.add_edge(org._dn, suborg._dn) if self.config is None: # We could not find any config self.logger(level="error", message="Could not find any config to use for drawing service profile dependencies!") return False # Draw plot G = nx.Graph() # Save the Figure as fig for later use (save it and use it later) fig = plt.figure(figsize=(25, 10)) # Starting dict of orgs orgs_dict = {"root": []} G.add_node("org-root") # Searching for all orgs for org in self.config.orgs: parse_org(org, orgs_dict["root"], G) # Get position for shattered view (not used) # pos = self.hierarchy_pos(G, root="org-root", width=2 * math.pi, xcenter=0) # pos = {u: (r * math.cos(theta), r * math.sin(theta)) for u, (theta, r) in pos.items()} # Get position for top-down view (if less than 10 org (excluding root) are present) if len(G._node) < 11: pos = self.hierarchy_pos(G, root="org-root") mode_pos = "hierarchy_pos" # Get position for kamada_kawai_layout view else: pos = nx.kamada_kawai_layout(G) mode_pos = "kamada_kawai_layout" # Draw nodes, edges and labels nx.draw_networkx_nodes(G, pos, node_shape="v", node_size=1000) # Put a red color for the root Org nx.draw_networkx_nodes(G, pos, node_color="red", node_shape="v", node_size=1000, nodelist=["org-root"] ) nx.draw_networkx_edges(G, pos) labels_dict = {} # Raise text positions to be above the shape of the node for p in pos: temp_pos = list(pos[p]) if mode_pos == "hierarchy_pos": temp_pos[1] += 0.02 elif mode_pos == "kamada_kawai_layout": temp_pos[1] += 0.08 pos[p] = tuple(temp_pos) del temp_pos labels_dict[p] = p.replace("org-", "").split("/")[-1] nx.draw_networkx_labels(G, pos, labels=labels_dict) title = "Orgs" plt.title(title) self.org_plot = fig
def show_corr_nx(H): # creates a list of the edges of G and their corresponding weights edges, weights = zip(*nx.get_edge_attributes(H, "weight").items()) # draw the network with the Kamada-Kawai path-length cost-function pos = nx.kamada_kawai_layout(H) # figure size plt.figure(figsize=(20, 20)) # computes the degree (number of connections) of each node deg = H.degree # list of node names nodelist = [] # list of node sizes node_sizes = [] # iterates over deg and appends the node names and degrees for n, d in deg: nodelist.append(n) node_sizes.append(d) # draw nodes nx.draw_networkx_nodes( H, pos, node_color="#DA70D6", nodelist=nodelist, node_size=np.power(node_sizes, 2.5), alpha=0.8, font_weight="bold", ) # node label styles nx.draw_networkx_labels(H, pos, font_size=8, font_family="sans-serif") # color map cmap = sns.cubehelix_palette(3, as_cmap=True, reverse=True) # draw edges nx.draw_networkx_edges( H, pos, edge_list=edges, style="solid", edge_color=weights, edge_cmap=cmap, edge_vmin=min(weights), edge_vmax=max(weights), ) # builds a colorbar sm = plt.cm.ScalarMappable( cmap=cmap, norm=plt.Normalize(vmin=min(weights), vmax=max(weights)) ) sm._A = [] plt.colorbar(sm) # displays network without axes plt.axis("off") # plt.savefig('dija_correlation_network.jpg') plt.show()
def plot_combine(result_dir, chi): plt.rc('xtick', labelsize=40) plt.rc('ytick', labelsize=40) plt.rc('legend', fontsize=40) plt.rc('lines', lw=5, markersize=15) font_title = { 'family': 'Verdana', 'style': 'normal', 'weight': 'normal', 'size': 60, } fig, ax = plt.subplots(nrows=1, ncols=4, figsize=(55, 13)) plt.subplots_adjust(wspace=0.05) ax = ax.flatten() graph_pool = ['lattice', 'rrg', 'sw', 'complete'] annotate = ['(a)', '(b)', '(c)', '(d)'] Jij_pool = ['ones', 'randn', 'randn', 'sk'] n = [256, 80, 70, 20] for i in range(4): if i == 0: beta = np.arange(0.1, 1.1, 0.1) L = 16 node = 'mps' if os.path.exists( 'results/squarelatticeL16/kacward{}.txt'.format(L)): exact = np.loadtxt( 'results/squarelatticeL16/kacward{}.txt'.format(L)) # fe_tn = np.loadtxt('{}n256chi{}{}.txt'.format(result_dir, chi, node)) fe_tn_np = np.loadtxt( 'results/squarelatticeL16/n256chi{}{}_np.txt'.format( chi, node)) free_energy = np.loadtxt('results/squarelatticeL16/results.txt') fe_MF = np.loadtxt('results/squarelatticeL16/MFn{}.txt'.format( L**2)) # left, bottom, width, height = 0.12, 0.12, 0.8, 0.8 """ ax1 = fig.add_axes([left, bottom, width, height]) ax1.set_xlim((0.301, 1.02)) ax1.set_ylim((-2.2, -1.85)) ax1.set_yticks(np.arange(-2.2, -1.9, 0.1)) ax1.tick_params(labelsize=15) ax1.set_xlabel(r'$\beta$', fontsize=22) ax1.set_ylabel('Free Energy', fontsize=22) ax1.plot(betas[33:], exact[33:], c='k') ax1.scatter(beta[3:], free_energy[1][3:], facecolors='none', edgecolors='y', marker='o') ax1.scatter(beta[3:], free_energy[3][3:], c='b', marker="x") ax1.scatter(beta[3:], free_energy[2][3:], c='tab:orange', marker="d") ax1.scatter(beta[3:], free_energy[0][3:], c='tab:cyan', marker='*') ax1.scatter(beta[3:], fe_tn[0][3:], c='r') ax1.legend(['Exact', 'Bethe', 'Dense', 'Conv', 'FVS', 'TN'], loc=2, ncol=1, fontsize=15, frameon=False) """ # plt.axes([0.55, 0.2, 0.35, 0.45]) # plt.axes([left, bottom, width, height]) ax[0].axvline(0.4406868, color='k', linestyle='--', label='_nolegend_') """ plt.scatter(beta, np.log10(np.abs(np.array(fe_tn[0]) - exact[0:100:11])), c='r') plt.scatter(beta, np.log10(np.abs(np.array(free_energy[1]) - exact[0:100:11])), facecolors='none', edgecolors='y', marker="o") plt.scatter(beta, np.log10(np.abs(np.array(free_energy[2]) - exact[0:100:11])), c='tab:orange', marker="d") plt.scatter(beta, np.log10(np.abs(np.array(free_energy[3]) - exact[0:100:11])), c='b', marker="x") plt.scatter(beta, np.log10(np.abs(np.array(free_energy[0]) - exact[0:100:11])), c='tab:cyan', marker='*') """ # plt.plot(beta, np.log10(np.abs(np.array(fe_tn[0]) - exact)), c='r', marker='<', mfc='none') # plt.plot(beta, np.log10(np.abs(np.array(fe_tn[2]) - exact)), c='r', marker='>', mfc='none') # plt.plot(beta, np.log10(np.abs(np.array(fe_tn[4]) - exact)), c='r', marker='^', mfc='none') # plt.plot(beta, np.log10(np.abs(np.array(fe_tn[6]) - exact)), c='r', marker='v', mfc='none') ''' ax[0].plot(beta, np.log10(np.abs(np.array(fe_tn_np[0]) - exact)), c='r', marker='<', mfc='none', label='Dmax: 1') ax[0].plot(beta, np.log10(np.abs(np.array(fe_tn_np[2]) - exact)), c='r', marker='>', mfc='none', label='Dmax: 10') ax[0].plot(beta, np.log10(np.abs(np.array(fe_tn_np[4]) - exact)), c='r', marker='^', mfc='none', label='Dmax: 20') ''' lines = ax[0].plot(beta, np.log10(np.abs(np.array(fe_tn_np[6]) - exact)), c='r', marker='v', mfc='none', label='Our method') lines += ax[0].plot(beta, np.log10( np.abs(np.array(free_energy[2]) - exact)), c='c', marker="*", label='Conv VAN') # Conv lines += ax[0].plot(beta, np.log10( np.abs(np.array(free_energy[3]) - exact)), c='k', marker='*', label='VAN') # Dense # plt.plot(beta, np.log10(np.abs(np.array(free_energy[0]) - exact[0:100:11])), # c='tab:cyan', marker='*') # FVS lines += ax[0].plot(beta, np.log10( np.abs(np.array(free_energy[1]) - exact)), c='y', mfc='none', mec='y', marker="o", label='Bethe') # Bethe lines += ax[0].plot(beta, np.log10(np.abs(fe_MF[1] - exact)), c='g', marker="d", label='TAP') # TAP lines += ax[0].plot(beta, np.log10(np.abs(fe_MF[2] - exact)), c='b', marker='x', label='NMF') # NMF lines.reverse() ax[0].set_ylim((-18, 0)) ax[0].set_yticks([-1, -4, -7, -10, -13, -16]) ax[0].set_yticklabels([ '$10^{-1}$', '$10^{-4}$', '$10^{-7}$', '$10^{-10}$', '$10^{-13}$', '$10^{-16}$' ], fontsize=40) ax[0].set_xticks(beta[0:10:2]) # ax[0].set_xticklabels(ax[0].get_xticks(), fontsize=40) ax[0].set_ylabel('Relative Error', fontsize=45) ax[0].set_xlabel(r'$\beta$', fontsize=45) # ax[0].set_title(annotate[0], fontsize=50) ax[0].text(0.5, -0.2, annotate[0], fontdict=font_title, transform=ax[0].transAxes, ha="center") ax0 = ax[0].inset_axes([0.5, 0.275, 0.4, 0.4]) L = 5 grid = nx.grid_2d_graph(L, L) pos = list(grid.nodes) pos_grid = {}.fromkeys(np.arange(len(pos))) for i in pos_grid.keys(): pos_grid[i] = pos[i] edges_2d = list(grid.edges) edges = [(i[0] * L + i[1], j[0] * L + j[1]) for i, j in edges_2d] graph = nx.Graph() graph.add_nodes_from(np.arange(len(pos))) graph.add_edges_from(edges) nodes = nx.draw_networkx_nodes(graph, pos_grid, ax=ax0) nodes.set_color('white') nodes.set_edgecolor('k') nx.draw_networkx_edges(graph, pos_grid, ax=ax0, width=3) ax0.set_axis_off() # ax[0].legend(loc='center left', ncol=2, fontsize=20, frameon=False) else: D = 16 beta = np.arange(0.1, 2.1, 0.1) results = np.loadtxt('{}{}_{}_Dmax=50_chi={}_Jij={}.txt'.format( result_dir, graph_pool[i], n[i], chi, Jij_pool[i])) exact = results[:, 1] tn = np.log10(abs(results[:, 2]).reshape(-1, 10) + 1e-20) results_van = np.loadtxt('{}{}_{}_Jij={}_van.txt'.format( result_dir, graph_pool[i], n[i], Jij_pool[i])) nmf = np.log10(abs(results[:, 4]).reshape(-1, 10)) tap = np.log10(abs(results[:, 6]).reshape(-1, 10)) bp = np.log10(abs(results[:, 8]).reshape(-1, 10)) van = np.log10(abs(results_van[:, 1] - exact).reshape(-1, 10)) ax[i].plot(beta, nmf.mean(axis=1), c='b', marker='x', label='NMF') ax[i].plot(beta, tap.mean(axis=1), c='g', marker="d", label='TAP') ax[i].plot(beta, bp.mean(axis=1), c='y', mfc='none', mec='y', marker="o", label='Bethe') ax[i].plot(beta, van.mean(axis=1), c='k', marker='*', label='VAN') ax[i].plot(beta, tn.mean(axis=1), c='r', marker='v', mfc='none', label='TN') ''' Dmax_list = [1, 10, 20, 50] marker_list = ['<', '>', '^', 'v'] for Dmax in Dmax_list: results = np.loadtxt('{}{}_{}_Dmax={}_chi={}_Jij={}.txt'.format( result_dir, graph_pool[i], n[i], Dmax, chi, Jij_pool[i])) exact = results[:, 1] tn = np.log10(abs(results[:, 2]).reshape(-1, 10) + 1e-20) if Dmax == 1: results_van = np.loadtxt('{}{}_{}_Jij={}_van.txt'.format( result_dir, graph_pool[i], n[i], Jij_pool[i])) nmf = np.log10(abs(results[:, 4]).reshape(-1, 10)) tap = np.log10(abs(results[:, 6]).reshape(-1, 10)) bp = np.log10(abs(results[:, 8]).reshape(-1, 10)) van = np.log10(abs(results_van[:, 1] - exact).reshape(-1, 10)) ax[i].plot(beta, nmf.mean(axis=1), c='b', marker='x', label='NMF') ax[i].plot(beta, tap.mean(axis=1), c='tab:orange', marker="d", label='TAP') ax[i].plot(beta, bp.mean(axis=1), c='y', mfc='none', mec='y', marker="o", label='Bethe') ax[i].plot(beta, van.mean(axis=1), c='k', marker='*', label='VAN') ax[i].plot(beta, tn.mean(axis=1), c='r', marker=marker_list[Dmax_list.index(Dmax)], mfc='none', label='Dmax: {}'.format(Dmax)) """ plt.errorbar(beta, nmf.mean(axis=1), yerr=nmf.std(axis=1), c='b', fmt='-x', capsize=7, ms=3, linewidth=2, label='NMF') plt.errorbar(beta, tap.mean(axis=1), yerr=tap.std(axis=1), c='tab:orange', fmt='-d', capsize=7, ms=3, linewidth=2, label='TAP') plt.errorbar(beta, bp.mean(axis=1), yerr=bp.std(axis=1), c='y', fmt='-o', capsize=7, ms=3, linewidth=2, label='BP') plt.errorbar(beta, van.mean(axis=1), yerr=van.std(axis=1), c='k', fmt='-*', capsize=7, ms=3, linewidth=2, label='VAN') plt.errorbar(beta, tn.mean(axis=1), yerr=tn.std(axis=1), c='r', fmt='-{}'.format(marker_list[Dmax_list.index(Dmax)]), capsize=7, ms=3, linewidth=2, label='Dmax: {}'.format(Dmax)) """ ''' ax[i].set_ylim((-18, 0)) ax[i].set_yticks([-1, -4, -7, -10, -13, -16]) ax[i].set_yticklabels([], fontsize=40) # ax[i].set_yticklabels(['$10^{-1}$', '$10^{-4}$', '$10^{-7}$', '$10^{-10}$', '$10^{-13}$', '$10^{-16}$'], # fontsize=40) ax[i].set_xticks(beta[0:-1:4]) # ax[i].set_xticklabels(ax[i].get_xticks(), fontsize=40) # ax[i].set_ylabel('Relative Error', fontsize=22) ax[i].set_xlabel(r'$\beta$', fontsize=45) ax[i].text(0.5, -0.2, annotate[i], fontdict=font_title, transform=ax[i].transAxes, ha="center") # ax[i].set_title(annotate[i], fontsize=50) graph_ax = ax[i].inset_axes([0.5, 0.275, 0.45, 0.45]) graph_ax.set_axis_off() if i == 1: rrg = nx.random_regular_graph(3, D, seed=2) pos = nx.circular_layout(rrg) nodes = nx.draw_networkx_nodes(rrg, pos, ax=graph_ax) nodes.set_color('white') nodes.set_edgecolor('k') nx.draw_networkx_edges(rrg, pos, ax=graph_ax, width=3) elif i == 2: sw = nx.watts_strogatz_graph(D, 4, 0.4, seed=1) pos = nx.circular_layout(sw) nodes = nx.draw_networkx_nodes(sw, pos, ax=graph_ax) nodes.set_color('white') nodes.set_edgecolor('k') nx.draw_networkx_edges(sw, pos, ax=graph_ax, width=3) else: sk = nx.complete_graph(D) pos = nx.circular_layout(sk) nodes = nx.draw_networkx_nodes(sk, pos, ax=graph_ax) nodes.set_color('white') nodes.set_edgecolor('k') nx.draw_networkx_edges(sk, pos, ax=graph_ax) labels = [ 'Our method', 'Conv VAN', 'VAN', 'Bethe', 'TAP', 'NMF' ] labels.reverse() ax[i].legend(lines, labels, loc='center left', bbox_to_anchor=(0, 0.44), ncol=1, fontsize=40, frameon=False) plt.savefig('fig/relative_errorv2.eps', bbox_inches='tight', dpi=300)
def show_graph(nfl): """ Displays a plot of the game graph. :param nfl: The NFL graph :return: Void """ import statistics import warnings warnings.filterwarnings("ignore") sns.set(style="ticks") # Add the inverse of the weight as an edge at weights = nx.get_edge_attributes(nfl, 'weight') inverse_weights = dict() for edge in weights.items(): inverse_weight = 1 / edge[1] inverse_weights[edge[0]] = inverse_weight nx.set_edge_attributes(nfl, inverse_weights, 'Inverse Weight') # Calculate the average inverse weight average_inverse_weight = statistics.mean(list(inverse_weights.values())) # Format and title the graph fig, ax = plt.subplots(figsize=(20, 10)) ax.set_title('League Graph') ax.set_facecolor('#FAFAFA') # Set the layout of the graph to a force directed layout pos = nx.spring_layout(nfl, k=10 / average_inverse_weight, iterations=10000, weight='Inverse Weight', scale=3.0) # Get the Pagerank of each node ranks = nx.pagerank_numpy(nfl) nx.set_node_attributes(nfl, ranks, 'Pagerank') # Draw the nodes in the graph nx.draw_networkx_nodes( nfl, pos, node_color=list(nx.get_node_attributes(nfl, 'Primary').values()), node_size=[ 10000 * rank for rank in nx.get_node_attributes(nfl, 'Pagerank').values() ]) # Draw the edges in the graph nx.draw_networkx_edges(nfl, pos, width=1, alpha=0.1, edge_color='black', arrowsize=20) # Draw the team names nodes = nx.get_node_attributes(nfl, 'Secondary') for node_name, secondary_color in nodes.items(): nx.draw_networkx_labels(nfl, pos, labels={node_name: node_name}, font_size=10, font_color=secondary_color, font_family='sans-serif') # Save the figure plt.savefig( '..\\Projects\\nfl\\NFL_Prediction\\2019Ratings\\LeagueGraph.png', dpi=300) # Show the graph plt.show()
def drawMip(self, file_path, user_focus, objects_focus1, objects_focus2, neighbours=True): """ saves an image of the *sub-graph* composed from a selected user and a group of objects. :param file_path: where to save the graph :param user_focus: the user which the DOI is in relation to :param objects_focus1: objects in this list will be highlighted in the graph :param objects_focus2: objects in this list will be added to the graph :param neighbours: weather to add the neighbours of the user_focus in the Mip-graph to the subgraph. """ userNcolor = 'b' userNshape = '^' focususerNshape = 's' objNshape = 'o' nodeLsize = 6 objNcmap = plt.cm.get_cmap("autumn") user_node = self._addUser(user_focus) object_nodes = [self._addObject(x) for x in objects_focus1] nodes = object_nodes + [user_node] if neighbours: nodes.extend(self.mip.neighbors(user_node)) nodes.extend(self._addObject(x) for x in objects_focus2) subgraph = self.mip.subgraph(nodes) fig = plt.figure(clear=True, frameon=False) plt.axis('off') layout = nx.shell_layout(subgraph) # pick graph layout objects = [] users = [] objNcolor = [] # will be computed as color map from DOI objNline = [] lables = {} for n in subgraph.nodes(): if subgraph.nodes[n]['node_type'] == 'user': lables[n] = self.nodeIDsToUsersIds[n] if n is not user_node: users.append(n) else: objects.append(n) lables[n] = self.nodeIDsToObjectsIds[n] objNcolor.append(self.DegreeOfInterestMIPs(user_focus, n)) objNline.append(3.0 if n in object_nodes else 1.0) nx.draw_networkx_nodes(subgraph, pos=layout, nodelist=[user_node], edgecolors='black', node_color=userNcolor, node_shape=focususerNshape, label='focus_user_node') nx.draw_networkx_nodes(subgraph, pos=layout, nodelist=users, edgecolors='black', node_color=userNcolor, node_shape=userNshape, label='user_node') nx.draw_networkx_nodes(subgraph, pos=layout, nodelist=objects, node_color=objNcolor, node_shape=objNshape, cmap=objNcmap, linewidths=objNline, edgecolors='black', label='object_node') nx.draw_networkx_labels(subgraph, pos=layout, labels=lables, font_size=nodeLsize) edges = {(edge[0], edge[1]): edge[2]['weight'] for edge in subgraph.edges(data=True) if edge[2]['weight'] > 0} nx.draw_networkx_edges(subgraph, pos=layout, label='edge_weight', edgelist=edges.keys()) nx.draw_networkx_edge_labels(subgraph, pos=layout, edge_labels=edges) plt.legend() plt.title(str(self)) plt.suptitle(f"graph before commit {self.iteration+1}", fontsize=14, fontweight='bold') plt.savefig(file_path) plt.close(fig)
def draw_service_profile_dependencies(self): """ Draws Service Profile dependencies using the specified config :return: True if draw is successful, False otherwise """ def parse_org(org, service_profile_list): if org.service_profiles is not None: for service_profile in org.service_profiles: if not service_profile.service_profile_template: service_profile_list.append(service_profile) if hasattr(org, "orgs"): if org.orgs is not None: for suborg in org.orgs: parse_org(suborg, service_profile_list) if self.config is None: # We could not find any config self.logger(level="error", message="Could not find any config to use for drawing service profile dependencies!") return False service_profile_list = [] # Searching for all Service Profiles (template or not) that are not from a template in all orgs for org in self.config.orgs: parse_org(org, service_profile_list) # Parsing all service profiles and draw plot for service_profile in service_profile_list: G = nx.Graph() sp_options_dict = self.get_service_profile_plot_options() if not sp_options_dict: self.logger(level="error", message="Service Profile options for plot not imported.") continue # Save the Figure as fig for later use (save it and use it later) fig = plt.figure(figsize=(25, 10)) plt.xlim(-0.25, 0.25) plt.ylim(-0.235, 0.235) # Create a dict to change the label's name and options (color, size) afterward # ex. node: (new_label_name, node_options) labels_dict = {} # Get the config object through the "config_object_name" string info in the service_profile_plot_options config_object = eval(sp_options_dict["service_profile"]["config_object_name"]) if "template" in service_profile.type: self.node_service_profile = config_object._CONFIG_NAME + " Template\n" + service_profile.name else: self.node_service_profile = config_object._CONFIG_NAME + "\n" + service_profile.name self.node_service_profile_options = sp_options_dict["service_profile"] self.node_service_profile_options["label"] = self.node_service_profile for sp_node, sp_node_options in sp_options_dict.items(): if sp_node != "service_profile": # if value of service_profile.*policy_name* != None if eval('service_profile.' + sp_node): # get the config object through the "config_object_name" string info in # the service_profile_plot_options config_object = eval(sp_node_options["config_object_name"]) # get the label name of a node (a specific policy). ex. "Boot Policy\ndefault" node_label_name = config_object._CONFIG_NAME + "\n" + eval('service_profile.' + sp_node) setattr(self, "node_" + sp_node, node_label_name) sp_options_dict[sp_node]["label"] = getattr(self, "node_" + sp_node) setattr(self, "node_" + sp_node + "_options", sp_options_dict[sp_node]) # Add a plot edge (link between two nodes) G.add_edge(self.node_service_profile, sp_options_dict[sp_node]["label"]) else: # Set the self.node_*policy* to None if the value is None in the Service Profile setattr(self, "node_" + sp_node, None) # Get position for shattered view pos = self.hierarchy_pos(G, root=self.node_service_profile, width=2 * math.pi, xcenter=0) pos = {u: (r * math.cos(theta), r * math.sin(theta)) for u, (theta, r) in pos.items()} # Get position for top-down view (not used) # pos = self.hierarchy_pos(G, root=self.node_service_profile) # Setting options for each edge and node (a node is characterized only by a name (label)) for node in ["node_" + i for i in sp_options_dict]: # the list includes all of the policies supported node_label_name = getattr(self, node) if getattr(self, node) is None: continue node_options = getattr(self, node + "_options") # Set options for a node nx.draw_networkx_nodes(G, pos, node_color=node_options["color"], nodelist=[node_label_name], node_size=node_options["size"], node_shape=node_options["shape"] ) if node != "node_service_profile": # Set options for an edge nx.draw_networkx_edges(G, pos, edgelist=[ (self.node_service_profile, node_label_name)]) edge_labels = {(self.node_service_profile, node_label_name): " ".join( node_label_name.split("\n")[0:1])} nx.draw_networkx_edge_labels(G, pos, rotate=True, font_color='black', font_size=11, label_pos=0.5, edge_labels=edge_labels ) # Create a dict of label key associate with an alias to remove # the unique identifier ("\n" and *policy name*) # ex. 'Service Profile\nTest': 'Test' labels_dict[node_label_name] = (node_label_name.split("\n")[1], node_options) else: # Create a dict of label key associate with an alias to remove # To fit into the square of the SP, it need to be split each 9 character n = 9 line = node_label_name.split("\n")[1] line = "\n".join([line[i:i + n] for i in range(0, len(line), n)]) labels_dict[node_label_name] = (line, node_options) # Raise text positions to be above the shape of the node for p in pos: for key, policy in sp_options_dict.items(): if "label" in policy: if policy["label"] == p: if key != "service_profile": temp_pos = list(pos[p]) temp_pos[1] += 0.02 pos[p] = tuple(temp_pos) del temp_pos break # the nearest loop # Add the labels alias using the dict created before for node, (label_node_name, label_node_option) in labels_dict.items(): nx.draw_networkx_labels(G, pos, labels={node: label_node_name}, font_color=label_node_option["node_font_color"], font_weight=label_node_option["node_font_weight"] ) title = service_profile._parent._dn + "\n" + self.node_service_profile plt.title(title) self.service_profile_plots[service_profile] = fig
def draw_networkx( self, G=None, pos=None, arrows=True, with_labels=True, task_node_color="#00EE00", auto_task_node_color="#005500", **kwds, ): """ Draw networkx Args: G (networkx.Digraph, optional): The information of networkx graph. Defaults to None -> self.get_networkx_graph(). pos (networkx.layout, optional): Layout of networkx. Defaults to None -> networkx.spring_layout(G). arrows (bool, optional): Digraph or Graph(no arrows). Defaults to True. with_labels (bool, optional): Label is describing or not. Defaults to True. task_node_color (str, optional): Node color setting information. Defaults to "#00EE00". auto_task_node_color (str, optional): Node color setting information. Defaults to "#005500". **kwds: another networkx settings. Returns: figure: Figure for a network """ G = G if G is not None else self.get_networkx_graph() pos = pos if pos is not None else nx.spring_layout(G) # nx.draw_networkx(G, pos=pos, arrows=arrows, with_labels=with_labels, **kwds) # normal task normal_task_list = [ task for task in self.task_list if not task.auto_task ] nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=normal_task_list, node_color=task_node_color, # **kwds, ) # auto task auto_task_list = [task for task in self.task_list if task.auto_task] nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=auto_task_list, node_color=auto_task_node_color, # **kwds, ) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos)
def draw_network_quick(g, label_p=0.75, adjust_text=False, node_or_community_norm='neighbor', spatialization=nx.layout.kamada_kawai_layout, custom_key=False): '''Function for quick visualization of networkself. Choose the fraction of labels to be displayed, will be ordered by relative community degree or relative neighbor degree. Use the adjust_text to avoid label overlap. node_or_community_norm: choose between 'neighbor' or 'community' or 'degree' Input spatialization function e.g. nx.spring_layout or nx.kamada_kawai_layout''' import matplotlib.pyplot as plt if custom_key: sort = sorted(g, key=lambda x: g.nodes[x][key], reverse=True) else: if node_or_community_norm == 'neighbor': key = 'neighbor_relative_degree' try: sort = sorted(g, key=lambda x: g.nodes[x][key], reverse=True) except: print('will add neighbor relative degre') g = add_neighbor_relative_degree(g) sort = sorted(g, key=lambda x: g.nodes[x][key], reverse=True) elif node_or_community_norm == 'community': key = 'relative_degree' try: sort = sorted(g, key=lambda x: g.nodes[x][key], reverse=True) except: print('will add community info') g = add_community_relative_degree(g) sort = sorted(g, key=lambda x: g.nodes[x][key], reverse=True) else: print('Will order by degree') sort = sorted(g, key=lambda x: len(g[x]), reverse=True) top = sort[:int(len(g) * label_p)] try: community = [int(g.nodes[i]['community']) for i in g] except: g = add_community_relative_degree(g) community = [int(g.nodes[i]['community']) for i in g] colors = [plt.cm.tab20(i / max(community)) for i in community] pos = spatialization(g) fig = plt.figure(figsize=(40, 30)) nx.draw_networkx_nodes(g, pos=pos, node_color=colors) nx.draw_networkx_edges(g, pos=pos) labels = [] for i in top: labels.append(plt.text(pos[i][0], pos[i][1], i, fontweight='bold')) #labels = nx.draw_networkx_labels(nx.subgraph(g,top),pos=pos) if adjust_text: try: from adjustText import adjust_text except: print('adjustText not installed. pip install adjustText') try: print('Adjusting text. May take a while...') adjust_text(labels) except Exception as e: print(e) print('Error') return fig
L[int(stw[0])][int(stw[1])]["weight"] = int(stw[2]) # SOURCE, TARGET, RATING, TIME # print G.nodes pos = nx.spring_layout(G) # positions for all nodes edge_labels = dict([(( u, v, ), d['weight']) for u, v, d in G.edges(data=True)]) # nodes nx.draw_networkx_nodes(G, pos, node_size=700) # edges nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6) nx.draw_networkx_edges(G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color='b', style='dashed') # labels print "AAAAAAAAAAAAAAAAAAAAAAa" print G.degree() nx.draw_networkx_labels(G, pos,
for i in communities: # multiplying with 100 here to see nodes bigger if necesarry multiplier number can change sizes[i] = [d[s] * 100 for s in communities[i]] #drawing network for i in communities: nx.draw_networkx_nodes(g, pos=pos, nodelist=communities[i], node_size=sizes[i], node_color=colors[i], label=str(i), edgecolors=(0.0, 0.0, 0.0)) nx.draw_networkx_edges(g, pos=pos) nx.draw_networkx_labels(g, pos=pos) plt.legend() plt.title(label="Main Network") plt.show() #making subnetworks and drawing them with their degree distrubutions subgraphs = {} for i in range(len(communities)): subgraphs["sub_network" + str(i + 1)] = g.subgraph( communities["community" + str(i + 1)]) nx.draw(subgraphs["sub_network" + str(i + 1)], pos=pos, node_size=sizes["community" + str(i + 1)], node_color=colors["community" + str(i + 1)],
def drawNetwork(network, posNodes): nx.draw_networkx_nodes(network, posNodes, node_size=10, node_color='r') nx.draw_networkx_edges(network, posNodes) return
def buildGraph(self): self.publishers = [] self.subscribers = [] pubs_list = [] subs_list = [] font_size = 8 max = 1 y_offset = 0 new_nodetoplot = [] old_nodetoplot = [] good_chantoplot = [] old_chantoplot = [] edgestoplot = [] self.g.clear() size_of_node = 266.66666 self.g.add_node("Publishers", layer=0) self.g.add_node("Channels", layer=1, node_color="white") self.g.add_node("Subscribers", layer=2, node_color="white") self.g.add_edge("Publishers", "Channels") self.g.add_edge("Channels", "Subscribers") label_list = {} width = self.canvas.width height = self.canvas.height for chan in self.channels: self.g.add_node(str(chan), layer=1) for pubs in self.channels[chan]["publishers"]: ip_port = "IP:" + str(pubs[0]) + "\nPort:" + str(pubs[1]) self.g.add_node(str(ip_port), layer=0) self.g.add_edge(str(ip_port), str(chan)) edgestoplot.append([str(ip_port), str(chan)]) if pubs not in self.g: self.publishers.append(pubs) pubs_list.append(str(ip_port)) for subs in self.channels[chan]["subscribers"]: ip_port = "IP:" + str(subs[0]) + "\nPort:" + str(subs[1]) self.g.add_node(str(ip_port), layer=2) self.g.add_edge(str(chan), str(ip_port)) edgestoplot.append([str(chan), str(ip_port)]) if subs not in self.g: self.subscribers.append(subs) subs_list.append(str(ip_port)) if (len(self.channels) > 1): max = len(self.channels) if (len(self.subscribers) > max): max = len(self.subscribers) if (len(self.publishers) > max): max = len(self.publishers) plt.clf() pos = nx.multipartite_layout(self.g, subset_key="layer") nx.draw_networkx_nodes( self.g, pos, nodelist=["Publishers", "Channels", "Subscribers"], node_color="w") if ((1.0 / max) * height * .1) > 8: font_size = 8 else: font_size = ((1.0 / max) * height * .1) if max < 3: y_offset = ((1.0 / 4) / 2) else: y_offset = ((1.0 / max) / 2) for node in pos: x, y = pos[node] text = str(node) if (text != "Publishers" and text != "Channels" and text != "Subscribers"): if (text in pubs_list): plt.text(x, y + y_offset, text, horizontalalignment='right', fontsize=font_size) lookup = node.replace("IP:", "") lookup = lookup.replace("\nPort", "") if (self.parent.host.checkPub(lookup)): new_nodetoplot.append(str(node)) else: old_nodetoplot.append(str(node)) if (text in subs_list): plt.text(x, y + y_offset, text, horizontalalignment='left', fontsize=font_size) lookup = node.replace("IP:", "") lookup = lookup.replace("\nPort", "") if (self.parent.host.checkSub(lookup)): new_nodetoplot.append(str(node)) else: old_nodetoplot.append(str(node)) if (text in self.channels): plt.text(x, y + y_offset, text, horizontalalignment='center', fontsize=font_size) if (self.parent.host.checkChan(node)): good_chantoplot.append(str(node)) else: old_chantoplot.append(str(node)) else: if (max == 0): plt.text(x, 0.0, text, horizontalalignment='center', fontsize=8) elif (max == 1): plt.text(x, 0.4166666666666666666666, text, horizontalalignment='center', fontsize=8) elif (max == 2): plt.text(x, 0.7777777777777777777777, text, horizontalalignment='center', fontsize=8) else: plt.text(x, 1.0, text, horizontalalignment='center', fontsize=8) if (((1.0 / max) * height) < size_of_node): size_of_node = ((1.0 / max) * height) nx.draw_networkx_nodes(self.g, pos, nodelist=new_nodetoplot, node_size=size_of_node) nx.draw_networkx_nodes(self.g, pos, nodelist=old_nodetoplot, node_size=size_of_node, node_color="grey") nx.draw_networkx_nodes(self.g, pos, nodelist=good_chantoplot, node_size=size_of_node, node_shape='s') nx.draw_networkx_nodes(self.g, pos, nodelist=old_chantoplot, node_size=size_of_node, node_shape='s', node_color="grey") nx.draw_networkx_edges(self.g, pos, edgelist=edgestoplot, arrowstyle="-") plt.axis('off') plt.savefig('figure.png') image = Image.open('figure.png') img_width, img_height = image.size rel_width = img_width / width rel_height = img_height / height image = image.resize( (int((rel_width + .4) * width), int((rel_height + .4) * height)), Image.ANTIALIAS) ## The (250, 250) is (height, width) img = ImageTk.PhotoImage(image) self.parent.one = img self.canvas.create_image(width / 2, height / 2, anchor='center', image=img) image.close() os.remove('figure.png')
def run(self, node, bidir, output_file): 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 = self.get_node_to_ips().keys() if not node else [node] adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir, self.iter_publication) 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=(len(G.nodes()) * 2, len(G.nodes()) * 2)) 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) if node: edge_labels = dict([((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)
import community as community_louvain import matplotlib.cm as cm partition = community_louvain.best_partition(graph_all_weeks[11].graph) G = graph_all_weeks[11].graph pos = nx.spring_layout(G) # color the nodes according to their partition cmap = cm.get_cmap('viridis', max(partition.values()) + 1) nx.draw_networkx_nodes(G, pos, partition.keys(), node_size=40, cmap=cmap, node_color=list(partition.values())) nx.draw_networkx_edges(G, pos, alpha=0.5) plt.show() dendogram = community_louvain.generate_dendrogram(G) community_louvain.modularity(partition, G) for w in range(0, 12): G = graph_all_weeks[w].graph partition = community_louvain.best_partition(G) print( 'Week ' + str(w + 1) + ': ' + str(community_louvain.modularity(partition, G)), ' -- No of coms: ' + str(max(partition, key=partition.get))) partition.items[0]
np.square(nodelist.iloc[i]['top'] - nodelist.iloc[j]['top'])) temp = round(temp / 100, 2) temp_dict['distance'] = temp t = ((nodelist.iloc[i]['id'], nodelist.iloc[j]['id']), ) t += (temp_dict, ) dist_result1.append(t) plt.figure(figsize=(8, 6)) nx.draw(g, pos=node_positions, edge_color=edge_colors, node_size=1000, node_color='skyblue', alpha=0.8) graph_pos = nx.spring_layout(g, weight=3) nx.draw_networkx_edges(g, graph_pos, edge_color=edge_colors) nx.draw_networkx_labels(g, pos=node_positions, font_size=8) nx.draw_networkx_edge_labels(g, pos=node_positions, edge_labels=edge_type, font_size=6) #labels = [(e[2]['attr_dict']['Type_of_road'], e[2]['attr_dict']['color']) for e in g.edges(data=True)] plt.title('Zoo Map', size=20) line1, = plt.plot([1, 2, 3], label='Not for Disabled', color='red', linewidth=2) line2, = plt.plot([3, 2, 1], label='Accessible route – ADA', color='gray',
G.add_edge(i,last,{r:int(n)}) last=i i=i+1 g.append(G) return g,c if __name__ == "__main__": (g,city)=minard_graph() try: import matplotlib.pyplot as plt plt.figure(1,figsize=(11,5)) plt.clf() colors=['b','g','r'] for G in g: c=colors.pop(0) node_size=[int(G.pop[n]/300.0) for n in G] nx.draw_networkx_edges(G,G.pos,edge_color=c,width=4,alpha=0.5) nx.draw_networkx_nodes(G,G.pos,node_size=node_size,node_color=c,alpha=0.5) nx.draw_networkx_nodes(G,G.pos,node_size=5,node_color='k') for c in city: x,y=city[c] plt.text(x,y+0.1,c) plt.savefig("napoleon_russian_campaign.png") except ImportError: pass
G_netsci_attack = G_netsci.copy() print('Before node removal') print_netStats(G_netsci_attack) # for loop for node removal for iRemove in range(15): nodeOut = snode_netsci[iRemove] print('Removing node ', nodeOut) G_netsci_attack.remove_node(nodeOut) print_netStats(G_netsci_attack) # drawing the graph (karate network only) --- Kamada-Kawai layout plt.figure(figsize=[12, 6]) plt.subplot(131) pos = nx.kamada_kawai_layout(G_karate, weight=None) # positions for all nodes nx.draw_networkx_nodes(G_karate, pos) nx.draw_networkx_edges(G_karate, pos, edge_color='lightblue') nx.draw_networkx_labels(G_karate, pos, font_size=10, font_color='DarkGreen') plt.title('Original karate network') plt.axis('off') plt.xlim([-0.6, 0.65]) plt.ylim([-0.85, 1.2]) plt.subplot(132) nodeList = G_karate_randdel.nodes() edgeList = G_karate_randdel.edges() nx.draw_networkx_nodes(G_karate, pos, nodelist=nodeList) nx.draw_networkx_edges(G_karate, pos, edgelist=edgeList, edge_color='lightblue') plt.title('Random deletion, karate network')
def draw_graph(graph, embedding, labels, path, s=25): assert embedding.shape[1] == 2 edges = list(graph.edges()) if labels is not None: # filter out noise nodes labelled as -1 # idx, = np.where(labels[:,0] > -1) num_labels = int(max(set(labels[:, 0])) + 1) # colours = np.random.rand(num_labels, 3) colours = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [1, 1, 1]]) # colours = np.array(["r", "g", "b", "y", "m", "c"]) assert num_labels < len(colours) else: idx = np.arange(len(embedding)) colours = None if not isinstance(edges, np.ndarray): edges = np.array(edges) print("saving two-dimensional poincare plot to {}".format(path)) fig = plt.figure() title = "Two dimensional poincare plot" plt.suptitle(title) ax = fig.add_subplot(111) hyperbolic_setup(fig, ax) # a = embedding[edges[:,0]] # b = embedding[edges[:,1]] # c = get_third_point(a, b) # draw_geodesic(a, b, c, ax) # # s = {n: (bc+.05) * 100 for n, bc in nx.betweenness_centrality(graph).items()} # # s = [s[n] for n in sorted(graph.nodes)] # s = np.array([graph.degree(n, weight="weight") for n in sorted(graph.nodes())]) # s = s / s.max() * 100 # ax.scatter(embedding[idx,0], embedding[idx,1], # c=colours[labels[idx,0]] if labels is not None else None, # s=s, zorder=2) pos = {n: emb for n, emb in zip(sorted(graph.nodes()), embedding)} node_colours = np.array([colours[labels[n, 0]] for n in graph.nodes() ]) if colours is not None else None # bc = nx.betweenness_centrality(graph) # node_sizes = np.array([(bc[n] + .05) * 50 for n in sorted(graph.nodes())]) node_sizes = np.array( [graph.degree(n, weight="weight") for n in graph.nodes()]) node_sizes = node_sizes / node_sizes.max() * 250 nx.draw_networkx_nodes(graph, pos=pos, node_color=node_colours, node_size=node_sizes) nx.draw_networkx_edges(graph, pos=pos, width=.05, node_size=node_sizes) # nx.draw_networkx_edge_labels(graph, pos=pos, edge_labels=nx.get_edge_attributes(graph, name="weight")) plt.savefig(path) plt.close()
def update_graph(frame_number): try: global __end_node_index__ global __obj_data__ final_path = [] node_list = __obj_data__.graph_dt[frame_number] parent = node_list[0] current = node_list[1] no_of_neighbours = node_list[2] edge_list = [] childs = [] edge_labels = {} if no_of_neighbours > 0: childs.extend(node_list[3].split(" ")) for i in range(0, len(childs)): edge_list.append((current, childs[i])) edge_dist = \ __obj_data__.node_list[ __obj_data__.node_name_list.index(childs[i]) ].total_dist edge_labels.update({(current, childs[i]): round(edge_dist, 2)}) nx.draw_networkx_nodes(__animation_graph__.graph_viz, __animation_graph__.pos, nodelist=childs, node_size=100, node_color='red', alpha=0.8) if parent == "": parent = current nx.draw_networkx_edges(__animation_graph__.graph_viz, __animation_graph__.pos, edgelist=[(parent, current)], width=3, edge_color='blue', alpha=0.5) nx.draw_networkx_edges(__animation_graph__.graph_viz, __animation_graph__.pos, edgelist=edge_list, width=2, edge_color='red', alpha=0.5, style="dashed") nx.draw_networkx_edge_labels(__animation_graph__.graph_viz, __animation_graph__.pos, edge_labels=edge_labels, label_pos=0.5, font_size=5) if (len(__obj_data__.graph_dt) - 1) == frame_number: end_node = __obj_data__.node_list[__end_node_index__] while end_node.parent is not None: final_path.append( (__obj_data__.node_list[end_node.parent].name, end_node.name)) end_node = __obj_data__.node_list[end_node.parent] nx.draw_networkx_edges(__animation_graph__.graph_viz, __animation_graph__.pos, edgelist=final_path, width=5, edge_color='black', alpha=0.5) except Exception as e: raise Exception("Something went wrong. " + str(e))
def draw_networkx( self, G=None, pos=None, arrows=True, with_labels=True, view_workers=False, team_node_color="#0099FF", worker_node_color="#D9E5FF", view_facilities=False, factory_node_color="#0099FF", facility_node_color="#D9E5FF", **kwds, ): """ Draw networkx Args: G (networkx.Digraph, optional): The information of networkx graph. Defaults to None -> self.get_networkx_graph(). pos (networkx.layout, optional): Layout of networkx. Defaults to None -> networkx.spring_layout(G). arrows (bool, optional): Digraph or Graph(no arrows). Defaults to True. with_labels (bool, optional): Label is describing or not. Defaults to True. view_workers (bool, optional): Including workers in networkx graph or not. Default to False. team_node_color (str, optional): Node color setting information. Defaults to "#0099FF". worker_node_color (str, optional): Node color setting information. Defaults to "#D9E5FF". view_facilities (bool, optional): Including facilities in networkx graph or not. Default to False. factory_node_color (str, optional): Node color setting information. Defaults to "#0099FF". facility_node_color (str, optional): Node color setting information. Defaults to "#D9E5FF". **kwds: another networkx settings. Returns: figure: Figure for a network """ G = (G if G is not None else self.get_networkx_graph( view_workers=view_workers, view_facilities=view_facilities)) pos = pos if pos is not None else nx.spring_layout(G) # nx.draw_networkx(G, pos=pos, arrows=arrows, with_labels=with_labels, **kwds) # team nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=self.team_list, node_color=team_node_color, # **kwds, ) # resources if view_workers: worker_list = [] for team in self.team_list: worker_list.extend(team.worker_list) nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=worker_list, node_color=worker_node_color, # **kwds, ) # factory nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=self.factory_list, node_color=factory_node_color, # **kwds, ) # facility if view_facilities: facility_list = [] for factory in self.factory_list: facility_list.extend(factory.facility_list) nx.draw_networkx_nodes( G, pos, with_labels=with_labels, nodelist=facility_list, node_color=facility_node_color, # **kwds, ) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos)