Python networkx.spring_layout() Examples
The following are 30
code examples of networkx.spring_layout().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: svm_utils.py From ilf with Apache License 2.0 | 9 votes |
def draw_wstate_tree(svm): import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import write_dot, graphviz_layout G = nx.DiGraph() pending_list = [svm.root_wstate] while len(pending_list): root = pending_list.pop() for trace, children in root.trace_to_children.items(): for c in children: G.add_edge(repr(root), repr(c), label=trace) pending_list.append(c) # pos = nx.spring_layout(G) pos = graphviz_layout(G, prog='dot') edge_labels = nx.get_edge_attributes(G, 'label') nx.draw(G, pos) nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8) nx.draw_networkx_labels(G, pos, font_size=10) plt.show()
Example #2
Source File: Measurements.py From marve with Apache License 2.0 | 7 votes |
def _build_graph(show=False): """Load word dependencies into graph using networkx. Enables easy traversal of dependencies for parsing particular patterns. One graph is created for each sentence. Args: show (bool): If set to True, labeled visualization of network will be opened via matplotlib for each sentence Returns: None: Global variable G is set from within function """ global G G = nx.Graph() node_labels, edge_labels = {}, {} for idx, dep in enumerate(A.deps): types = ["dependent", "governor"] # nodes, labels for x in types: G.add_node(str(dep[x]), word=dep[x + "Gloss"], pos=A.lookup[dep[x]]["pos"]) node_labels[str(dep[x])] = dep[x + "Gloss"] + " : " + A.lookup[dep[x]]["pos"] # edges, labels G.add_edge(str(dep[types[0]]), str(dep[types[1]]), dep=dep["dep"]) edge_labels[(str(dep[types[0]]), str(dep[types[1]]))] = dep["dep"] if show == True: pos = nx.spring_layout(G) nx.draw_networkx(G, pos=pos, labels=node_labels, node_color="white", alpha=.5) nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) plt.show() ######################################### # Dependency / POS parsing functions #########################################
Example #3
Source File: class_based_visualization.py From Mathematics-of-Epidemics-on-Networks with MIT License | 6 votes |
def plot_network(self, G, status, pos=None, nodelist=None, colordict={'S':'#009a80','I':'#ff2020', 'R':'gray'}, **nx_kwargs): r''' Plots the network in the axes self.networkx_ax. Nodes are colored according to their status. if no ordered nodelist is provided, then the nodes are plotted so that 'I' nodes appear on top, while the order of the 'S' and 'R' nodes is random. When the network is very dense this highlights 'I' nodes and allows the final state to more accurately represent the proportion of nodes having each status. ''' colorlist = [] if pos is None: pos = nx.spring_layout(G) if nodelist is None: nodelist = list(G.nodes()) I_nodes = [node for node in nodelist if status[node] == 'I'] other_nodes = [node for node in nodelist if status[node]!='I'] random.shuffle(other_nodes) nodelist = other_nodes + I_nodes edgelist = list(G.edges()) else: nodeset = set(nodelist) edgelist = [edge for edge in G.edges() if edge[0] in nodeset and edge[1] in nodeset] for node in nodelist: colorlist.append(colordict[status[node]]) nx.draw_networkx_edges(G, pos, edgelist=edgelist, ax = self.network_axes, **nx_kwargs) nx.draw_networkx_nodes(G, pos, nodelist = nodelist, node_color=colorlist, ax=self.network_axes, **nx_kwargs) self.network_axes.set_xticks([]) self.network_axes.set_yticks([])
Example #4
Source File: networkx.py From hvplot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def draw_spring(G, **kwargs): """Draw networkx graph with spring layout. Parameters ---------- G : graph A networkx graph kwargs : optional keywords See hvplot.networkx.draw() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. Returns ------- graph : holoviews.Graph or holoviews.Overlay Graph element or Graph and Labels """ return draw(G, nx.spring_layout, **kwargs)
Example #5
Source File: test_layout.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
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) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G) vpos = nx.kamada_kawai_layout(G, dim=1)
Example #6
Source File: safe_io.py From safepy with GNU General Public License v3.0 | 6 votes |
def apply_network_layout(G, layout='kamada_kawai', verbose=True): if layout == 'kamada_kawai': if verbose: print('Applying the Kamada-Kawai network layout... (may take several minutes)') pos = nx.kamada_kawai_layout(G) elif layout == 'spring_embedded': if verbose: print('Applying the spring-embedded network layout... (may take several minutes)') pos = nx.spring_layout(G, k=0.2, iterations=100) for n in G: G.nodes[n]['x'] = pos[n][0] G.nodes[n]['y'] = pos[n][1] return G
Example #7
Source File: util.py From diffpool with MIT License | 6 votes |
def plot_graph(plt, G): plt.title('num of nodes: '+str(G.number_of_nodes()), fontsize = 4) parts = community.best_partition(G) values = [parts.get(node) for node in G.nodes()] colors = [] for i in range(len(values)): if values[i] == 0: colors.append('red') if values[i] == 1: colors.append('green') if values[i] == 2: colors.append('blue') if values[i] == 3: colors.append('yellow') if values[i] == 4: colors.append('orange') if values[i] == 5: colors.append('pink') if values[i] == 6: colors.append('black') plt.axis("off") pos = nx.spring_layout(G) # pos = nx.spectral_layout(G) nx.draw_networkx(G, with_labels=True, node_size=4, width=0.3, font_size = 3, node_color=colors,pos=pos)
Example #8
Source File: test_layout.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
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.planar_layout(G, center=(1, 1)) assert_equal(vpos, {}) vpos = nx.bipartite_layout(G, G) 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, {})
Example #9
Source File: igp_graph.py From FibbingNode with GNU General Public License v2.0 | 6 votes |
def draw_graph(graph, output): """If matplotlib is available, draw the given graph to output file""" try: layout = nx.spring_layout(graph) metrics = { (src, dst): data['metric'] for src, dst, data in graph.edges_iter(data=True) } nx.draw_networkx_edge_labels(graph, layout, edge_labels=metrics) nx.draw(graph, layout, node_size=20) nx.draw_networkx_labels(graph, layout, labels={n: n for n in graph}) if os.path.exists(output): os.unlink(output) plt.savefig(output) plt.close() log.debug('Graph of %d nodes saved in %s', len(graph), output) except: pass
Example #10
Source File: basics.py From HarvestText with MIT License | 6 votes |
def build_word_ego_graph(): import networkx as nx import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体) plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题) from harvesttext import get_sanguo, get_sanguo_entity_dict, get_baidu_stopwords ht0 = HarvestText() entity_mention_dict, entity_type_dict = get_sanguo_entity_dict() ht0.add_entities(entity_mention_dict, entity_type_dict) sanguo1 = get_sanguo()[0] stopwords = get_baidu_stopwords() docs = ht0.cut_sentences(sanguo1) G = ht0.build_word_ego_graph(docs,"刘备",min_freq=3,other_min_freq=2,stopwords=stopwords) pos = nx.kamada_kawai_layout(G) nx.draw(G,pos) nx.draw_networkx_labels(G,pos) plt.show() G = ht0.build_entity_ego_graph(docs, "刘备", min_freq=3, other_min_freq=2) pos = nx.spring_layout(G) nx.draw(G, pos) nx.draw_networkx_labels(G, pos) plt.show()
Example #11
Source File: test_viz_network.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_nx_cluster(self): g = nx.karate_club_graph() coms = algorithms.louvain(g) pos = nx.spring_layout(g) viz.plot_network_clusters(g, coms, pos) plt.savefig("cluster.pdf") os.remove("cluster.pdf") coms = algorithms.demon(g, 0.25) pos = nx.spring_layout(g) viz.plot_network_clusters(g, coms, pos, plot_labels=True, plot_overlaps=True) plt.savefig("cluster.pdf") os.remove("cluster.pdf")
Example #12
Source File: MinDisagreeClusterByComponent.py From SDA with MIT License | 6 votes |
def AddLayoutPreCC(g): pos = ABPUtils.BuildLayoutArray(g) if pos is None and len(g.nodes()) > 0: pos = nx.spring_layout(g, k=1/math.sqrt(len(g.nodes())), weight=math.sqrt(len(g.nodes())), scale=100, iterations=1000) if pos is not None: nx.set_node_attributes(g, 'x', dict(zip(g.nodes(), [pos[n][0] for n in g.nodes()]))) nx.set_node_attributes(g, 'y', dict(zip(g.nodes(), [pos[n][1] for n in g.nodes()]))) #starts = args.starts #scores = {} #scoreVals = [] #for idx in range(starts):
Example #13
Source File: gengraph.py From GenGraph with GNU General Public License v3.0 | 6 votes |
def plot_subgraph(self, region_start, region_stop, seq_name, neighbours=0): """ Return a plot of a sub-graph from a defined region with positions relative to some of the sequences. :param region_start: Start position (bp) :param region_stop: Stop position (bp) :param seq_name: Sequence ID that the bp positions are relative to. :param neighbours: Number of neighbours to be included. Currently testing, only 1 level available. :return: Plots a netowrkx + matplotlib figure of the region subgraph. """ sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours) pos = nx.spring_layout(sub_graph) nx.draw_networkx_nodes(sub_graph, pos, cmap=plt.get_cmap('jet'), node_size=300) nx.draw_networkx_labels(sub_graph, pos) nx.draw_networkx_edges(sub_graph, pos, arrows=True) plt.show()
Example #14
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_center_wrong_dimensions(self): G = nx.path_graph(1) assert_raises(ValueError, nx.random_layout, G, center=(1, 1, 1)) assert_raises(ValueError, nx.circular_layout, G, center=(1, 1, 1)) assert_raises(ValueError, nx.spring_layout, G, center=(1, 1, 1)) assert_raises(ValueError, nx.fruchterman_reingold_layout, G, center=(1, 1, 1)) assert_raises(ValueError, nx.fruchterman_reingold_layout, G, dim=3, center=(1, 1)) assert_raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1)) assert_raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1)) assert_raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
Example #15
Source File: test_pylab.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
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()
Example #16
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
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) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
Example #17
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
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, {})
Example #18
Source File: plot.py From tropycal with MIT License | 5 votes |
def plot_nhc_labels(self, ax, x, y, labels, k=0.01): G = nx.DiGraph() data_nodes = [] init_pos = {} for xi, yi, label in zip(x, y, labels): data_str = 'data_{0}'.format(label) G.add_node(data_str) G.add_node(label) G.add_edge(label, data_str) data_nodes.append(data_str) init_pos[data_str] = (xi, yi) init_pos[label] = (xi, yi) pos = nx.spring_layout(G, pos=init_pos, fixed=data_nodes, k=k) # undo spring_layout's rescaling pos_after = np.vstack([pos[d] for d in data_nodes]) pos_before = np.vstack([init_pos[d] for d in data_nodes]) scale, shift_x = np.polyfit(pos_after[:,0], pos_before[:,0], 1) scale, shift_y = np.polyfit(pos_after[:,1], pos_before[:,1], 1) shift = np.array([shift_x, shift_y]) for key, val in pos.items(): pos[key] = (val*scale) + shift start = False for label, data_str in G.edges(): if start == False: start = True continue self.ax.annotate(label, xy=pos[data_str], xycoords='data', xytext=pos[label], textcoords='data', fontweight='bold', ha='center', va='center', arrowprops=dict(arrowstyle="-",#-> shrinkA=0, shrinkB=0, connectionstyle="arc3", color='k'), transform=ccrs.PlateCarree())
Example #19
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
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(G.to_directed()) vpos = nx.spectral_layout(self.bigG) vpos = nx.spectral_layout(self.bigG.to_directed()) vpos = nx.shell_layout(G) if self.scipy is not None: vpos = nx.kamada_kawai_layout(G)
Example #20
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
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)
Example #21
Source File: nx_pylab.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def draw_spring(G, **kwargs): """Draw the graph G with a spring layout. Parameters ---------- G : graph A networkx graph kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. """ draw(G, spring_layout(G), **kwargs)
Example #22
Source File: test_layout.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_scale_and_center_arg(self): sc = self.check_scale_and_center c = (4, 5) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5)) # rest can have 2*scale length: [-scale, scale] sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c) if self.scipy is not None: sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
Example #23
Source File: graph.py From interact with MIT License | 5 votes |
def plot_graph( interactions, pos=None, node_color='orange', edge_color='black', title='', fixed_weight=None, weight_offset=1, weight_factor=4, layout='spring_layout', layout_parameters={}, figsize=(12, 12), output_filepath='' ): """Plot graph from list of pandas df with interactions.""" G = nx.Graph() G.add_weighted_edges_from(interactions.to_records(index=False)) weights = [ ( fixed_weight if fixed_weight is not None else (weight_offset + G[u][v]['weight']) * weight_factor ) for u, v in G.edges() ] if pos is None: pos = layout_factory[layout](G, **layout_parameters) plt.figure(figsize=figsize) plt.title(title) nx.draw( G, pos=pos, node_color=node_color, width=weights, edge_color=edge_color ) nx.draw_networkx_labels( G, pos=pos, bbox=dict( boxstyle='round', ec=(0.0, 0.0, 0.0), alpha=0.9, fc=node_color, lw=1.5 ) ) if output_filepath: plt.savefig(output_filepath, bbox_inches='tight') return pos
Example #24
Source File: plotting.py From metaknowledge with GNU General Public License v2.0 | 5 votes |
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')
Example #25
Source File: test_layout.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_spring_args(self): G = nx.complete_graph(9) vpos = nx.spring_layout(G, dim=3) assert_equal(vpos[0].shape, (3,)) vpos = nx.spring_layout(G, fixed=[0,1], pos={1:(0,0), 2:(1,1)}) vpos = nx.spring_layout(G, k=2, fixed=[0,1], pos={1:(0,0), 2:(1,1)}) vpos = nx.spring_layout(G, scale=3, center=(2,5)) vpos = nx.spring_layout(G, scale=3) vpos = nx.spring_layout(G, center=(2,5))
Example #26
Source File: test_layout.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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))
Example #27
Source File: test_layout.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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))
Example #28
Source File: test_layout.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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)
Example #29
Source File: test_layout.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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.spectral_layout(G) vpos=nx.spectral_layout(self.bigG) vpos=nx.shell_layout(G)
Example #30
Source File: nx_pylab.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def draw_spring(G, **kwargs): """Draw the graph G with a spring layout. Parameters ---------- G : graph A networkx graph kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. """ draw(G, spring_layout(G), **kwargs)