def test_fixed_node_fruchterman_reingold(self): # Dense version (numpy based) pos = nx.circular_layout(self.Gi) npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos, fixed=[(0, 0)]) assert_equal(tuple(pos[(0, 0)]), tuple(npos[(0, 0)])) # Sparse version (scipy based) pos = nx.circular_layout(self.bigG) npos = nx.fruchterman_reingold_layout(self.bigG, pos=pos, fixed=[(0, 0)]) for axis in range(2): assert_almost_equal(pos[(0,0)][axis], npos[(0,0)][axis])
def test_fixed_node_fruchterman_reingold(self): # Dense version (numpy based) pos = nx.circular_layout(self.Gi) npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos, fixed=[(0, 0)]) assert_equal(tuple(pos[(0, 0)]), tuple(npos[(0, 0)])) # Sparse version (scipy based) pos = nx.circular_layout(self.bigG) npos = nx.fruchterman_reingold_layout(self.bigG, pos=pos, fixed=[(0, 0)]) for axis in range(2): assert_almost_equal(pos[(0, 0)][axis], npos[(0, 0)][axis])
def test_smoke_int(self): G = self.Gi vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.fruchterman_reingold_layout(self.bigG) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(self.bigG) vpos = nx.shell_layout(G)
def test_smoke_int(self): G = self.Gi vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.fruchterman_reingold_layout(self.bigG) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(self.bigG) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
def test_smoke_empty_graph(self): G = [] nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.bipartite_layout(G, G) nx.spiral_layout(G) nx.kamada_kawai_layout(G)
def test_smoke_string(self): G = self.Gs nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.spiral_layout(G) nx.kamada_kawai_layout(G) nx.kamada_kawai_layout(G, dim=1) nx.kamada_kawai_layout(G, dim=3)
def visualize(savefile, i): adj = pickle.load(open('PROCESSED/adjacentMatrixUnderCS_1000', 'rb')) adj = nx.from_scipy_sparse_matrix(adj) dic = defaultdict(list) with open('PROCESSED/PaperToKeywords_1000.txt', 'r') as outfile: pid = 0 for line in outfile: keywords = line.strip().split('\t') keyword = keywords[random.randint(0, len(keywords) - 1)] dic[keyword].append(pid) pid += 1 plt.figure(i) # pos = nx.spectral_layout(adj) pos = nx.fruchterman_reingold_layout(adj) # pos = nx.spring_layout(adj) color = list() for i in range(0, 10): color.append(generate_new_color(color, pastel_factor=0.9)) i = 0 for keywords, pid_list in dic.items(): nx.draw_networkx_nodes(adj, pos, nodelist=pid_list, node_color=color[i], node_size=10, alpha=0.7) i += 1 nx.draw_networkx_edges(adj, pos, width=1.0, alpha=0.5) plt.title('Network Visualization for 1000 documents') plt.savefig(save)
def fn_load_graph(G_type): """ load a graph - can be google, gen_large, gen_new """ if G_type == "google": # google graph prep G_path = “…\\web-Google.txt" G = nx.read_edgelist(G_path,comments='#',create_using=nx.DiGraph(), nodetype=int) # load the graph # get largest weakly connected component G = max(nx.weakly_connected_component_subgraphs(G),key=len) G = G.to_undirected() # convert to undirected elif G_type == "gen_large": # originally used #n = 600000 # nodes #m = 3 # edges per node #G = nx.barabasi_albert_graph(n,m,seed=1) # preferential attachment G_path = "random walks\\practical\\keeper results\\graph_01.txt" nx.write_edgelist(G, G_path) G = nx.read_edgelist(G_path,nodetype=int) elif G_type == "gen_new": n = 50 # nodes m = 3 # edges per node G = nx.barabasi_albert_graph(n,m,seed=1) if draw_graph: pos = nx.fruchterman_reingold_layout(G) nx.draw(G,pos,with_labels=True) return G
def get_interaction_networks(network_name, data, interactions, location): DG = nx.Graph() """Initiating host nodes""" birds = data.groupby(['ID', 'Sex', 'Age', 'Location', 'Species' ]).size().reset_index().rename(columns={0: 'count'}) birds_n = pd.unique(interactions[['ID', 'second_bird']].values.ravel('K')) birds = birds[birds['ID'].isin(birds_n)] for index, row in birds.iterrows(): DG.add_node(row['ID'], type="host", Sex=row['Sex'], Age=row['Age'], Location=row['Location'], Species=row['Species']) """Iterating through the raw data to add Edges if a virus is found in a host""" for index, row in interactions.iterrows(): DG.add_edge(row['ID'], row['second_bird'], weight=row['overlap'] + 12) """Creating positions of the nodes""" #layout = nx.spring_layout(DG, k = 0.05, scale=2) # layout = nx.fruchterman_reingold_layout(DG, k=0.05, iterations=50) """graph ready""" nx.write_graphml( DG, location + '/' + network_name + "hummingbirds_interaction.graphml") nx.draw(DG) # networkx draw() plt.draw() return DG
def draw_streets_as_vertices(g, ebc, max_ebc, save_img=False, save_name="saida.png"): node_colors = [] nodes_to_label = {n: "" for n in g.nodes()} for n in g.nodes(): node_colors.append(-ebc[n] / (1.0 * max_ebc)) if ebc[n] >= (max_ebc * 0.4): print n nodes_to_label.update({n: n}) nx.draw_networkx(g, pos=nx.fruchterman_reingold_layout(g), font_size=12, with_labels=True, labels=nodes_to_label, linewidths=None, node_size=30, arrows=False, node_color=node_colors, cmap=plt.cm.RdYlGn, vmin=-1.0, vmax=0.0) if save_img: plt.savefig("%s/%s" % (mg.NODE_BETWEENNESS_IMG_FOLDER, save_name), dpi=1200) else: plt.show()
def plot_rules(rules: List[Craft]) -> None: import networkx as nx from matplotlib import pyplot pyplot.figure(figsize=(30, 30)) G = nx.MultiDiGraph(directed=True) values = {} for craft in rules: for source in craft.from_item: G.add_edges_from([(source.item.name, craft.to_item.item.name)], lab=craft.label(source)) values[craft.to_item.item.name] = craft.time edge_labels = dict([(( u, v, ), d["lab"]) for u, v, d in G.edges(data=True)]) pos = nx.fruchterman_reingold_layout(G, k=0.7, iterations=100, scale=5) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw_networkx(G, pos, with_labels=True, node_size=3000, node_color=[values.get(node, 0) for node in G.nodes()]) pyplot.show()
def my_graph_generator(file, value, ordered): G = nx.Graph() source = [] node_indices = [] with open(file, 'r') as f: for line in f: line = line.strip() names = line.split(";") source.append((names[0], names[1])) G.add_edge(names[0], names[1], weight=1) for nm in names[0:1]: if nm not in node_indices: node_indices.append(nm) size_array = [] for nd in G.nodes(): G.node[nd]['degree'] = len(G[nd]) G.node[nd]['size'] = int(math.log(G.node[nd]['degree'] + 2) * 5) size_array.append(G.node[nd]['size']) pos = [] if value == 'circ': [pos, size_array] = my_circular_layout(G, ordered, size_array) if value == 'lvl': [pos, size_array] = my_level_layout(G) if value == 'oth': pos = nx.fruchterman_reingold_layout(G) #nx.draw(G,pos = my_circular_layout(G),with_labels=True,nodecolor = 'b',edge_color = 'r',node_size=size_array,node_shape='o') return [G, pos, size_array]
def plotGraphs(forest,tweet_ids,noGraphs = 10): ''' Plots all graphs in the forest. :param forest: List of reply trees :param tweet_ids: Dict of all tweet ids ''' fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 6 fig_size[1] = 6 plt.rcParams["figure.figsize"] = fig_size font = {'family' : 'normal', 'size' : 1} plt.rc('font', **font) for row in range(noGraphs): test = 1 #print(row) g = nx.Graph() traverse(g,forest[row],tweet_ids) d=dict(g.degree) nx.draw_networkx(g, pos = nx.fruchterman_reingold_layout(g),node_size=[v * 2 for v in d.values()],font_size=1,width =0.08) plt.savefig('../DATA/graph'+str(row)+'.png' ,dpi = 1200) print(row) g.clear() plt.clf()
def word_sna_graph(word_matrix, n, fname=None): G = nx.Graph() for word1, word2, count in word_matrix[:n]: #상위 n개로만 그림 그리기 G.add_edge(word1, word2, weight=count) T = nx.minimum_spanning_tree(G) nodes = nx.nodes(T) degrees = nx.degree(T) node_size = [] for node in nodes: ns = degrees[node] * 200 node_size.append(ns) if sys.platform in ["win32", "win64"]: font_name = "malgun gothic" elif sys.platform == "darwin": fornt_name = "AppleGothic" plt.figure(figsize=(12, 10)) nx.draw( T, pos=nx.fruchterman_reingold_layout(G, k=0.5), node_size=node_size, node_color="#42FC0A", #노란색: "#FFE27F" # http://www.colourlovers.com/palettes/add 에서 색상 가져올 수 있음 font_family=font_name, label_pos=0, #0=head, 0.5=center, 1=tail with_labels=True, font_size=10) if fname != None: plt.savefig(fname) print('{}에 저장하였습니다'.format(fname)) plt.axis("off") plt.show()
def drawGraph(): getMatrix() g = [] for i in range(size): for j in range(size): if matrix[i][j] != 0: g.append([[nodes[i], nodes[j]], matrix[i][j]]) G = nx.Graph() for i in range(len(g)): G.add_edge(*g[i][0], weight=g[i][1]) pos = nx.fruchterman_reingold_layout(G) edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)} nx.draw_networkx_nodes(G, pos, node_size=600) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.axis('off') plt.savefig('output.png') plt.close() panel.configure(image=img1) panel.image = img1 img2 = ImageTk.PhotoImage(Image.open('output.png')) panel.configure(image=img2) panel.image = img2
def afficher_graph_dens_weight(n, dens): G = graphe_creux_dens_weight2(n, dens) #print(G.edges()) elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] < 10**6 + 10000 and d['weight'] > 10**6 - 10000] esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 10**6 + 10000 or d['weight'] < 10**6 - 10000] #erand=[(u,v) for (u,v,d) in G.edges(data=True) if abs(d['weight']) !=1] pos = nx.fruchterman_reingold_layout(G) 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') #nx.draw_networkx_edges(G,pos,edgelist=erand, #width=6,alpha=0.5,edge_color='r',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
def build_neigh(query_repo, k=50): import networkx if query_repo not in all_repos: return '%s is not in the list of repos, please choose a public repo with at least 10 stargazers' % query_repo result = None try: result = graph.get_neighborhood(query_repo, radius=2,) verts, edges = result.get_vertices(), result.get_edges() similar_text = rec_text.get_similar_items([query_repo], k) text_search = verts.filter_by(similar_text['similar'], '__id') text_search = list(set(text_search['__id'])) verts, edges = list(verts) , list(edges) G = networkx.Graph() G.add_edges_from([[i['__src_id'], i['__dst_id']] for i in edges]) pos=networkx.fruchterman_reingold_layout(G) for vert in verts: vert['x'] = int(pos.get(vert['__id'])[0]*10000) vert['y'] = int(pos.get(vert['__id'])[1]*10000) vert['text'] = 1 if vert['__id'] in text_search else 0 # vert['contributros'] = 1 if vert['__id'] in contributors else 0 return {"edges": edges, "verts": verts, "query": query_repo} except Exception as e: return 'Exception error: %s' %type(e)
def create_graph(adjacency_matrix, graph_layout='shell'): # given an adjacency matrix use networkx and matlpotlib to plot the graph rows, cols = np.where(adjacency_matrix == 1) edges = zip(rows.tolist(), cols.tolist()) G = nx.Graph() G.add_edges_from(edges) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos = nx.spring_layout(G) elif graph_layout == 'spectral': graph_pos = nx.spectral_layout(G) elif graph_layout == 'random': graph_pos = nx.random_layout(G) elif graph_layout == 'kk': graph_pos = nx.kamada_kawai_layout(G) elif graph_layout == 'fruchterman_reingold': graph_pos = nx.fruchterman_reingold_layout(G) else: graph_pos = nx.shell_layout(G) nx.set_node_attributes(G, name='pos', values=graph_pos) return G
def plot_2D(self, attr, label=False): plt.clf() block = nx.get_node_attributes(self.G, 'block') pos = nx.fruchterman_reingold_layout(self.G) labels = {} for node in block: labels[node] = node for node in set(self.nodeSet): nx.draw_networkx_nodes(self.G, pos, with_labels=False, nodelist=[key for key, val in block.items() if val == node], node_color=attr[node][0], node_size=attr[node][1], alpha=0.8) nx.draw_networkx_edges(self.G, pos, width=1.0, alpha=0.5) for key, value in pos.items(): pos[key][1] += 0.01 if label == True: nx.draw_networkx_labels(self.G, pos, labels, font_size=7) plt.axis('off') f = tempfile.NamedTemporaryFile( dir='out/sna', suffix='.png', delete=False) # save the figure to the temporary file plt.savefig(f, bbox_inches='tight') f.close() # close the file # get the file's name # (the template will need that) plotPng = f.name.split('/')[-1] plotPng = plotPng.split('\\')[-1] return plotPng
def get_results(self, images_dir): """Gathers the results of the CPM algorithm. It gathers the results, images, and optimum solution as founded by the CPM algorithm that run on the given project. Args: images_dir: a string, that represents the path that the images will be stored Returns: A tuple of three objects. The first object is a list of dictionaries, the second object is a list of strings, and the third object is a tuple of two numbers. """ pos = None images = [] results = [] solutions = [] for iteration, snapshot in enumerate(self.snapshots): graph = pickle.loads(snapshot) results.append(graph.results) solutions.append((graph.results['total_cost'], graph.results['project_duration'])) if iteration == 0: pos = networkx.fruchterman_reingold_layout(graph) images.append(draw_network(graph, pos, images_dir, iteration)) optimum_solution = min(solutions) return results, images, optimum_solution
def test_smoke_int(self): G = self.Gi vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.planar_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.fruchterman_reingold_layout(self.bigG) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(G.to_directed()) vpos = nx.spectral_layout(self.bigG) vpos = nx.spectral_layout(self.bigG.to_directed()) vpos = nx.shell_layout(G) vpos = nx.spiral_layout(G) vpos = nx.kamada_kawai_layout(G) vpos = nx.kamada_kawai_layout(G, dim=1)
def display(interval, hold=False): G = ln pos = nx.fruchterman_reingold_layout(G, scale=1000, center=[0, 0]) labels = {} n = sorted(G.nodes(), key=operator.attrgetter('index')) l = [i.name if int(i.name) > 0 else "Hotel" for i in n] for i in range(len(l)): labels[n[i]] = l[i] nx.draw_networkx_nodes(G, pos, alpha=0.7, node_color='lightblue', node_size=100) nx.draw_networkx_edges(G, pos, arrows=True, arrowsize=10, edge_color='lightgreen') nx.draw_networkx_labels(G, pos, labels, font_size=11) # plt.show() if not hold: plt.pause(interval) plt.clf() else: plt.show()
def plot_graph(): edge_list = tangle.edges frm = [] to = [] for i in edge_list.keys(): for j in edge_list[i]: frm.append(i) to.append(j) df = pd.DataFrame({ 'from':frm, 'to':to}) # Build the tangle graph G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.DiGraph) j=65 mapping = {} cols = [] size = [] for i in G: wt = tangle.transactions[i].cumulative_weight mapping[i]=(chr(j), wt) j=j+1 size.append(1000+500*G.in_degree[i]) if G.in_degree[i] > 0: cols.append('skyblue') else: cols.append('lightgreen') nx.draw(G, labels = mapping, node_color = cols, node_size=size, pos=nx.fruchterman_reingold_layout(G)) plt.title("Tangle") plt.show()
def visualize_msm_graph(msm, features_df, output_file, tmat_thresh=2e-2): _m = np.zeros_like(msm.transition_matrix) _m[msm.transition_matrix > tmat_thresh] = msm.transition_matrix[ msm.transition_matrix > tmat_thresh] g_tmat = nx.from_numpy_array(_m, create_using=nx.DiGraph) nodename_dict = { i: features_df.iloc[j].KeywordLabel for i, j in enumerate(msm.active_set) } g_tmat = nx.relabel_nodes(g_tmat, nodename_dict) edge_cmap = plt.matplotlib.colors.LinearSegmentedColormap.from_list( "uwe", [(0, 0, 0, .1), (0, 0, 0, 1)]) weights = np.array(list(nx.get_edge_attributes(g_tmat, 'weight').values())) pos = nx.fruchterman_reingold_layout(g_tmat, k=1e-1) # fixed=keep) fig, ax = plt.subplots(figsize=(10, 10)) nx.draw_networkx_nodes( g_tmat, pos, node_size=msm.pi * 1000, ax=ax, ) nx.draw_networkx_edges(g_tmat, pos, edge_cmap=edge_cmap, node_size=msm.pi * 1000, edge_color=weights, width=2, ax=ax) fig.savefig(output_file)
def draw_network(graph, users, filename): """ Draw the network to a file. Only label the candidate nodes; the friend nodes should have no labels (to reduce clutter). Methods you'll need include networkx.draw_networkx, plt.figure, and plt.savefig. Your figure does not have to look exactly the same as mine, but try to make it look presentable. """ ###TODO candidates_dict = {} layout = nx.fruchterman_reingold_layout(graph) plt.figure(figsize=(40, 50)) nx.draw_networkx(graph, layout, with_labels=False) for n in graph.nodes(): for u in range(0, len(users)): val = users[u]['screen_name'] candidates_dict[users[u]['id']] = val nx.draw_networkx_labels(graph, layout, labels=candidates_dict, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, bbox=None, ax=None) plt.savefig(filename) pass
def plot_digraph(edge, fname): G = nx.DiGraph() G.add_edges_from(edge) plt.figure(figsize=(15, 15)) pos = nx.fruchterman_reingold_layout(G) nx.draw_networkx(G, pos, node_color="#5050ff", font_size=0, node_size=75) plt.savefig(fname)
def user_neighborhood(user_name, d1=20, d2=7): import networkx if user_name not in all_users: return '%s is not in the list of users, please choose a different user or repo' % user_name try: watched_repos = list(user_sf[user_sf['user_name'] == user_name]['repos'][0]) edges = graph.get_edges(src_ids=watched_repos[:d1]) second_degree = edges.groupby('__src_id', {'dst': gl.aggregate.CONCAT('__dst_id')}) def flatten_edges(x): return [[x['__src_id'], edge] for edge in x['dst'][:d2]] edges = second_degree.flat_map(['__src_id','__dst_id'], lambda x: flatten_edges(x)) edges = list(edges.filter_by(list(watched_repos), '__dst_id', exclude=True)) G = networkx.Graph() G.add_edges_from([[i['__src_id'], i['__dst_id']] for i in edges]) G.add_edges_from([[user_name , i['__src_id']] for i in edges]) pos=networkx.fruchterman_reingold_layout(G) verts = list(graph.get_vertices(G.nodes())) verts.append({'__id': user_name}) for vert in verts: vert['x'] = int(pos.get(vert['__id'])[0]*10000) vert['y'] = int(pos.get(vert['__id'])[1]*10000) return {"edges": edges, "verts": verts} except Exception as e: return 'Exception error: %s' %type(e)
def parse(data_input,ID): G = nx.Graph() link_nums=int(data_input[0][1]) Nodes_nums=int(data_input[0][0]) customers=data_input[link_nums+5:] cus_node=[int(x[1]) for x in customers] Nodes_color=['y']*Nodes_nums for rn in cus_node: Nodes_color[rn]='r' color_tb=['r','y','b','g','m'] edges_color=[] G.add_nodes_from(range(Nodes_nums), node_color=Nodes_color) edge_labels={} for L in data_input[4:link_nums+4]: if len(L)==4: line=[int(x) for x in L] clr=color_tb[random.randint(0,len(color_tb)-1)] edges_color.append( clr ) edge_labels[tuple([line[0],line[1]] ) ]="("+L[2]+","+L[3]+")" G.add_edge(line[0],line[1],weight=line[3]) pos = nx.fruchterman_reingold_layout(G) #spectral_layout,shell_layout,spring_layout, plt.figure(2) nx.draw(G,pos,node_color=Nodes_color,edge_color=edges_color, with_labels=True) nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,font_size=8)#,node_color=Nodes_color,edge_color=edges_color, with_labels=True) plt.savefig(str(ID)+".eps",format='eps') plt.show() sp=nx.shortest_path(G, source=0, target=20) print(sp)
def visualize(graph, id_to_counter): # Build a dataframe with 4 connections from_list = [] to_list = [] for k, v in graph.edges.items(): for v_i in v.keys(): from_list.append(id_to_counter[k]) to_list.append(id_to_counter[v_i]) df = pd.DataFrame({'from': from_list, 'to': to_list}) print(df) # Build your graph G = nx.from_pandas_edgelist(df, 'from', 'to') # Plot it # nx.draw(G, with_labels=True) nx.draw(G, with_labels=True, node_size=150, font_size=8, node_color="skyblue", pos=nx.fruchterman_reingold_layout(G)) plt.show()
def auto_layout(self): """ Automatic layout of the nodes """ if self.circuit.graph is None: self.circuit.build_graph() pos = nx.spectral_layout(self.circuit.graph, scale=2, weight='weight') pos = nx.fruchterman_reingold_layout(self.circuit.graph, dim=2, k=None, pos=pos, fixed=None, iterations=500, weight='weight', scale=20.0, center=None) # assign the positions to the graphical objects of the nodes for i, bus in enumerate(self.circuit.buses): try: x, y = pos[i] * 500 bus.graphic_obj.setPos(QPoint(x, y)) # apply changes to the API objects bus.x = x bus.y = y except KeyError as ex: warn('auto_layout: Node ' + str(i) + ' not in the graph!!!! \n' + str(ex)) self.center_nodes()
def draw_clusters(G, clusterfile): with open(clusterfile) as ifile: """colors is list of allowed colors for the clusters""" with open(COLORFILE) as cfile: colors = cfile.readlines() shuffle(colors) colormap = {} i = 0 for line in ifile: clusternodes = line.split() for node in clusternodes: colormap[node] = float(colors[i]) i += 1 values = [colormap[str(node + 1)] for node in G.nodes()] """Drawing starts""" node_labels = {i: str(i + 1) for i in G.nodes()} node_pos = nx.fruchterman_reingold_layout(G) edge_widths = [(G.get_edge_data(u, v)['weight'] / 100.0) * 3 for (u, v) in G.edges()] nx.draw_networkx(G, cmap='jet', pos=node_pos, node_color=values, labels=node_labels, width=edge_widths) plt.savefig(clusterfile + '-visual.jpg', dpi=200) plt.show()
def test_smoke_string(self): G=self.Gs vpos=nx.random_layout(G) vpos=nx.circular_layout(G) vpos=nx.spring_layout(G) vpos=nx.fruchterman_reingold_layout(G) vpos=nx.spectral_layout(G) vpos=nx.shell_layout(G)
def plot_graph(graph): plt.figure(figsize=(20,12)) pos = nx.fruchterman_reingold_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=70) nx.draw_networkx_edges(graph, pos, edgelist=[(u,v) for (u,v,d) in graph.edges(data=True)], width=0.25, edge_color="m", alpha=0.3) nx.draw_networkx_labels(graph, pos, font_size=7, font_family='sans-serif', font_color="b", alpha=0.2) plt.axis('off') plt.show()
def plot_optimal(): plt.figure(2) individual = self.__best_individual__() G = nx.Graph() G.add_nodes_from(individual.names) some_edges = [tuple(list(x)) for x in individual.edges] G.add_edges_from(some_edges) layout = nx.fruchterman_reingold_layout(G) nx.draw_networkx(G, pos=layout, cmap=plt.get_cmap('jet'), node_color=individual.colors.values())
def make_graph(list_of_edges): G = nx.Graph() for x in list_of_edges: pair = tuple(x.split("-", 1)) G.add_edge(pair[0], pair[1]) print len(G.edges()) pos=nx.fruchterman_reingold_layout(G) nx.draw(G,pos) plt.show() return len(list_of_edges)
def test_smoke_empty_graph(self): G = [] vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.spectral_layout(G) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
def test_spring_init_pos(self): # Tests GH #2448 import math G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)]) init_pos = {0: (0.0, 0.0)} fixed_pos = [0] pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos) has_nan = any(math.isnan(c) for coords in pos.values() for c in coords) assert_false(has_nan, 'values should not be nan')
def test_center_parameter(self): G = nx.path_graph(1) vpos = nx.random_layout(G, center=(1, 1)) vpos = nx.circular_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.spring_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.spectral_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1)) vpos = nx.shell_layout(G, center=(1, 1)) assert_equal(tuple(vpos[0]), (1, 1))
def test_empty_graph(self): G = nx.empty_graph() vpos = nx.random_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.circular_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.spring_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.spectral_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.shell_layout(G, center=(1, 1)) assert_equal(vpos, {})
def test_empty_graph(self): G=nx.Graph() vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.shell_layout(G) vpos = nx.spectral_layout(G) # center arg vpos = nx.random_layout(G, scale=2, center=(4,5)) vpos = nx.circular_layout(G, scale=2, center=(4,5)) vpos = nx.spring_layout(G, scale=2, center=(4,5)) vpos = nx.shell_layout(G, scale=2, center=(4,5)) vpos = nx.spectral_layout(G, scale=2, center=(4,5))
def test_single_node(self): G = nx.Graph() G.add_node(0) vpos = nx.random_layout(G) vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) vpos = nx.shell_layout(G) vpos = nx.spectral_layout(G) # center arg vpos = nx.random_layout(G, scale=2, center=(4,5)) vpos = nx.circular_layout(G, scale=2, center=(4,5)) vpos = nx.spring_layout(G, scale=2, center=(4,5)) vpos = nx.shell_layout(G, scale=2, center=(4,5)) vpos = nx.spectral_layout(G, scale=2, center=(4,5))
def draw_streets_as_vertices(g,ebc,max_ebc,save_img=False,save_name="saida.png"): node_colors = [] nodes_to_label = {n:"" for n in g.nodes()} for n in g.nodes(): node_colors.append( -ebc[n]/(1.0*max_ebc) ) if ebc[n]>=(max_ebc*0.4): print n nodes_to_label.update({n:n}) nx.draw_networkx(g,pos=nx.fruchterman_reingold_layout(g),font_size=12,with_labels=True,labels=nodes_to_label,linewidths=None,node_size=30,arrows=False,node_color=node_colors,cmap=plt.cm.RdYlGn, vmin=-1.0, vmax=0.0) if save_img: plt.savefig("%s/%s" % (mg.NODE_BETWEENNESS_IMG_FOLDER,save_name),dpi=1200) else: plt.show()
def draw_graph(graph): nodes = set([n1 for n1, n2, n3 in graph] + [n2 for n1, n2,n3 in graph]) G = nx.Graph() for node in nodes: G.add_node(node) for edge in graph: G.add_edge(edge[0], edge[1], weight = edge[2]) pos = nx.fruchterman_reingold_layout(G) nx.draw(G, pos, node_size = 2) edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) # show graph plt.show()
def plot_graph(graph, threshold, plotfolder): idno = graph.graph["idno"] # Filter the full graph by edge weight graph = nx.Graph([(u, v, d) for u, v, d in graph.edges(data=True) if d['weight'] > threshold]) # Derive necessary data weights = get_weights(graph) edgelabels = create_edgelabels(graph) positions = nx.fruchterman_reingold_layout(graph, k=2, scale=2) # Perform the actual drawing nx.draw_networkx_nodes(graph, positions, node_size=1200, node_color="g", label="label") nx.draw_networkx_edges(graph, positions, width=weights) nx.draw_networkx_labels(graph, positions, font_size=10) nx.draw_networkx_edge_labels(graph, positions, edge_labels=edgelabels, font_size=8) # Save the figure plt.axis('off') plt.title(str(idno)) plt.savefig(plotfolder + idno + "-plot.png", dpi=300) plt.close()
def weighted_edges(weight_tuples, table_type, table="following", categories = categories, colors = cat_colors, e_colors = edge_colors, l_colors = label_colors, fname = "following", users_table = "users"): fname = fname+ ".dot" G=nx.MultiDiGraph() el = {} for x in categories: G.add_node( x , label = x + " ["+ str(users_count(x, users_table)) + "]", style='filled' , fillcolor=colors[x]) max_weight = max(weight_tuples,key=lambda item:item[2])[2] summ = 0 for w in weight_tuples: weight = w[2] summ +=int(weight) edge_weight = 9.0*weight/max_weight + 1 ''' if weight > 1000: edge_weight = 10 elif weight > 100: edge_weight = 7 elif weight > 50: edge_weight = 3 ''' G.add_edge(w[0], w[1], label=str(weight), fontcolor = l_colors[w[0]], style="bold", color= e_colors[w[0]], fontsize=13, fontweight=10, penwidth=edge_weight) el[(w[0], w[1])] = int(weight) pos = nx.circular_layout(G) # positions for all nodes pos = nx.spectral_layout(G) pos = nx.shell_layout(G) pos = nx.fruchterman_reingold_layout(G) #pos = nx.circular_layout(G) # nodes nx.draw_networkx_nodes(G,pos,node_list=categories) nx.draw_networkx_labels(G,pos,font_size=7,font_family='sans-serif') # edges nx.draw_networkx_edges(G,pos) nx.draw_networkx_edge_labels(G,pos, edge_labels = el,) #plt.axis('off') #plt.savefig("edges.png") nx.write_dot(G,fname) print "done :D " print "dot file in " + fname +" :D :D :D"
def draw_graph(graph): nodedata = [(v["weight"], {n: v["label"]}) for (n, v) in graph.nodes(data=True)] nodelabels = {} nodeweights = [] for weight, label in nodedata: nodeweights.append(weight) nodelabels.update(label) # maxweight = max(nodeweights) # minweight = min(nodeweights) # ratio = maxweight/minweight # nodeweights = map(lambda x: x/ratio, nodeweights) # pos = nx.random_layout(graph) pos = nx.fruchterman_reingold_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=nodeweights, node_color="w", alpha=0.4) nx.draw_networkx_labels(graph, pos, nodelabels) nx.draw_networkx_edges(graph, pos) output = basename(getcwd()) + ".gml" if isfile(output): remove(output) nx.write_gml(graph, output) plt.show() # display
def draw_graph(word, hypernym=False): """Draw graph of word hyponym, or hypernym if hypernym=True, Displays in Jupyter notebook. Requires pre-installed plotly apikey""" G = visualize_word(word, not hypernym) nxpos = nx.fruchterman_reingold_layout(G) labels = [] pos = [] for k, v in nxpos.items(): labels.append(str(k())) pos.append(v) trace1 = scatter_edges(G, nxpos) trace2 = scatter_nodes(pos, labels=labels) axis = dict(showline=False, # hide axis line, grid, ticklabels and title zeroline=False, showgrid=False, showticklabels=False, title='') layout = Layout(title='Graph for word "{}"'.format(word), font=Font(), showlegend=False, autosize=True, # width=width, # height=height, xaxis=XAxis(axis), yaxis=YAxis(axis), #margin=Margin( # l=40, # r=40, # b=85, # t=100, # pad=0,), # plot_bgcolor='#EFECEA', #set background color hovermode='closest') data = Data([trace1, trace2]) fig = Figure(data=data, layout=layout) return plotly.iplot(fig, filename='networkx')
def draw_clusters(G, clusterfile): with open(clusterfile) as ifile: """colors is list of allowed colors for the clusters""" with open(COLORFILE) as cfile: colors = cfile.readlines() shuffle(colors) colormap={} i=0 for line in ifile: clusternodes = line.split() for node in clusternodes: colormap[node] = float(colors[i]) i+=1 values = [colormap[str(node+1)] for node in G.nodes()] """Drawing starts""" node_labels = {i:str(i+1) for i in G.nodes()} node_pos = nx.fruchterman_reingold_layout(G) edge_widths = [(G.get_edge_data(u,v)['weight']/100.0)*3 for (u,v) in G.edges()] nx.draw_networkx(G, cmap='jet', pos=node_pos, node_color = values, labels=node_labels, width=edge_widths) plt.savefig(clusterfile+'-visual.jpg', dpi=200) plt.show()
def get_as_uri(G): """Export graph as an html png. Arguments: G -- networkx.Graph -- the graph that will be exported Return: it returns a string containing the html representation """ #clear the figure, in case another one was already drawn. plt.clf() #draw the graph on the figure. nx.draw(G, nx.fruchterman_reingold_layout(G)) #save the figure on a stream. imgdata = StringIO.StringIO() plt.savefig(imgdata, format='png') #return to the beginning of the stream. imgdata.seek(0) #convert to 64 bit representation. buf64 = base64.b64encode(imgdata.buf) uri = 'data:image/png;base64,' + urllib.quote(buf64) #return the html code for the representation. return '<img src = "%s"/>' % uri
def visualize_coarsening(G, G_coarse, c_data): npr.seed(10) random.seed(10) pos = nx.fruchterman_reingold_layout(G) seeds = list(c_data['aggregates'].keys()) for seed in seeds: trapped_nodes = c_data['aggregates'][seed][:] trapped_nodes.remove(seed) #rnd_color = random.choice(['r', 'b', 'g', 'c', 'm', 'y', 'w']) #[npr.rand(), npr.rand(), npr.rand(), npr.rand()] #rnd_color = mpl.colors.rgb2hex((npr.rand(), npr.rand(), npr.rand())) #rnd_color = random.random() #rnd_color = random.choice(mpl.colors.cnames.keys()) rnd_color = (npr.rand(), npr.rand(), npr.rand(), 1.) color_seed = np.ones((1,4)) color_rest = np.ones((len(trapped_nodes),4)) for i,val in enumerate(rnd_color): color_seed[:,i] *= val color_rest[:,i] *= val nx.draw_networkx_nodes(G, pos=pos, nodelist=[seed], node_color=color_seed, cmap=pylab.hot, node_size=500, with_labels=True, node_shape='s') nx.draw_networkx_nodes(G, pos=pos, nodelist=trapped_nodes, node_color=color_rest, cmap=pylab.hot, node_size=200, with_labels=True, node_shape='o') nx.draw_networkx_edges(G, pos=pos, alpha=1.0) nx.draw_networkx_labels(G, pos=pos) pylab.show()
def cascade_ltm_community(self,node_state,graph,seed_size,theta): if Config.plot_graph: in_pos = nx.fruchterman_reingold_layout(inGraph) try: from allPlot import plotGraph except: raise graphObj = plotGraph() adaption_step = 0 adaption_step_starting = 0 adaption_step_others = 0 flag = True step=1 step_dic ={} step_starting_dic = {} step_others_dic = {} node_updated_state = {} unadapted_count = len(node_state) - seed_size unadapted_starting_count = len(node_state)/Config.community_count - seed_size unadapted_others_count = len(node_state)/Config.community_count * (Config.community_count - 1) step_dic[0]=(unadapted_count,unadapted_starting_count,unadapted_others_count) node_adoption_probability = {}# keep adoption prob for each node for i in node_state: node_updated_state[i]=node_state[i] if random.uniform(0,1) < theta: node_adoption_probability[node] = theta - Config.epsilon else: node_adoption_probability[node] = theta + Config.epsilon
def test_smoke_initial_pos_fruchterman_reingold(self): pos = nx.circular_layout(self.Gi) npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
g = create_graph(bills) if args.trim is not None: g = trim_edges(g, weight=args.trim) # Calculate the betweenness centralities of the nodes. Removing the weakest # edges before calculating the betweenness centralities mainly just for # visualization purposes, so it's possible to visually discern which nodes # have stronger relationships with their colleagues and betweenness. betweenness_centralities = nx.centrality.betweenness_centrality(trim_edges(g, weight=10), normalized=False) degrees = nx.degree(trim_edges(g, weight=10)) for node_id in g.nodes(): g.node[node_id]['betweenness'] = betweenness_centralities[node_id] g.node[node_id]['degree'] = degrees[node_id] if not args.browser: pos = nx.fruchterman_reingold_layout(g) dems = [n for n in g.nodes() if g.node[n]['party_affiliation'] == 'democrat'] reps = [n for n in g.nodes() if g.node[n]['party_affiliation'] == 'republican'] inds = [n for n in g.nodes() if g.node[n]['party_affiliation'] == 'independent'] node_size = lambda nid: g.node[nid][args.resize] if args.resize else 300 nx.draw_networkx_nodes(g, pos, nodelist=dems, node_color='blue', node_size=map(node_size, dems)) nx.draw_networkx_nodes(g, pos, nodelist=reps, node_color='red', node_size=map(node_size, reps)) nx.draw_networkx_nodes(g, pos, nodelist=inds, node_color='gray', node_size=map(node_size, inds)) nx.draw_networkx_edges(g, pos, alpha=0.05) plt.show() else: # TODO: Create a script that compiles all external files into the # govtrack file (see virtualenv for details on how to do this). # With that done, create all of the HTML, CSS, and JS files on
def net_plot(title, AAT, theta, Z, r, lambda_A, lambda_R, layout='fruchterman', plotting = True, graphScale=1.0, color_threshold=0.7, *args, **kwargs): """Provide the eigenvector covariances AAT from RESCAL_ALS output and Z the sampled network from one of the netCreate sampling algorithms """ # get system time to name figures time = str(dt.datetime.now().time()) time = time.replace(':','') time = time.replace('.','') # heatmap hm = ncFunctions.heatmap(AAT, plotting=plotting, color_threshold=color_threshold) if plotting: plt.suptitle(r'A(A^T) HAC for Induced Rank = %s, $\lambda_{A}$ = %s, $\lambda_{R}$ = %s ' %(r,lambda_A, lambda_R), fontweight='bold', fontsize=14) plt.savefig(title+'_heatmap_'+time, figsize=(6,6)) # NETWORK # Create networkx graph from Z g = nx.Graph() #add nodes with colors of group for n in np.arange(np.shape(hm['corder'])[0]-1): g.add_node(hm['corder'][n],color=hm['group'][n]) nodeColorList = list(nx.get_node_attributes(g,'color').values()) #add edges with weight of theta (probability the link exists) cardE = len(np.where(Z==1)[1]) edgeList = [(np.where(Z==1)[0][i], np.where(Z==1)[1][i]) for i in np.arange(cardE)] edgeWeightList = theta[np.where(Z==1)] * (2 / max(theta[np.where(Z==1)])) #scaled link prob Pr(Z[i,j]=1) * weight for e in np.arange(len(edgeList)-1): g.add_edge(edgeList[e][0],edgeList[e][1],weight=edgeWeightList[e]) # NODE SIZES # 1. cluster linkage importance #nodesizelist = cluster['linkage'] * (400 / max(cluster['linkage'])) # 2. betweenness centrality (wide range of sizes; very small on periphery) #nodesizelist = np.asarray(list(nx.betweenness_centrality(G,normalized=False).values())) * (400 / max(list(nx.betweenness_centrality(G,normalized=False).values()))) # 3. degree (smaller range of sizes; easier to see on the periphery) nodeSizeList = np.asarray(list(g.degree().values())) * (300 / max(list(g.degree().values()))) #scaled so the largest is size 350 # reproducibility np.random.seed(1) #bc = nx.betweenness_centrality(g) E = len(nx.edges(g)) V = len(g) k = round(E/V,3) #size = np.array(list(bc.values())) * 1000 # here replacing the hierarchical magnitude hm['corder'] fignx = plt.figure(figsize=(6,6)) ## use heatmap color groupings to color nodes and heatmap magnitudes to size nodes if layout == 'spring': nx.draw(g, pos=nx.spring_layout(g, scale=graphScale), node_color=nodeColorList, node_size=nodeSizeList, width=edgeWeightList) elif layout == 'fruchterman': nx.draw(g, pos=nx.fruchterman_reingold_layout(g, scale=graphScale), node_color=nodeColorList, node_size=nodeSizeList, width=edgeWeightList) else: print('Please indicate at a valid layout.') #else: #nx.graphviz_layout(g, prog=graphProg) plt.title('Network Created from Induced Rank = %s \n V = %s, E = %s, <k> = %s'%(r,V,E,k), fontweight='bold', fontsize=14) plt.savefig(title+'_graph_'+time, figsize=(6,6)) #plot log degree sequence degree_sequence=sorted(nx.degree(g).values(),reverse=True) fig3 = plt.figure(figsize=(5,3)) plt.loglog(degree_sequence) plt.title('Log Degree Distribution', fontweight='bold', fontsize=14) return {'cluster':hm, 'graph':g, 'linkage':hm['linkage'], 'group':hm['group']}
def draw_graph(graph, name, gov_out_degree=1): import matplotlib.pyplot as plt gov_nodes = [ node for (node, data) in graph.nodes(data=True) if data['type'] == GOV_ACTOR_TYPE and graph.out_degree(node) > gov_out_degree ] print("Filtered %s --\n\tGov Nodes: %d" % (name, len(gov_nodes))) biz_nodes = [] for node in gov_nodes: biz_nodes += graph.successors(node) print("\tBiz Nodes: %d" % (len(biz_nodes))) # pos = nx.spring_layout(graph, **GRAPH_SETTINGS) pos = nx.fruchterman_reingold_layout(graph, **GRAPH_SETTINGS) # Size gov nodes by out degree out_degrees = graph.out_degree(nbunch=gov_nodes) nx.draw_networkx_nodes(graph, pos, nodelist=gov_nodes, node_color='m', node_size=[val for val in out_degrees.values()]) # Size biz nodes by in degree in_degrees = graph.in_degree(nbunch=biz_nodes) nx.draw_networkx_nodes(graph, pos, nodelist=biz_nodes, node_color='c', node_size=[val for val in in_degrees.values()]) # Filter to only edges connected to gov nodes all_edges = graph.edges(nbunch=gov_nodes, data=True) # Separate the edges with negative and positive tone (stored as weight) edges_positive = [(u, v, d) for (u, v, d) in all_edges if d['tone'] >= 0.0] positive_weights = [d["weight"] for (u, v, d) in edges_positive] pos_min = min(positive_weights) pos_max = max(positive_weights) edges_positive_weights = [scale_weight(d["weight"], pos_min, pos_max) * 2 for (u, v, d) in edges_positive] edges_negative = [(u, v, d) for (u, v, d) in all_edges if d['tone'] < 0.0] negative_weights = [d["weight"] for (u, v, d) in edges_negative] neg_min = min(negative_weights) neg_max = max(negative_weights) edges_negative_weights = [scale_weight(d["weight"], neg_min, neg_max) * 2 for (u, v, d) in edges_negative] # Draw positive tone edges in blue nx.draw_networkx_edges(graph, pos, edgelist=edges_positive, edge_color='b', width=edges_positive_weights, **EDGE_SETTINGS) # Draw negative tone edges in green nx.draw_networkx_edges(graph, pos, edgelist=edges_negative, edge_color='g', width=edges_negative_weights, **EDGE_SETTINGS) # labels labels = {node: node for node in gov_nodes} nx.draw_networkx_labels(graph, pos, labels=labels, font_size=5) plt.axis('off') plt.savefig("results/%s_weighted_graph.pdf" % (name))
def __init__(self, edges, starting_node, ending_node): self.graph = nx.Graph(edges) self.starting_node = starting_node self.ending_node = ending_node self.pos = nx.fruchterman_reingold_layout(self.graph) self.original_path = find_path(self.graph, starting_node, ending_node)