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 save_graph(ruin, name="out.png"): G=nx.Graph() # Position the bottom node at 0 offsetY = 0; for room in ruin.rooms: if room.pos[1] < offsetY: offsetY = room.pos[1] offsetY = offsetY - 1 for room in ruin.rooms: G.add_node(room.full_name.title(), posxy=[room.pos[0], room.pos[1]-offsetY]) G.add_node("outside".title(), posxy=[0, -offsetY - 1]) for room in ruin.rooms: for key, val in room.connections.items(): if val is None: pass elif val == 'entrance': G.add_edge(room.full_name.title(), "outside".title()) else: connected_room = val[1] G.add_edge(room.full_name.title(), connected_room.full_name.title()) positions = nx.get_node_attributes(G,'posxy') pyplot.figure(1,figsize=(8,8)) pyplot.title("Map of " + ruin.name.title()) nx.draw(G, positions, node_size=2000, node_color=(0, .7, .8), edge_color='#00aaaa', width=4, linewidths=0.2, with_labels=False, transparent=True) for p in positions: # raise text positions v_offset = positions[p][0] % 4 positions[p][1] += [0.14, -0.07, .07, -0.14][v_offset] nx.draw_networkx_labels(G, positions, font_size=10) pyplot.savefig(md_writer.output_folder+"/images/" + name, transparent=True) # save as png pyplot.close() G.clear()
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 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 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 test_labels_and_colors(self): G = nx.cubical_graph() pos = nx.spring_layout(G) # positions for all nodes # nodes nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color='r', node_size=500, alpha=0.8) nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color='b', node_size=500, alpha=0.8) # edges nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) nx.draw_networkx_edges(G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)], width=8, alpha=0.5, edge_color='r') nx.draw_networkx_edges(G, pos, edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)], width=8, alpha=0.5, edge_color='b') # some math labels labels = {} labels[0] = r'$a$' labels[1] = r'$b$' labels[2] = r'$c$' labels[3] = r'$d$' labels[4] = r'$\alpha$' labels[5] = r'$\beta$' labels[6] = r'$\gamma$' labels[7] = r'$\delta$' nx.draw_networkx_labels(G, pos, labels, font_size=16) 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 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 drawGraph(space): """ Displays an edge and node graph to represent all of the planets in space and their possible paths Parameters: space: a graph of all planets(nodes) and paths (edges) (digraph) Returns: A figure """ pos = nx.spring_layout(space) nx.draw_networkx_nodes(space,pos) eone = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==1] etwo = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==2] ethree = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==3] efour = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==4] nx.draw_networkx_edges(space,pos,edgelist=eone,width=2,edge_color='green') nx.draw_networkx_edges(space,pos,edgelist=etwo,width=3,edge_color='blue') nx.draw_networkx_edges(space,pos,edgelist=ethree,width=4,edge_color='orange') nx.draw_networkx_edges(space,pos,edgelist=efour,width=5,edge_color='red') nx.draw_networkx_labels(space,pos) plt.axis("off") plt.show()
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 _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 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 plot_graph_3D(graph, I_shape, plot_terminal=True, plot_weights=True, font_size=7): w_h = I_shape[1] * I_shape[2] X, Y = np.mgrid[:I_shape[1], :I_shape[2]] aux = np.array([Y.ravel(), X[::-1].ravel()]).T positions = {i: aux[i] for i in xrange(w_h)} for i in xrange(1, I_shape[0]): for j in xrange(w_h): positions[w_h * i + j] = [positions[j][0] + 0.3 * i, positions[j][1] + 0.2 * i] positions['s'] = np.array([-1, int(I_shape[1] / 2)]) positions['t'] = np.array([I_shape[2] + 0.2 * I_shape[0], int(I_shape[1] / 2)]) nxg = graph.get_nx_graph() if not plot_terminal: nxg.remove_nodes_from(['s', 't']) nx.draw(nxg, pos=positions) nx.draw_networkx_labels(nxg, pos=positions) if plot_weights: edge_labels = dict([((u, v,), d['weight']) for u, v, d in nxg.edges(data=True)]) nx.draw_networkx_edge_labels(nxg, pos=positions, edge_labels=edge_labels, label_pos=0.3, font_size=font_size) plt.axis('equal') plt.show()
def draw(self, layout_type='spring_layout'): ''' Draw the graph layout_type = The type of layout algorithm (Default = 'spring_layout') ''' import matplotlib.pyplot as plt try: pos = getattr(nx, layout_type)(self.G) except: raise Exception('layout_type of %s is not valid' % layout_type) nx.draw_networkx_nodes(self.G,pos, nodelist=self.species, node_color=self.options['species']['color'], node_size=self.options['species']['size'], alpha=self.options['species']['alpha']) nx.draw_networkx_edges(self.G, pos, edgelist=self.product_edges) nx.draw_networkx_edges(self.G, pos, edgelist=self.reactant_edges, arrows=False) nx.draw_networkx_edges(self.G, pos, edgelist=self.modifier_edges, style='dashed') labels = {} for n in self.G.nodes(): if n in self.species: labels[n] = n nx.draw_networkx_labels(self.G,pos,labels,font_size=self.options['species']['label_size']) plt.axis('off') plt.show()
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 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 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_molecule(molecule): # Create a new NetworkX graph g = nx.Graph() # For each vertex and edge in molecule graph add node and edge in NetworkX graph for n in molecule.vertices(): g.add_node(molecule.position_of_vertex(n), element=n.label) for e in molecule.edges(): if e.single: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='single') elif e.double: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='double') elif e.triple: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='triple') elif e.quadruple: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='quadruple') elif e.aromatic: g.add_edge(molecule.endpoints_position(e)[0], molecule.endpoints_position(e)[1], type='aromatic') # Set the layout pos = nx.spring_layout(g, iterations=30) # Display the element type and edge type as labels labels = dict((n,d['element']) for n,d in g.nodes(data=True)) edge_labels = dict(((u,v),d['type']) for u,v,d in g.edges(data=True)) # Add the labels to the graph nx.draw(g, pos=pos, node_color='w') nx.draw_networkx_labels(g, pos=pos, labels=labels) nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=edge_labels) # Display the completed graph plt.show() return g
def 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 drawLabels(self, labelAll=True): """Draw labels on nodes in graph (nodeId by default)""" # circleNodes = [ n for (n, m) in self.G.nodes(data=True) if m.get('shape','circle') == 'circle'] # pdb.set_trace() if labelAll: nx.draw_networkx_labels(self.G, pos=nx.get_node_attributes(self.G, 'pos'), font_size=10, labels=self.labelMap) else: # boxNodes = [ n for (n, m) in self.G.nodes(data=True) if m.get('shape','circle') == 'box'] # lm = {} # for n in boxNodes: # lm[n]=self.labelMap[n] # nx.draw_networkx_labels(self.G, # pos=nx.get_node_attributes(self.G, 'pos'), # font_size=10, # labels=lm) emptyNodes = [ n for (n,m) in self.G.nodes(data=True) if m.get('shape','circle') == 'empty'] if emptyNodes: lm = {} for n in emptyNodes: lm[n]=self.labelMap[n] nx.draw_networkx_labels(self.G, pos=nx.get_node_attributes(self.G, 'pos'), font_size=10, labels=lm)
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_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_dg(dg): plt.figure() # pos = networkx.spring_layout(dg) pos = networkx.pygraphviz_layout(dg,'dot') networkx.draw_networkx_labels(dg,pos) networkx.draw(dg,pos,arrows=True) plt.show()
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 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, output=None, pos=None, legend=False, ax=None, colors=False): if pos is None: if self.pos is None: self.pos = self.layout() pos = self.pos nodes = list(pos.keys()) inputs = self.inputs() outputs = self.outputs() node_colors = [] node_pos = [] for node in nodes: node_pos.append(pos[node]) if colors: if node in inputs: node_colors.append(self.colors[2]) elif node in outputs: node_colors.append(self.colors[1]) else: node_colors.append(self.colors[0]) else: node_colors.append(self.colors[0]) node_pos = np.array(node_pos) if ax is None: ax = nx.draw(self.dag, pos, nodelist=nodes, node_color=node_colors) #, node_size=300) else: nx.draw(self.dag, pos, nodelist=nodes, node_color=node_colors, ax=ax) #, node_size=300) labels = {(node_i, node_j): label for node_i, node_j, label in self.dag.edges(data='label', default='')} nx.draw_networkx_labels(self.dag, pos, ax=ax) nx.draw_networkx_edge_labels(self.dag, pos, labels, ax=ax) if legend: node_types = ['Regular node', 'Input', 'Output'] node_colors = [self.colors[0], self.colors[2], self.colors[1]] patches = [ mpl.patches.Patch(color=node_colors[i], label=label) for i, label in enumerate(node_types) ] plt.legend(handles=patches, fontsize=10) plt.gcf().tight_layout() if output is None: plt.show() else: plt.savefig(output, dpi=300) plt.close()
def draw_G_fromalledges(alledges, bsites=2, nnodes_cycle=3, separate=True, figsize1=(10, 10), figsize2=(10, 20), coords_t=[(1.5, 4), (4, 1.5), (0, 0)], drawlabels=True): #figsize_transitions=(10,10) #this has to be tuned depending on the size of the graph G = nx.DiGraph() for edge in alledges: G.add_edge(edge[0], edge[2], lab=edge[1]) coords = dict() nnodes_b = 2**bsites #coords_t= yoffset = 1.5 #1.1 xoffset = 1.5 #1.1 #coords_b=[(2,2),(1,1),(3,1),(2,0)] #calculate the coordinates of the binding graph coords_b = [] nodes_per_level = [] for i in range(0, bsites + 1): nodes_per_level.append( int( math.factorial(bsites) / (math.factorial(bsites - i) * math.factorial(i)))) maxn = max(nodes_per_level) middle = maxn / 2 for i in range(bsites + 1): y = (bsites - i) if nodes_per_level[i] == 1: coords_b.append((middle, y)) else: offset = (maxn - nodes_per_level[i]) / 2 for x in np.linspace(0, nodes_per_level[i], nodes_per_level[i]): #print(i,":",nodes_per_level[i],x,y) coords_b.append((x + offset, y)) n = 1 for j in range(nnodes_cycle): t = coords_t[j] dx, dy = t for i in range(nnodes_b): coords[n] = (coords_b[i][0] + dx * xoffset, coords_b[i][1] + dy * yoffset) n += 1 colors_persite = [ '', 'darkolivegreen', 'lightgreen', 'navy', 'lightblue', 'red', 'orange', 'magenta', 'violet', 'saddlebrown', 'maroon' ] if bsites > 10: for i in range(bsites - len(colors_persite)): colors_persite.append('k') bcolors = [] tcolors = [] bedges = [] tedges = [] labsdict = {e: G[e[0]][e[1]]['lab'] for e in G.edges} labsdict_t = {k: v for k, v in labsdict.items() if v[0] == 'k'} labsdict_b = {k: v for k, v in labsdict.items() if v[0] != 'k'} for edge in G.edges: n0, n1 = edge bgroup0 = n0 % nnodes_b bgroup1 = n1 % nnodes_b #print(n0,n1,bgroup0,bgroup1) if bgroup0 != bgroup1: bcolors.append('b') bedges.append(edge) else: tcolors.append('r') tedges.append(edge) #print() #first plot a graph labelling the transitions fig, ax = plt.subplots(1, 1, figsize=figsize1) nx.draw_networkx_nodes(G, pos=coords, node_color='lightgray', ax=ax) nx.draw_networkx_labels(G, pos=coords, ax=ax) nx.draw_networkx_edges(G, pos=coords, edgelist=tedges, edge_color=tcolors, ax=ax, connectionstyle="arc3,rad=-0.1") if drawlabels: nx.draw_networkx_edge_labels(G, pos=coords, edge_labels=labsdict_t, alpha=1, rotate=True, label_pos=0.2, bbox={'alpha': 0}, font_color='r', ax=ax) if separate: nx.draw_networkx_edges(G, pos=coords, edgelist=bedges, edge_color=bcolors, connectionstyle="arc3,rad=0.1", ax=ax) if drawlabels: nx.draw_networkx_edge_labels(G, pos=coords, edge_labels=labsdict_t, alpha=1, rotate=True, label_pos=0.2, bbox={'alpha': 0}, font_color='r', ax=ax) plt.show() else: for i in range(2): if i == 0: #linestyle='solid' width = 2 #the linestyle doesn't work, so I am making binding edges wider than unbinding edges edgelist = [k for k, v in labsdict_b.items() if v[0] == 'a'] else: width = 1 edgelist = [k for k, v in labsdict_b.items() if v[0] == 'b'] ecolors = [] for e in edgelist: site = G[e[0]][e[1]]['lab'].split("_")[0][ 1:] #label is of form "asite_" color = colors_persite[int(site)] ecolors.append(color) nx.draw_networkx_edges(G, pos=coords, edgelist=edgelist, edge_color=ecolors, ax=ax, width=width, connectionstyle="arc3,rad=0.1") if drawlabels: nx.draw_networkx_edge_labels( G, pos=coords, edge_labels={ k: v for k, v in labsdict_b.items() if e in edgelist }, alpha=1, rotate=True, label_pos=0.7, bbox={'alpha': 0}, font_color='k', ax=ax) plt.show() if separate: #now plot the binding transitions fig, axes = plt.subplots(nnodes_cycle, 1, figsize=figsize2) for a, ax in enumerate(axes): nodes = [ node for node in G.nodes if ((node - 1) // (nnodes_b)) == a ] nx.draw_networkx_nodes(G, nodelist=nodes, pos=coords, node_color='lightgray', ax=ax) nx.draw_networkx_labels( G, labels={n: n for n in G.nodes if n in nodes}, pos=coords, ax=ax) for i in range(2): if i == 0: #linestyle='solid' width = 2 #the linestyle doesn't work, so I am making binding edges wider than unbinding edges edgelist = [ k for k, v in labsdict_b.items() if ((k[0] in nodes) and (k[1] in nodes) and v[0] == 'a' ) ] labelcolor = 'k' else: width = 1 edgelist = [ k for k, v in labsdict_b.items() if ((k[0] in nodes) and (k[1] in nodes) and v[0] == 'b' ) ] labelcolor = 'gray' ecolors = [] for e in edgelist: color = colors_persite[int(G[e[0]][e[1]]['lab'][1])] ecolors.append(color) nx.draw_networkx_edges(G, pos=coords, edgelist=edgelist, edge_color=ecolors, ax=ax, width=width, connectionstyle="arc3,rad=0.1") if drawlabels: nx.draw_networkx_edge_labels( G, pos=coords, edge_labels={ k: v for k, v in labsdict_b.items() if k in edgelist }, alpha=1, rotate=True, label_pos=0.7, bbox={'alpha': 0}, font_color=labelcolor, ax=ax) for ax in axes: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) plt.show() return
est_main_conns = sorted(est_main_conns.items(), key=operator.itemgetter(1), reverse=True)[:5] est_main_conns = tuple(map(operator.itemgetter(0), est_main_conns)) nx.draw_networkx_edges(G, pos, edgelist=est_main_conns, edge_color='red', alpha=0.9, width=6, style='dashed') nx.draw_networkx_labels(G, pos, labels={ 0: G.node[0]['club'], 33: G.node[33]['club'] }, font_size=15, font_color='white') candidate_edges = ((8, 15), (30, 21), (29, 28), (1, 6)) nx.draw_networkx_edges(G, pos, edgelist=candidate_edges, edge_color='blue', alpha=0.5, width=2, style='dashed') nx.draw_networkx_labels(G, pos, labels={u: u
import networkx as nx import numpy as np # 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 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 print(R) # 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
if args.show_se != "no": labels_ends = {} if args.node_type == "int": start = 0 end = 2**L-1 else: start = StateToString([0]*L) end = StateToString([1]*L) if args.show_se == "bracket": labels_ends[start] = "{}" else: labels_ends[start] = "no\nfeatures" labels_ends[end] = "all\nfeatures" if args.show_se != "bracket": nx.draw_networkx_labels(G, pos, labels_ends, font_size=args.labels_fontsize, font_color='black') else: if args.show_se.lower() != "none": nx.draw_networkx_labels(G, pos, labels_ends, font_size=args.labels_fontsize, font_color='white') labels = {} top_sizes = MakeTopSizesByOnes(G, node_sizes) if args.extra_labels != None: if args.labels != None: state_labels = [str(el) for el in list(pd.read_csv(args.labels, header=None, index_col = None).iloc[:,1])] else: state_labels = range(L) ns = [int(el) for el in (args.extra_labels).split(",")] lim = ns[-1] ns = ns[:-1] for i, n in enumerate(ns):
def plot_Graph(DAG, pos): G = nx.DiGraph(DAG) # Create default Graph nx.draw(G, pos=pos) nx.draw_networkx_labels(G, pos=pos) return
def plot_graph(cls, G, filename=None, node_attribute_name='id', edge_attribute_name=None, colored_nodes=None, colored_edges=None, colored_path=None, **kwargs): #def plot_graph(self, G, out_file, **kwd): """plot graph""" plt.clf() # get the layout of G pos = nx.get_node_attributes(G, 'pos') if not pos: pos = nx.spring_layout(G) # get node attributes with_labels = False node_labels = None if node_attribute_name == 'id': with_labels = True elif node_attribute_name: node_labels = nx.get_node_attributes(G, node_attribute_name) # get edge attributes if not edge_attribute_name: edge_labels = nx.get_edge_attributes(G, edge_attribute_name) # colored nodes node_default_color = '0.75' # Gray shades node_color = node_default_color if colored_nodes: node_color = [ 'r' if node in colored_nodes else node_default_color for node in G.nodes() ] # colored path if colored_path: nrof_nodes = len(colored_path) idx = 0 colored_edges = list() while idx < nrof_nodes - 1: colored_edges.append( (colored_path[idx], colored_path[idx + 1])) idx += 1 # colored edges edge_default_color = 'k' # black edge_color = edge_default_color if colored_edges: set_colored_edges = {frozenset(t) for t in colored_edges } # G.edges returns a list of 2-tuples edge_color = [ 'r' if frozenset([u, v]) in set_colored_edges else edge_default_color for u, v in G.edges() ] # draw nx.draw(G, pos, with_labels=with_labels, node_color=node_color, edge_color=edge_color, **kwargs) if node_labels: nx.draw_networkx_labels(G, pos, labels=node_labels) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) if filename: plt.savefig(filename, bbox_inches='tight', pad_inches=0) else: plt.show()
def paint(self, display_pipo=True, order=False): 'no mamupulation of nodes or edges in this func, just pict graph' if order: #------------------------------------ #需要改进 #获取最大的逻辑深度,以及X坐标方向的长度 max_depth = 0 for eachFD in self.fd_nodes: if self.fd_depth_dict[eachFD][1]: tmp2 = self.fd_depth_dict[eachFD][0] if tmp2 > max_depth: max_depth = tmp2 else: continue pos_dict = {} x_max = 2 + max_depth #计算每一个点的横纵坐标,横坐标为逻辑深度,纵坐标为在本一行当中的排序 cnt = [] for i in range(0, max_depth + 1): cnt.append(0) cnt[0] = len(self.pi_nodes) cnt[-1] = len(self.po_nodes) for eachPi in self.pi_nodes: pos_dict[eachPi] = (0, self.pi_nodes.index(eachPi)) for eachPo in self.po_nodes: pos_dict[eachPo] = (max_depth + 1, self.po_nodes.index(eachPo)) for i in range(1, max_depth + 1): for eachFD in self.fd_nodes: if self.fd_depth_dict[eachFD][1] == True: if self.fd_depth_dict[eachFD][0] == i: cnt[i] = cnt[i] + 1 pos_dict[eachFD] = (self.fd_depth_dict[eachFD][0], cnt[i]) else: pos_dict[eachFD] = (x_max, 0) y_max = max(cnt) ps = pos_dict else: ps = nx.spring_layout(self) #-------------------------------- #根据前面算出来的位置信息进行节点与边的绘制 #------------------------------- if display_pipo: nx.draw_networkx_nodes(self, pos=ps, nodelist=self.pi_nodes, node_color='r') nx.draw_networkx_nodes(self, pos=ps, nodelist=self.po_nodes, node_color='b') nx.draw_networkx_nodes(self, pos=ps, nodelist=self.fd_nodes, node_color='g') nx.draw_networkx_edges(self, ps) label_dict = {} label_pos = {} if display_pipo: for eachVertex in self.pi_nodes + self.po_nodes: label_dict[ eachVertex] = eachVertex.port_type + "\n" + eachVertex.port_name label_pos[eachVertex] = (pos_dict[eachVertex][0] + 0.2, pos_dict[eachVertex][1]) for eachVertex in self.fd_nodes: label_dict[ eachVertex] = eachVertex.cellref + "\n" + eachVertex.name if order: label_pos[eachVertex] = (pos_dict[eachVertex][0] + 0.2, pos_dict[eachVertex][1]) self.label_dict = label_dict if order: nx.draw_networkx_labels(self, pos=label_pos, labels=label_dict, font_color='m') else: nx.draw_networkx_labels(self, pos=ps, labels=label_dict, font_color='m') ##--------------------------------------------------------------------- ##保存绘图到当前路径下的 tmp/文件夹 pic_dir = os.getcwd() + "//tmp//" pic_full_name = pic_dir + self.name + "_s_graph.png" plt.savefig(pic_full_name)
ax.bar(range(frequencies.size), frequencies, 0.5, color='k') ax.set_xticklabels(keywords,rotation=45,fontsize=ticksFontSizeSmall) ax.set_ylim(0,max(frequencies)+1) box=ax.get_position() ax.set_position([box.x0, box.y0+box.height*0.3, box.width, box.height*0.7]) fig.show() " Dirgraph showing clusters of keywords, no citations as size, and citations as arrows. " poses=networkx.graphviz_layout(G) # Plot the network of which article cites which and what keywords they have. fig, ax = matplotlib.pyplot.subplots(1,figsize=(12,8)) matplotlib.pyplot.grid(linewidth=2) ax.tick_params(axis='both',reset=False,which='both',length=5,width=1.5) matplotlib.pyplot.subplots_adjust(left=0.1, right=1, top=0.95, bottom=0.1) nodePatches=networkx.draw_networkx_nodes(G, poses, cmap=matplotlib.pyplot.get_cmap('jet'), node_color=cluster_labels, node_size=noCitations, ax=ax) networkx.draw_networkx_edges(G, poses, edge_color='k', arrows=True, ax=ax) # Draw keywords of every Article. networkx.draw_networkx_labels(G, poses, dict(zip(range(len(allArticles)),[keywords[articleFeatures[i,:]] for i in range(len(allArticles))])), font_size=graphLabelFontSize, ax=ax) # Add a colourbar nodePatches.set_clim(0,max(cluster_labels)) cbar=fig.colorbar(nodePatches,ticks=numpy.arange(0,max(cluster_labels)+1,2),pad=0.01) cbarBox=cbar.ax.get_position() cbar.ax.set_position([cbarBox.x0, cbarBox.y0+cbarBox.height * 0.12, cbarBox.width*1., cbarBox.height * 0.75]) cbar.ax.set_ylabel(r'$Cluster\ ID$', size=labelsFontSize) cbar.set_clim(0,max(cluster_labels)) fig.show()
nx.draw_networkx_nodes(G, pos, nodelist=persons[0:8], node_color='r', node_size=2000, alpha=0.6) # nx.draw_networkx_nodes(G, pos, # nodelist=persons[7:8], # node_color='y', # node_size=2000, # alpha=0.6) # nx.draw_networkx_nodes(G, pos, # nodelist=persons[4:7], # node_color='b', # node_size=2000, # alpha=0.6) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) test= nx.draw_networkx_edge_labels(G,pos=nx.circular_layout(G), edge_labels=bc) ### example edges: # nx.draw_networkx_edges(G, pos, # edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)], # width=8, alpha=0.5, edge_color='b') nx.draw_networkx_labels(G, pos, font_size=14) plt.axis('off') plt.subplots_adjust(bottom=0.03, top=0.97) plt.savefig('filename.png', dpi=300)
def draw_graph(self, nodes=None): others = self.others graph = self.graph color_map = [] atom_type2 = [] esingle = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] == 1] etriple = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] == 3] edouble = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] == 2] earom = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] == 1.5] pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=500) # nx.draw_networkx_nodes(graph, pos, node_size=250, nodelist=nodes, node_color='g') if nodes == None: nodes = graph.nodes() else: for node in range(len(nodes)): # print(node, nodes[node].type) if nodes[node].type == 'O': nx.draw_networkx_nodes(graph, pos, node_size=500, nodelist=others, node_color='r') elif nodes[node].type == 'Cl': nx.draw_networkx_nodes(graph, pos, node_size=500, nodelist=others, node_color='y') elif nodes[node].type == 'F': nx.draw_networkx_nodes(graph, pos, node_size=500, nodelist=others, node_color='g') elif nodes[node].type == 'N': nx.draw_networkx_nodes(graph, pos, node_size=500, nodelist=others, node_color='b') nx.draw_networkx_edges(graph, pos, edgelist=etriple, width=12, alpha=0.5, edge_color='b', node_color=color_map) nx.draw_networkx_edges(graph, pos, edgelist=edouble, width=12, alpha=0.5, edge_color='g', node_color=color_map) nx.draw_networkx_edges(graph, pos, edgelist=esingle, width=10, node_color=color_map) nx.draw_networkx_edges(graph, pos, edgelist=earom, width=12, alpha=0.5, edge_color='r', node_color=color_map) # nx.draw_networkx_edges(graph, pos, edgelist=var, width=3, style='dashed') nx.draw_networkx_labels(graph, pos, font_size=20, font_family='sans-serif', node_color=color_map) plt.axis('off') plt.show()
def draw(ft, draw_type): if draw_type == "DATACENTER": G = nx.Graph() pos = {} labels = {} G = ft i_for_power = 0.0 i_for_router = 0.0 i_for_dc = 0.0 i_for_piece = 0.0 i_for_app = 0.0 nodeListDC = [] nodeListRouter = [] nodeListPiece = [] nodeListPower = [] nodeListApp = [] for node in G: if G.node[node].keys()[0] == 'POWERSTATION': nodeListPower.append(node) pos[node] = (5 + i_for_power, 0.2) labels[node] = r'R' i_for_power += 30 if G.node[node].keys()[0] == 'INTERNET': nodeListRouter.append(node) pos[node] = (10 + i_for_router, 0.4) labels[node] = r'Agg' i_for_router += 20 if G.node[node].keys()[0] == 'DATACENTER': nodeListDC.append(node) pos[node] = (13 + i_for_dc, 0.6) labels[node] = r'RA' i_for_dc += 14 if G.node[node].keys()[0] == 'PIECE': nodeListPiece.append(node) pos[node] = (13 + i_for_piece, 0.8) labels[node] = r'P' i_for_piece += 14 if G.node[node].keys()[0] == 'JOB': nodeListApp.append(node) pos[node] = (20 + i_for_app, 1.0) labels[node] = r'JOB' i_for_app += 30 nx.draw_networkx_nodes(G, pos, nodelist = nodeListPower,\ node_color = 'yellow', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListRouter,\ node_color = 'orange', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListDC,\ node_color = 'green', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListPiece,\ node_color = 'green', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListApp,\ node_color = 'yellow', node_size = 400) nx.draw_networkx_edges(G, pos, width=1.0, alpha=1.0) nx.draw_networkx_labels(G, pos, labels, font_size=12) elif draw_type == "RACK": G = nx.Graph() pos = {} labels = {} G = ft i_for_rack = 0.0 i_for_router = 0.0 i_for_agg = 0.0 i_for_piece = 0.0 i_for_app = 0.0 nodeListRack = [] nodeListRouter = [] nodeListPiece = [] nodeListAgg = [] nodeListApp = [] for node in G: if G.node[node].keys()[0] == 'ROUTER': nodeListRouter.append(node) pos[node] = (5 + i_for_router, 0.2) labels[node] = r'R' i_for_router += 30 if G.node[node].keys()[0] == 'AGGSWITCH': nodeListAgg.append(node) pos[node] = (10 + i_for_agg, 0.4) labels[node] = r'Agg' i_for_agg += 20 if G.node[node].keys()[0] == 'RACK': nodeListRack.append(node) pos[node] = (13 + i_for_rack, 0.6) labels[node] = r'RA' i_for_rack += 14 if G.node[node].keys()[0] == 'PIECE': nodeListPiece.append(node) pos[node] = (13 + i_for_piece, 0.8) labels[node] = r'P' i_for_piece += 14 if G.node[node].keys()[0] == 'JOB': nodeListApp.append(node) pos[node] = (20 + i_for_app, 1.0) labels[node] = r'JOB' i_for_app += 30 nx.draw_networkx_nodes(G, pos, nodelist = nodeListRouter,\ node_color = 'yellow', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListAgg,\ node_color = 'orange', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListRack,\ node_color = 'green', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListPiece,\ node_color = 'green', node_size = 400) nx.draw_networkx_nodes(G, pos, nodelist = nodeListApp,\ node_color = 'yellow', node_size = 400) nx.draw_networkx_edges(G, pos, width=1.0, alpha=1.0) nx.draw_networkx_labels(G, pos, labels, font_size=12) else: pass plt.show()
while curr_state != 9: next_step = np.where(Q[curr_state, ] == np.max(Q[curr_state]))[1] if len(next_step) > 1: next_step = np.random.choice(next_step, 1)[0] curr_edge.append(next_step) else: next_step = next_step[0] curr_edge.append(next_step) path.append(tuple(curr_edge)) curr_state = next_step curr_edge = [ curr_state, ] print(path) # To draw the graph import networkx as nx my_graph = nx.Graph() my_graph.add_edges_from(point_set, color="black", weight=1) for e1, e2 in path: my_graph[e1][e2]['color'] = "blue" my_graph[e1][e2]["weight"] = 3 layout = nx.spring_layout(my_graph) edges = my_graph.edges() colors = [my_graph[a][b]['color'] for a, b in edges] weights = [my_graph[u][v]['weight'] for u, v in edges] nx.draw(my_graph, layout, edges=edges, edge_color=colors, width=weights) nx.draw_networkx_labels(my_graph, layout) plt.show()
#print G.nodes(data=True) pos = nx.random_layout(G) #pos=nx.spring_layout(G,scale=10) plt.figure(figsize=(8, 8)) #draw nodes for i in range(no_of_communities): current_nodes = all_social_network_graph_user[i] nx.draw_networkx_nodes(G, pos, node_size=500, nodelist=current_nodes, node_color=(random(), random(), random())) ## for all one color #nx.draw_networkx_nodes(G,pos,node_size=500,nodelist=current_nodes,node_color='r') # labels nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif') #nx.draw(G) plt.axis('off') plt.savefig('ques.jpg') plt.show() print all_social_network_graph_user for one_cluster in all_social_network_graph_user: print len(one_cluster)
def DrawSyndromes(self, xSyndNodes, zSyndNodes): print("Drawing SCLayout with syndromes") xcrdlist = [self.map.inv[s] for s in xSyndNodes if s in self.map.inv] xslist = [self.crd2name[crd] for crd in xcrdlist] zcrdlist = [self.map.inv[s] for s in zSyndNodes if s in self.map.inv] zslist = [self.crd2name[crd] for crd in zcrdlist] nx.draw_networkx_nodes(self.graph, self.pos, nodelist=self.dList, node_color='green', alpha=0.85, node_size=1000) nx.draw_networkx_nodes(self.graph, self.pos, nodelist=self.xList, node_color='red', alpha=0.85, node_size=1000) nx.draw_networkx_nodes(self.graph, self.pos, nodelist=self.zList, node_color='blue', alpha=0.85, node_size=1000) #nx.draw_networkx_nodes(self.graph, self.pos, nodelist=self.zBndryList , node_color='blue', alpha=0.25, node_size=1000) #nx.draw_networkx_nodes(self.graph, self.pos, nodelist=self.xBndryList , node_color='red', alpha=0.25, node_size=1000) nx.draw_networkx_nodes(self.graph, self.pos, nodelist=xslist, node_color='red', alpha=0.95, node_shape='D', node_size=1000) nx.draw_networkx_nodes(self.graph, self.pos, nodelist=zslist, node_color='blue', alpha=0.95, node_shape='D', node_size=1000) nx.draw_networkx_labels(self.graph, self.pos, font_size=10, font_color='white') nx.draw_networkx_edges(self.graph, self.pos, edge_color='black', arrows=False, style='dashed') plt.title( str(self.dx) + "X" + str(self.dy) + " lattice layout with X and Z syndromes") plt.axis('on') plt.axis('equal') plt.grid('on') #plt.savefig("graph.png") #plt.ion() plt.show()
print(relation_key[0][0]) print('######################################################################################################################################') #最後畫圖 G = nx.Graph() for i in range(len(relation_key)): G.add_edge(relation_key[i][0], relation_key[i][1], weight=key_value[i][1]) elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 12] esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 12] pos = nx.spring_layout(G) # nodes nx.draw_networkx_nodes(G, pos, node_size=350) # edges nx.draw_networkx_edges(G, pos, edgelist=elarge,width=6) nx.draw_networkx_edges(G, pos, edgelist=esmall,width=3, alpha=0.5, edge_color='b') # labels # 結點字會出現亂碼或方塊是因為內建沒有中文字只要去網路上下載中文字體ttf檔然後將檔名存成DejaVuSans放在matplotlib中的mpl-data\fonts\ttf的資料夾下 nx.draw_networkx_labels(G, pos, font_size=5, font_family='DejaVu Sans') plt.axis('off') plt.show()
def draw_topology(self, include_labels=True, save_to_file=None): r"""Plot the current topology. For use in interactive sessions.""" import networkx as nx plt.clf() Graph = nx.Graph() print("site indices:", self.site_indices) for c in self.site_indices: Graph.add_node(c) Graph.nodes[c]["neighbours"] = self.nearest_neighbours[c] Graph.nodes[c]["position"] = tuple(self.coordinates[c]) Graph.nodes[c]["label"] = str(c) # Get positions and labels positions = dict( zip( Graph.nodes(), tuple([prop["position"] for (n, prop) in Graph.nodes(data=True)]), ) ) label_positions = [] label_padding = 0.0 labels = dict( zip( Graph.nodes(), tuple([prop["label"] for (n, prop) in Graph.nodes(data=True)]), ) ) for key in positions.keys(): label_positions.append( tuple(np.array(positions[key]) - np.array([0.0, label_padding])) ) label_positions = dict(zip(positions.keys(), tuple(label_positions))) # which nodes to connect (nearest neighbours) edges = [] for c in self.site_indices: # neighbours = self.nearest_neighbours[c] neighbours = self.site_connections[c] for n in neighbours: edge = tuple(sorted([c, n])) if edge not in edges: edges.append(edge) plt.gca().invert_yaxis() # so branch 0 on top plt.title("Topology of system") nx.draw_networkx_nodes( Graph, with_labels=True, # labels=labels, pos=positions, node_size=600, node_color="blue", alpha=0.2, ) if include_labels: nx.draw_networkx_labels( Graph, label_positions, labels, font_color="black", font_weight="bold" ) nx.draw_networkx_edges( Graph, pos=self.coordinates, edgelist=edges, edge_color="grey", alpha=0.8, style="dashed", label="Nearest neighbours", ) self.Graph = Graph if save_to_file is not None: plt.savefig(save_to_file)
def network(self, filename: str, expt_to_bait=None, figsize=[8, 8], fontsize=6, **kargs): """ **Purpose** Draw a connected network PPI-style plot. Designed for Co-IP MS experiments Requires networkx **Arguments** filename (Required) filename to save the image of the network expt_to_bait (Required) A dict with the bait for each experiment. Use '-' for controls. fontsize (Optional, default=6) fontsize for the nodes; **Returns** The networkx network """ assert filename, 'filename is required' assert self.called, 'network can only be used if the data has been called' assert expt_to_bait, 'Requires a expt_to_bait argument' assert isinstance(expt_to_bait, dict), 'Must be a dict' import networkx as nx g = nx.Graph() __already_warned_using_as_bait = set([]) # Nodes #for pep in self.linearData: # g.add_node(pep['name']) co_interactors = [] baits = [b for b in expt_to_bait.values() if b != '-'] #Edges for pep in self.linearData: for ip, call in zip(self._conditions, pep['call']): try: if expt_to_bait[ip] == '-': continue except KeyError: if ip not in __already_warned_using_as_bait: __already_warned_using_as_bait.add(ip) config.log.warning( f'Treating "{ip}" as a control sample. Add {{"{ip}": "-"}} to expt_to_bait to remove this warning' ) if call: if expt_to_bait[ip] == pep['name']: continue g.add_edge(expt_to_bait[ip], pep['name']) co_interactors.append(pep['name']) # Check all the baits made it into the network baits = [b for b in baits if b in g] config.log.info('Built network') # Remove isolated nodes; #pos = nx.nx.kamada_kawai_layout(g) #pos = nx.circular_layout(g, scale=0.2) pos = nx.spring_layout(g, k=1, iterations=1000, seed=1234) config.log.info('Layout done') fig = self.draw.getfigure(figsize=figsize) ax = fig.add_subplot(111) ax.axis("off") ax.set_position([0, 0, 1, 1]) nx.draw_networkx_edges(g, pos=pos, alpha=0.1) nx.draw_networkx_nodes(g, pos=pos, nodelist=set(co_interactors), alpha=0.6, node_size=100, node_color="tab:red") nx.draw_networkx_nodes(g, pos=pos, nodelist=baits, alpha=0.9, node_size=100, node_color="tab:orange") nx.draw_networkx_labels(g, pos=pos, font_size=fontsize, alpha=0.9) self.draw.do_common_args(ax, **kargs) real_filename = self.draw.savefigure(fig, filename) return g
labels[u + 1] = "v" labels[u + 2] = "w" u_y = -u_y temp = v_y v_y = -w_y w_y = -temp if i % 2 == 1: u_x += 20 v_x += 20 w_x += 20 for edge in type: clustering_demo.add_edge(node_dict[edge[0]], node_dict[edge[1]]) u += 3 nx.draw_networkx_edges(clustering_demo, positions) nx.draw_networkx_nodes( clustering_demo, positions, node_color=[colors[node] for node in clustering_demo.nodes()]) nx.draw_networkx_labels(clustering_demo, positions, labels, font_size=12, font_family='sans-serif', font_color='black') plt.axis('off') plt.show()
def test_edge_colors_and_widths(self): pos = nx.circular_layout(self.G) for G in (self.G, self.G.to_directed()): nx.draw_networkx_nodes(G, pos, node_color=[(1.0, 1.0, 0.2, 0.5)]) nx.draw_networkx_labels(G, pos) # edge with default color and width nx.draw_networkx_edges(G, pos, edgelist=[(0, 1)], width=None, edge_color=None) # edges with global color strings and widths in lists nx.draw_networkx_edges(G, pos, edgelist=[(0, 2), (0, 3)], width=[3], edge_color=['r']) # edges with color strings and widths for each edge nx.draw_networkx_edges(G, pos, edgelist=[(0, 2), (0, 3)], width=[1, 3], edge_color=['r', 'b']) # edges with fewer color strings and widths than edges nx.draw_networkx_edges(G, pos, edgelist=[(1, 2), (1, 3), (2, 3), (3, 4)], width=[1, 3], edge_color=['g', 'm', 'c']) # edges with more color strings and widths than edges nx.draw_networkx_edges(G, pos, edgelist=[(3, 4)], width=[1, 2, 3, 4], edge_color=['r', 'b', 'g', 'k']) # with rgb tuple and 3 edges - is interpreted with cmap nx.draw_networkx_edges(G, pos, edgelist=[(4, 5), (5, 6), (6, 7)], edge_color=(1.0, 0.4, 0.3)) # with rgb tuple in list nx.draw_networkx_edges(G, pos, edgelist=[(7, 8), (8, 9)], edge_color=[(0.4, 1.0, 0.0)]) # with rgba tuple and 4 edges - is interpretted with cmap nx.draw_networkx_edges(G, pos, edgelist=[(9, 10), (10, 11), (10, 12), (10, 13)], edge_color=(0.0, 1.0, 1.0, 0.5)) # with rgba tuple in list nx.draw_networkx_edges(G, pos, edgelist=[(9, 10), (10, 11), (10, 12), (10, 13)], edge_color=[(0.0, 1.0, 1.0, 0.5)]) # with color string and global alpha nx.draw_networkx_edges(G, pos, edgelist=[(11, 12), (11, 13)], edge_color='purple', alpha=0.2) # with color string in a list nx.draw_networkx_edges(G, pos, edgelist=[(11, 12), (11, 13)], edge_color=['purple']) # with single edge and hex color string nx.draw_networkx_edges(G, pos, edgelist=[(12, 13)], edge_color='#1f78b4f0') plt.show()
def draw_graph(rules, rules_to_show, metric=None): if metric=='lift': plt.figure(figsize=(12,8)) G1 = nx.DiGraph() color_map=[] colors = 0.14035943 for i in range (rules_to_show): for a in rules.iloc[i]['antecedents']: G1.add_nodes_from(nodes_for_adding=[a]) for c in rules.iloc[i]['consequents']: G1.add_nodes_from(nodes_for_adding=[c]) G1.add_edge(a, c, color=colors, weight= rules.iloc[i,6]) for node in G1: color_map.append('turquoise') edges = G1.edges() colors = [G1[u][v]['color'] for u,v in edges] weights = [G1[u][v]['weight'] for u,v in edges] pos = nx.spring_layout(G1, k=16, scale=1) nx.draw(G1, pos, edges=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.1 nx.draw_networkx_labels(G1, pos,font_size=16) plt.title('Network visualizing association rules',fontsize=20) plt.show() elif metric=='conviction': plt.figure(figsize=(12,8)) G1 = nx.DiGraph() color_map=[] colors = 0.14035943 for i in range (rules_to_show): for a in rules.iloc[i]['antecedents']: G1.add_nodes_from(nodes_for_adding=[a]) for c in rules.iloc[i]['consequents']: G1.add_nodes_from(nodes_for_adding=[c]) G1.add_edge(a, c, color=colors, weight= rules.iloc[i,-1]) for node in G1: color_map.append('turquoise') edges = G1.edges() colors = [G1[u][v]['color'] for u,v in edges] weights = [G1[u][v]['weight'] for u,v in edges] pos = nx.spring_layout(G1, k=16, scale=1) nx.draw(G1, pos, edges=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.1 nx.draw_networkx_labels(G1, pos,font_size=16) plt.title('Network visualizing association rules',fontsize=20) plt.show() elif metric=='confidence': plt.figure(figsize=(12,8)) G1 = nx.DiGraph() color_map=[] colors = 0.14035943 for i in range (rules_to_show): for a in rules.iloc[i]['antecedents']: G1.add_nodes_from(nodes_for_adding=[a]) for c in rules.iloc[i]['consequents']: G1.add_nodes_from(nodes_for_adding=[c]) G1.add_edge(a, c, color=colors, weight= (1+rules.iloc[i,5])) for node in G1: color_map.append('turquoise') edges = G1.edges() colors = [G1[u][v]['color'] for u,v in edges] weights = [G1[u][v]['weight'] for u,v in edges] pos = nx.spring_layout(G1, k=16, scale=1) nx.draw(G1, pos, edges=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.1 nx.draw_networkx_labels(G1, pos,font_size=16) plt.title('Network visualizing association rules',fontsize=20) plt.show() elif metric=='support': plt.figure(figsize=(12,8)) G1 = nx.DiGraph() color_map=[] colors = 0.14035943 for i in range (rules_to_show): for a in rules.iloc[i]['antecedents']: G1.add_nodes_from(nodes_for_adding=[a]) for c in rules.iloc[i]['consequents']: G1.add_nodes_from(nodes_for_adding=[c]) G1.add_edge(a, c, color=colors, weight= (1+rules.iloc[i,4])) for node in G1: color_map.append('turquoise') edges = G1.edges() colors = [G1[u][v]['color'] for u,v in edges] weights = [G1[u][v]['weight'] for u,v in edges] pos = nx.spring_layout(G1, k=16, scale=1) nx.draw(G1, pos, edges=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.1 nx.draw_networkx_labels(G1, pos,font_size=16) plt.title('Network visualizing association rules',fontsize=20) plt.show() else: plt.figure(figsize=(12,8)) G1 = nx.DiGraph() color_map=[] colors = 0.14035943 for i in range (rules_to_show): for a in rules.iloc[i]['antecedents']: G1.add_nodes_from(nodes_for_adding=[a]) for c in rules.iloc[i]['consequents']: G1.add_nodes_from(nodes_for_adding=[c]) G1.add_edge(a, c, color=colors, weight= 2) for node in G1: color_map.append('turquoise') edges = G1.edges() colors = [G1[u][v]['color'] for u,v in edges] weights = [G1[u][v]['weight'] for u,v in edges] pos = nx.spring_layout(G1, k=16, scale=1) nx.draw(G1, pos, edges=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.1 nx.draw_networkx_labels(G1, pos,font_size=16) plt.title('Network visualizing association rules',fontsize=20) plt.show()
def analyze_AG_bipartite_network(genes, authors_GB_genes, pub_thresh=1, save_file_name="author_gene_bp.json", plot_flag=False): gene_list = genes.split(',') t0 = time.time() # unpickle groupby object #authors_GB_genes = pd.read_pickle(author_gene_GB_fname) authors_GB_genes = app.authors_GB_genes_loaded # get rid of invalid genes in gene_list new_gene_list = [] for gene in gene_list: if gene in authors_GB_genes: new_gene_list.append(gene) gene_list = new_gene_list # create list of all authors/weights who have published on at least one gene in gene_list AW_list_total = [] for gene in gene_list: AW_list_total.extend(list(authors_GB_genes[gene].index)) AW_list_total = zip(*AW_list_total) author_list_total = AW_list_total[0] weight_list_total = AW_list_total[1] print(time.time() - t0) author_list_total = pd_Series(author_list_total) weight_list_total = pd_Series(weight_list_total, index=author_list_total) # take the mean of duplicate entries df_temp = pd_DataFrame( { 'weight': list(weight_list_total), 'author': list(author_list_total) }, index=range(len(author_list_total))) AW_gb_temp = df_temp.weight.groupby(df_temp['author']).mean() author_list_total = list(AW_gb_temp.index) weight_list_total = list(AW_gb_temp.values) weight_list_total = pd_Series(weight_list_total, index=author_list_total) # make a dataframe, indexed by authors in author_list_total, with columns = entries in gene_list author_gene_df = pd_DataFrame(np.zeros( [len(author_list_total), len(gene_list)]), index=author_list_total, columns=gene_list) print(time.time() - t0) # fill in the dataframe for gene in gene_list: #print(gene) temp = list(authors_GB_genes[gene].index) temp = zip(*temp) authors_temp = list(np.unique(temp[0])) author_gene_df[gene][authors_temp] = weight_list_total[authors_temp] print(time.time() - t0) # add a column for total weight author_gene_df['total_weight'] = np.sum(np.array(author_gene_df), 1) author_gene_df.sort('total_weight', inplace=True, ascending=False) # next, convert this dataframe into bipartite network # make the small bipartite graph author_gene_bp = nx.Graph() # pick out authors which have published on > pub_thresh genes in gene_list index_temp = list(author_gene_df['total_weight'][ author_gene_df['total_weight'] > pub_thresh].index) # only allow 200 authors max if len(index_temp) > 200: author_nodes = index_temp[0:200] else: author_nodes = index_temp #index_temp = list(author_gene_df['total_num'].index) #author_nodes = index_temp[0:num_authors] print(time.time() - t0) for gene in gene_list: for author in author_nodes: # only add a link if connection exists if author_gene_df[gene][author] > 0: author_gene_bp.add_edge(gene, author) # add all genes in gene_list in case none of them come up author_gene_bp.add_nodes_from(gene_list) # now apply clustering algo to the bipartite graph partition = community.best_partition(author_gene_bp) partition = pd_Series(partition) col_temp_authors = partition[author_nodes] col_temp_genes = partition[gene_list] col_temp = partition[author_gene_bp.nodes()] if plot_flag: # plot graph if plot_flag = True plt.figure(figsize=[15, 15]) pos = nx.spring_layout(author_gene_bp, k=.3) #nx.draw(author_gene_bp,pos=pos,alpha=.5,node_size=100,node_color = col_temp,cmap='Paired') gene_list = list(gene_list) nx.draw_networkx_nodes(author_gene_bp, nodelist=author_nodes, node_color=col_temp_authors, cmap='Paired', pos=pos, alpha=.5, node_size=100) nx.draw_networkx_nodes(author_gene_bp, nodelist=gene_list, node_color=col_temp_genes, cmap='Paired', pos=pos, alpha=.5, node_size=200, node_shape='s') nx.draw_networkx_edges(author_gene_bp, pos=pos, alpha=.1) node_subset_dict = dict(zip(index_temp[0:20], index_temp[0:20])) gene_subset_dict = dict(zip(gene_list, gene_list)) temp = node_subset_dict.update(gene_subset_dict) nx.draw_networkx_labels(author_gene_bp, pos=pos, labels=node_subset_dict) # Set up json for saving # what should the colors be?? num_communities = len(np.unique(col_temp)) color_list = plt.cm.gist_rainbow(np.linspace(0, 1, num_communities)) # blend the community colors (so that to-nodes are a mixture of all the communities they belong to) rfrac, gfrac, bfrac = calc_community_fraction(author_gene_bp, author_nodes, gene_list, partition, color_list) # save network in json format nodes = author_gene_bp.nodes() numnodes = len(nodes) edges = author_gene_bp.edges() numedges = len(edges) #nodes_dict = [{"id":n,"com":col_temp[n],"degree":author_gene_bp.degree(n)} for n in nodes] nodes_dict = [{ "id": n, "com": col_temp[n], "degree": author_gene_bp.degree(n), "rfrac": rfrac[n] * 255, "gfrac": gfrac[n] * 255, "bfrac": bfrac[n] * 255 } for n in nodes] node_map = dict(zip( nodes, range(numnodes))) # map to indices for source/target in edges edges_dict = [{ "source": node_map[edges[i][0]], "target": node_map[edges[i][1]] } for i in range(numedges)] #import json json_graph = {"directed": False, "nodes": nodes_dict, "links": edges_dict} #json.dump(json_graph,open(save_file_name,'w')) print(time.time() - t0) return json_graph
nx.draw_networkx_nodes(G, pos, nodelist=node_citation, node_color='b', node_size=50, alpha=0.3) nx.draw_networkx_nodes(G, pos, nodelist=node_related, node_color='g', node_size=50, alpha=0.3) nx.draw_networkx_edges(G, pos, width=0.5, alpha=0.2) nx.draw_networkx_nodes(G, pos, nodelist=node_patent + node_patent_cited, node_color='red', node_size=300, with_labels=True) nx.draw_networkx_labels(G, pos, labels=dict( zip(node_patent + node_patent_cited, node_patent + node_patent_cited))) plt.savefig(r'visualization\citation graph\total.png')
else: node_color_array.append(another_state_color) pos = nx.spring_layout(G) for edge in G.edges(): e.draw_networkx_multi_edges(G, pos, edgelist=[edge], width=1.0, alpha=0.6, arrows=True, label=state_to_state_transition[edge], rad=0.3) nx.draw_networkx_nodes(G, pos, nodelist=G.nodes(), node_size=300, node_color=node_color_array, alpha=0.8) nx.draw_networkx_labels(G, pos, labels={node: node for node in G.nodes()}) e.draw_networkx_edge_labels(G, pos, edge_labels=state_to_state_transition, label_pos=0.5, alpha=1.0, rotate=True) # pyplot render plt.axis('off') plt.show()
def visualize(self, file_name=None, file_format="pdf", dim=2, k=None, pos=None, fixed=None, iterations=50, weight='weight', scale=1.0, labeled=False): layout = nx.spring_layout(self.graph.structure, dim=dim, k=k, pos=pos, fixed=fixed, iterations=iterations, weight=weight, scale=scale) handles = [] honest_handle = nx.draw_networkx_nodes( self.left_region.graph.structure, layout, node_size=150, node_color="green") honest_handle.set_label("Honest") handles.append(honest_handle) sybil_nodes = range(self.left_region.graph.structure.order(), self.graph.order()) sybil_handle = nx.draw_networkx_nodes( self.right_region.graph.structure, layout, nodelist=sybil_nodes, node_size=150, node_color="red") sybil_handle.set_label("Sybil") handles.append(sybil_handle) known_handle = nx.draw_networkx_nodes(self.left_region.graph.structure, layout, nodelist=self.known_honests, node_color="orange", node_size=150) known_handle.set_label("Known") handles.append(known_handle) if labeled: nx.draw_networkx_labels(self.graph.structure, layout) nx.draw_networkx_edges(self.graph.structure, layout, edge_color="black", alpha=0.5) nx.draw_networkx_edges(self.graph.structure, layout, edgelist=self.attack_edges, edge_color="red", alpha=0.5, width=5) labels = [handle.get_label() for handle in handles] plt.legend(handles, labels, scatterpoints=1) plt.title("{0}".format(self.name)) plt.axis('off') if file_name: plt.savefig("{0}.{1}".format(file_name, file_format), format=file_format) plt.clf() else: plt.show()
import networkx as nx import matplotlib.pyplot as plt import numpy as np import pandas as pd # loading the Les Miserables network G = nx.read_gml('IntroNetworkData/lesmis.gml') # drawing the graph --- Kamada-Kawai layout plt.figure(figsize=[9,9]) pos = nx.kamada_kawai_layout(G, weight=None) # positions for all nodes nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos, edge_color='lightblue') nx.draw_networkx_labels(G, pos, font_size=10, font_color='DarkGreen') plt.axis('off') plt.title('Les Miserables interaction network') plt.show() # loading the college football network G = nx.read_gml('IntroNetworkData/football.gml') # drawing the graph --- Kamada-Kawai layout plt.figure(figsize=[12,12]) pos = nx.kamada_kawai_layout(G, weight=None) # positions for all nodes # extracting conference information conf = [] for i,d in G.nodes(data=True): conf.append(d['value']) # drawing nodes, different conferences in different colors for iConf in range(12):
def generate_edge_weight_buffer(nodes): b_nodes = list(nodes.values()) print(b_nodes) G = nx.DiGraph() total_stake = sum([node.stake for node in b_nodes]) # Build node sizes in proportion to stake held within the graph. node_sizes = [] node_labels = {} for node in b_nodes: G.add_node(node.identity) node_sizes.append(25 + 500 * (node.stake / total_stake)) node_labels[node.identity] = str(node.identity) # Edge colors (alphas and weight) reflect attribution wieghts of each # connection. edge_colors = {} edge_labels = {} for node in b_nodes: for edge in node.edges: if (node.identity, edge['first']) not in edge_labels: G.add_edge(node.identity, edge['first']) edge_colors[(node.identity, edge['first'])] = float(edge['second']) if node.identity != edge['first']: edge_labels[( node.identity, edge['first'])] = "%.3f" % float(edge['second']) else: edge_labels[(node.identity, edge['first'])] = "" # Set edge weights. for u, v, d in G.edges(data=True): d['weight'] = edge_colors[(u, v)] edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items()) # Clear Matplot lib buffer and create new figure. plt.cla() plt.clf() figure = plt.figure(figsize=(20, 15)) pos = nx.layout.circular_layout(G) nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='blue') edges = nx.draw_networkx_edges(G, pos, arrowstyle='->', arrowsize=15, edge_color=weights, edge_cmap=plt.cm.Blues, width=5) edge_labels = nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, with_labels=True, label_pos=0.3) for node in b_nodes: pos[node.identity] = pos[node.identity] + numpy.array([0, 0.1]) labels = nx.draw_networkx_labels(G, pos, node_labels) # Save the plot to a PNG in memory. buf = io.BytesIO() plt.savefig(buf, format='png') # Closing the figure prevents it from being displayed directly inside # the notebook. plt.close(figure) buf.seek(0) return buf
def creategraph1(self): import networkx as nx import pylab g = nx.Graph() for conn in self.nw.conns.index: nodename1 = str(conn.s.label) + str(conn.s_id) nodename2 = str(conn.t.label) + str(conn.s_id) if g.has_node(nodename1): print('node {} already in'.format(nodename1)) else: g.add_node(nodename1) if g.has_node(nodename2): print('node {} already in'.format(nodename2)) else: g.add_node(nodename2) # edgename = 'conn_'+str(conn.s.label)+'-'+str(conn.t.label) g.add_edge(nodename1, nodename2, name=str(conn.s.label) + str(conn.t.label)) self.g = g pos = nx.spring_layout(g) pylab.figure(1) nx.draw(g, pos) nx.draw_networkx_labels(g, pos, node_size=0.1) # def plotnw(nw): # import networkx as nx # from plotly.offline import download_plotlyjs, init_notebook_mode, iplot # from plotly.graph_objs import * # init_notebook_mode() # g = nx.Graph() # for conn in self.nw.conns.index: # nodename1 = str(conn.s.label) # nodename2 = str(conn.t.label) # if g.has_node(nodename1): # print('node {} already in'.format(nodename1)) # else: # g.add_node(nodename1) # # if g.has_node(nodename2): # print('node {} already in'.format(nodename2)) # else: # g.add_node(nodename2) # #edgename = 'conn_'+str(conn.s.label)+'-'+str(conn.t.label) # g.add_edge(str(conn.s.label),str(conn.t.label)) # #print(g.nodes) # #print(g.edges) # #nx.draw_spring(g,node_size=0.1) # pos = nx.spectral_layout(g) # print(pos) # fig = go.Figure(data=[edge_trace, node_trace], # layout=go.Layout( # title='<br>Network graph made with Python', # titlefont=dict(size=16), # showlegend=False, # hovermode='closest', # margin=dict(b=20,l=5,r=5,t=40), # annotations=[ dict( # text="Python code: <a href='https://plot.ly/ipython-notebooks/network-graphs/'> https://plot.ly/ipython-notebooks/network-graphs/</a>", # showarrow=False, # xref="paper", yref="paper", # x=0.005, y=-0.002 ) ], # xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), # yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))) # # py.iplot(fig, filename='networkx') # %% #dhi = DHimport('heatnet', 'WaermeNetz') # dhi.import_xml() # dhi.export_xml_topickles('pickles') # dhi.creategraph(draw =True) #dhi.import_xml_frompickles('pickles') #dhi.import_xml_frompickles('pickles_little') #dhi.createTESPynet() #dhi.creategraph() # dhi = DHimport('heatnet', 'WaermeNetz') # dhi.import_xml_frompickles('pickles_little_little') # dhi.createTESPynet() #dhi.creategraph1()
import networkx as nx import matplotlib.pyplot as plt nl=6 puntos=7 G=nx.grid_2d_graph(N,N) pos = dict(zip(G.nodes(),G.nodes())) ordering = [(y,N-1-x) for y in range(N) for x in range(N)] labels = dict(zip(ordering, range(len(ordering)))) nx.draw_networkx(G, pos=pos, with_labels=False, node_size = 300, node_color='green') nx.draw_networkx_labels(G, pos=pos, labels=labels) plt.axis('off') plt.show() plt.savefig("ldjnd")
def draw_task_graph(tg, ttg=None): print ("DRAWING TASK GRAPH...") plt.figure() node_colors = [] for Node in tg.nodes(): if tg.node[Node]['Criticality'] == 'H': node_colors.append('#FF878B') elif tg.node[Node]['Criticality'] == 'GH': node_colors.append('#FFC29C') elif tg.node[Node]['Criticality'] == 'GNH': node_colors.append('#928AFF') else: node_colors.append('#A0CBE2') edge_colors = [] for Edge in tg.edges(): if tg.edge[Edge[0]][Edge[1]]['Criticality'] == 'H': edge_colors.append('red') else: edge_colors.append('black') tg_edge_list = [] tg_edge_weight = [] for Edge in tg.edges(): tg_edge_list.append(Edge) tg_edge_weight.append(tg.edge[Edge[0]][Edge[1]]['ComWeight']) if Config.TG_Type == "RandomIndependent": pos = networkx.shell_layout(tg) else: width = 1000 height = 10000 pos = {} max_distance = TG_Functions.calculate_max_distance(tg) for current_distance in range(0, max_distance+1): num_tasks_with_same_distance = 0 for node in tg.nodes(): if tg.node[node]['Type'] == 'App': distance = tg.node[node]['Distance'] if current_distance == distance: num_tasks_with_same_distance += 1 counter = 0 for node in tg.nodes(): if tg.node[node]['Type'] == 'App': distance = tg.node[node]['Distance'] if current_distance == distance: counter += 1 pos[node] = (counter*(width/num_tasks_with_same_distance)+width, (max_distance-current_distance)*height/max_distance) if ttg is not None: temp_pos = networkx.shell_layout(ttg) for test_node in tg.nodes(): if tg.node[test_node]['Type'] == 'Test': pos[test_node] = [temp_pos[test_node][0]*(width/2)+width/2, temp_pos[test_node][1]*(height/2)+height/2] networkx.draw_networkx_nodes(tg, pos, with_labels=True, node_color=node_colors, node_size=50) networkx.draw_networkx_edges(tg, pos, edge_color=tg_edge_weight, edge_cmap=plt.cm.Reds, width=3, arrows=False) networkx.draw_networkx_edges(tg, pos, arrows=False, width=0.5) networkx.draw_networkx_labels(tg, pos, font_size=4) # networkx.draw_networkx_edge_labels(TG, pos, edge_labels=dict(zip(tg_edge_list, tg_edge_weight)), # font_size=10, label_pos=0.7) if ttg is None: plt.savefig("GraphDrawings/TG.png", dpi=200, bbox_inches='tight') else: plt.savefig("GraphDrawings/TG_And_TTG.png", dpi=200, bbox_inches='tight') plt.clf() print ("\033[35m* VIZ::\033[0mTASK GRAPH DRAWINGS CREATED AT: GraphDrawings/TG.png") return None