def draw_graph(relationships): G = nx.Graph() add_edges(relationships, G) elarge = [(u, v) for (u, v, d) in G.edges(data=True)] # positions for all nodes pos = nx.spring_layout(G, k=1, seed=1) # nodes nx.draw_networkx_nodes(G, pos, node_size=90, node_color="k") # edges nx.draw_networkx_edges(G, pos, edgelist=elarge, width=0.1, edge_color="b") # labels nx.draw_networkx_labels(G, pos, font_size=0.3, font_family="sans-serif", font_color="w") # no_overwrite("output\\graph", ".pdf") no_overwrite("output\\graph", ".png")
def draw(graph: Graph, components): """Draw the graph showing edge weight :param graph: graph object to draw :param components: tuple of sets, where each set represents a set of nodes """ graph_nx = nx.Graph() graph_nx.add_weighted_edges_from(graph.weighted_edges) labels = nx.get_edge_attributes(graph_nx, 'weight') pos = nx.spring_layout(graph_nx) community_map = get_community_map(components) nx.draw_networkx(graph_nx, pos=pos, with_labels=False, node_size=200, node_shape="o", node_color=list(community_map.values())) plt.get_cmap() plt.axis('off') plt.title(graph.name) plt.show()
def plot_graph(self, name, score): #Import matplotlib, a library used to produce graphic in python. import matplotlib.pyplot as plt from networkx import nx plt.figure(figsize=(7, 7)) # Adjust the window size plt.margins(.2, .2) # Adjust margins #We determine the node position: https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.layout.spring_layout.html position = nx.spring_layout(self.graph) nx.draw_networkx(self.graph, with_labels=True, pos=position) plt.axis('off') # Removing axis #Weights on edges : solution found on stackoverflow #https://stackoverflow.com/questions/28372127/add-edge-weights-to-plot-output-in-networkx labels = nx.get_edge_attributes(self.graph, 'weight') nx.draw_networkx_edge_labels(self.graph, pos=position, edge_labels=labels) plt.title( "fasta alignment graph according to a minimum alignment score of " + str(score)) plt.savefig( name + ".png") # Produce a png file with the graph annotated by default plt.show() nx.write_gexf( self.graph, name + ".gexf") # Produce a gexf file that can be annotated with gephi. return None
def plot(self, filename=None, with_capacity=False, dpi=300): """Plot network topology.""" pos = nx.spring_layout(self.graph) labels = nx.get_edge_attributes(self.graph, "capacity") nx.draw(self.graph, pos, with_labels=True) if with_capacity: nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=labels) if filename: plt.savefig(filename, dpi=dpi)
def showGraph(G, W=None): n = len(G) E = [(i, j) for i in range(n) for j in G[i]] nxG = nx.Graph(E) pos = nx.spring_layout(nxG) nx.draw(nxG, pos, with_labels=True, node_color='yellow', node_size=500) if W is not None: labels = [W[i][k] for i in range(n) for k in range(len(G[i]))] for (i, j), w in zip(E, labels): nxG[i][j]['weight'] = w labels = nx.get_edge_attributes(nxG, 'weight') nx.draw_networkx_edge_labels(nxG, pos, edge_labels=labels) plt.show() return
def save_graph(graph, n, p): #initialze Figure plt.figure(num=None, figsize=(20, 20), dpi=80) plt.axis('off') fig = plt.figure(figsize=(20, 15)) pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos) nx.draw_networkx_edges(graph, pos) nx.draw_networkx_labels(graph, pos) file_name = 'Q7_Assets/ErdosRenyi_N_' + str(n) + '_P_' + str(p) + '.pdf' plt.savefig(file_name, bbox_inches="tight") plt.close(fig) del fig
def draw_graph(self, node_type='', layout=''): if layout == 'spring': pos = nx.spring_layout(self.scgraph.code_graph) if layout == 'spectral': pos = nx.spectral_layout(self.scgraph.code_graph) if layout == 'planar': pos = nx.planar_layout(self.scgraph.code_graph) if layout == 'shell': pos = nx.shell_layout(self.scgraph.code_graph) if layout == 'circular': pos = nx.circular_layout(self.scgraph.code_graph) if layout == 'spiral': pos = nx.spiral_layout(self.scgraph.code_graph) if layout == 'random': pos = nx.random_layout(self.scgraph.code_graph) if node_type == 'cycles': self.scgraph.draw('cycles', layout) if node_type == 'dict': self.scgraph.draw('dict', layout)
def visualize(environment): G = nx.from_numpy_matrix(environment.state_space) print(G.edges(data=True)) color_map = [] for node in G.nodes(): if node in environment.fire_locations: color_map.append('red') elif node in environment.terminal_states: color_map.append('green') else: color_map.append('cyan') nx.draw(G, with_labels=True, node_color=color_map, node_size=[100 for v in G.nodes()], layout=nx.spring_layout(G, scale=1000)) plt.savefig(os.path.join(dir_path, "environment_graph.pdf")) plt.savefig(os.path.join(dir_path, "environment_graph.png"))
def get_concept_network(search_regex_string: str, min_count: int = 1, highlight_regex_string: str = "", nearest_neighbor_count: int = 0) -> str: """Extracts a network of words from vector data in an AI model.""" graph: Graph = Graph() w2v: Word2Vec = Word2Vec.load(Config.PANEGYRICI_LATINI_MODEL_PATH) search_regex: Pattern[str] = re.compile(search_regex_string) keys: List[str] = [x for x in w2v.wv.vocab if search_regex.match(x)] if not nearest_neighbor_count: # adjust the graph size depending on the given parameters to prevent bloating nearest_neighbor_count: int = max( int(100 * (min_count**2) / (1 + len(keys))), 2) keys = [ x for x in keys if all(y.isalpha() for y in x) and w2v.wv.vocab[x].count >= min_count ] edge_color: Tuple[float, float, float] = (0.6, 0.6, 0.6) add_edges(keys, w2v, nearest_neighbor_count, min_count, graph) pos: dict = nx.spring_layout(graph, k=0.7, iterations=100) pyplot.clf() pyplot.subplot() nx.draw(graph, pos, node_size=25, with_labels=True, alpha=1) colors: List[Tuple[float, float, float]] = [] highlight_regex: Pattern[str] = re.compile(highlight_regex_string) for edge in graph.edges: if highlight_regex_string and any( highlight_regex.match(x) for x in edge) and any(search_regex.match(x) for x in edge): colors.append((1, 0, 0)) else: colors.append(edge_color) nx.draw_networkx_edges(graph, pos, alpha=1, edge_color=colors) pyplot.savefig(fname=Config.NETWORK_GRAPH_TMP_PATH, format="svg", bbox_inches="tight") xml_string: str = open(Config.NETWORK_GRAPH_TMP_PATH).read() os.remove(Config.NETWORK_GRAPH_TMP_PATH) svg_string: str = re.findall(r"<svg[\s\S]*?svg>", xml_string)[0] return svg_string
def Plot_network(G, colors): ## Plot graph fig, ax = plt.subplots(figsize = (10,5)) nx.draw(G, node_size=50, node_color=colors, width = 0.2, pos=nx.spring_layout(G, k=0.25, iterations=50), alpha = 0.8) plt.show() degree_sequence = sorted([d for n, d in G.degree()], reverse=True) degreeCount = collections.Counter(degree_sequence) deg, cnt = zip(*degreeCount.items()) fig, ax = plt.subplots(figsize = (10,5)) plt.bar(deg, cnt, width=0.80, color='b') plt.title("Degree Histogram") plt.ylabel("Count") plt.xlabel("Degree") deg_2 = [] for ind, d in enumerate(deg): if ind % 2== 0: deg_2.append(d) ax.set_xticks([d for d in deg_2]) ax.set_xticklabels(deg_2, rotation = 90)
def draw_small_graph(graph): """Draw the graph showing edge weight :param graph: graph object to draw """ graph_nx = nx.Graph() graph_nx.add_weighted_edges_from(graph.weighted_edges) labels = nx.get_edge_attributes(graph_nx, 'weight') pos = nx.spring_layout(graph_nx) nx.draw_networkx_edge_labels(graph_nx, pos=pos, edge_labels=labels) nx.draw(graph_nx, pos=pos, with_labels=True, node_size=10, node_color="skyblue", node_shape="o", alpha=0.5, linewidths=30) plt.title(graph.name) plt.show()
# some properties print("node degree clustering") for v in nx.nodes(G): print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v))) # G.add_edge(0, 3, weight=4) for e in G.edges: a = e[0] b = e[1] w = randint(1, 1) G.add_edge(int(e[0]), int(e[1]), weight=w) # print (a) # Drawing the graph node_pos = nx.spring_layout(G) edge_weight = nx.get_edge_attributes(G, 'weight') # Draw the nodes nx.draw_networkx(G, node_pos, node_color='grey', node_size=100) # Draw the edges nx.draw_networkx_edges(G, node_pos, edge_color='black') # Draw the edge labels nx.draw_networkx_edge_labels(G, node_pos, edge_color='red', edge_labels=edge_weight)
def draw(self, node_type='', layout=''): """ Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices corresponding to the qubit indices for the surface code """ if not node_type in ['cycles', 'dict']: raise ValueError('node_type can be "cycles" or "dict"') if layout == 'spring': pos = nx.spring_layout(self.code_graph) if layout == 'spectral': pos = nx.spectral_layout(self.code_graph) if layout == 'planar': pos = nx.planar_layout(self.code_graph) if layout == 'shell': pos = nx.shell_layout(self.code_graph) if layout == 'circular': pos = nx.circular_layout(self.code_graph) if layout == 'spiral': pos = nx.spiral_layout(self.code_graph) if layout == 'random': pos = nx.random_layout(self.code_graph) # white nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.alpha), node_color='c', node_size=500, alpha=0.3) # vertex nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.sigma), node_color='b', node_size=500, alpha=0.6) # face nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.phi), node_color='r', node_size=500, alpha=0.6) # edges nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5) labels = {} if node_type == 'cycles': ''' label nodes the cycles of sigma, alpha, and phi ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({node})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({node})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({node})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) if node_type == 'dict': ''' label nodes with v, e, f and indices given by node_dict corresponding to qubit indices of surface code ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({self.alpha_dict[node]})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({self.sigma_dict[node]})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({self.phi_dict[node]})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) # plt.axis('off') # plt.savefig("labels_and_colors.png") # save as png plt.show() # display
and report some properties. This graph is sometimes called the Erdős-Rényi graph but is different from G{n,p} or binomial_graph which is also sometimes called the Erdős-Rényi graph. """ import matplotlib.pyplot as plt from networkx import nx n = 10 # 10 nodes m = 20 # 20 edges seed = 20160 # seed random number generators for reproducibility # Use seed for reproducibility G = nx.gnm_random_graph(n, m, seed=seed) # some properties print("node degree clustering") for v in nx.nodes(G): print(f"{v} {nx.degree(G, v)} {nx.clustering(G, v)}") print() print("the adjacency list") for line in nx.generate_adjlist(G): print(line) pos = nx.spring_layout(G, seed=seed) # Seed for reproducible layout nx.draw(G, pos=pos) plt.show()
# graph = nx.read_gml("test_gml") graph = nx.read_weighted_edgelist("8_0.01diamter3_newtest.weighted.edgelist") # some properties print("node degree clustering") for v in nx.nodes(graph): print('%s %d %f' % (v, nx.degree(graph, v), nx.clustering(graph, v))) # print the adjacency list to terminal try: nx.write_adjlist(graph, sys.stdout) except TypeError: nx.write_adjlist(graph, sys.stdout.buffer) node_pos = nx.spring_layout(graph) edge_weight = nx.get_edge_attributes(graph, 'weight') # Draw the nodes nx.draw_networkx(graph, node_pos, node_color='grey', node_size=100) # Draw the edges nx.draw_networkx_edges(graph, node_pos, edge_color='black') # Draw the edge labels nx.draw_networkx_edge_labels(graph, node_pos, edge_color='red', edge_labels=edge_weight) print(edge_weight) print(graph)
Random graph from given degree sequence. """ import matplotlib.pyplot as plt from networkx import nx # Specify seed for reproducibility seed = 668273 z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1] print(nx.is_graphical(z)) print("Configuration model") G = nx.configuration_model( z, seed=seed) # configuration model, seed for reproduciblity degree_sequence = [d for n, d in G.degree()] # degree sequence print(f"Degree sequence {degree_sequence}") print("Degree histogram") hist = {} for d in degree_sequence: if d in hist: hist[d] += 1 else: hist[d] = 1 print("degree #nodes") for d in hist: print(f"{d:4} {hist[d]:6}") pos = nx.spring_layout(G, seed=seed) # Seed layout for reproducibility nx.draw(G, pos=pos) plt.show()