Python networkx.spectral_layout() Examples

The following are 27 code examples of networkx.spectral_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: networkx.py    From hvplot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw_spectral(G, **kwargs):
    """Draw networkx graph with spectral 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.spectral_layout, **kwargs) 
Example #2
Source File: util.py    From diffpool with MIT License 6 votes vote down vote up
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 #3
Source File: layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def _spectral(A, dim=2):
    # Input adjacency matrix A
    # Uses dense eigenvalue solver from numpy
    try:
        import numpy as np
    except ImportError:
        raise ImportError("spectral_layout() requires numpy: http://scipy.org/ ")
    try:
        nnodes,_=A.shape
    except AttributeError:
        raise nx.NetworkXError(\
            "spectral() takes an adjacency matrix as input")

    # form Laplacian matrix
    # make sure we have an array instead of a matrix
    A=np.asarray(A)
    I=np.identity(nnodes,dtype=A.dtype)
    D=I*np.sum(A,axis=1) # diagonal of degrees
    L=D-A

    eigenvalues,eigenvectors=np.linalg.eig(L)
    # sort and keep smallest nonzero
    index=np.argsort(eigenvalues)[1:dim+1] # 0 index is zero eigenvalue
    return np.real(eigenvectors[:,index]) 
Example #4
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #5
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #6
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_smoke_string(self):
        G = self.Gs
        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.spectral_layout(G)
        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 #7
Source File: layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _spectral(A, dim=2):
    # Input adjacency matrix A
    # Uses dense eigenvalue solver from numpy
    try:
        import numpy as np
    except ImportError:
        msg = "spectral_layout() requires numpy: http://scipy.org/ "
        raise ImportError(msg)
    try:
        nnodes, _ = A.shape
    except AttributeError:
        msg = "spectral() takes an adjacency matrix as input"
        raise nx.NetworkXError(msg)

    # form Laplacian matrix
    # make sure we have an array instead of a matrix
    A = np.asarray(A)
    I = np.identity(nnodes, dtype=A.dtype)
    D = I * np.sum(A, axis=1)  # diagonal of degrees
    L = D - A

    eigenvalues, eigenvectors = np.linalg.eig(L)
    # sort and keep smallest nonzero
    index = np.argsort(eigenvalues)[1:dim + 1]  # 0 index is zero eigenvalue
    return np.real(eigenvectors[:, index]) 
Example #8
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_default_scale_and_center(self):
        sc = self.check_scale_and_center
        c = (0, 0)
        G = nx.complete_graph(9)
        G.add_node(9)
        sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
        sc(nx.spring_layout(G), scale=1, center=c)
        sc(nx.spectral_layout(G), scale=1, center=c)
        sc(nx.circular_layout(G), scale=1, center=c)
        sc(nx.shell_layout(G), scale=1, center=c)
        if self.scipy is not None:
            sc(nx.kamada_kawai_layout(G), scale=1, center=c) 
Example #11
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: editor.py    From GridCal with GNU General Public License v3.0 5 votes vote down vote up
def auto_layout(self):
        """
        Automatic layout of the nodes
        """

        if self.circuit.graph is None:
            self.circuit.compile_snapshot()

        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() 
Example #16
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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.planar_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 #17
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_default_scale_and_center(self):
        sc = self.check_scale_and_center
        c = (0, 0)
        G = nx.complete_graph(9)
        G.add_node(9)
        sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
        sc(nx.spring_layout(G), scale=1, center=c)
        sc(nx.spectral_layout(G), scale=1, center=c)
        sc(nx.circular_layout(G), scale=1, center=c)
        sc(nx.shell_layout(G), scale=1, center=c)
        if self.scipy is not None:
            sc(nx.kamada_kawai_layout(G), scale=1, center=c) 
Example #18
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #19
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_smoke_empty_graph(self):
        G = []
        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.spectral_layout(G)
        vpos = nx.shell_layout(G)
        vpos = nx.bipartite_layout(G, G)
        if self.scipy is not None:
            vpos = nx.kamada_kawai_layout(G) 
Example #20
Source File: test_layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_scale_and_center_arg(self):
        G = nx.complete_graph(9)
        G.add_node(9)
        vpos = nx.random_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spring_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spectral_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        # circular can have twice as big length
        vpos = nx.circular_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))
        vpos = nx.shell_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))

        # check default center and scale
        vpos = nx.random_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spring_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spectral_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.circular_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0))
        vpos = nx.shell_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0)) 
Example #21
Source File: test_layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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 #22
Source File: test_layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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 #23
Source File: test_layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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 #24
Source File: test_layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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 #25
Source File: em_help.py    From mapper-tda with MIT License 5 votes vote down vote up
def plot_graph(G, filename='prova.png', values=None, colorbar_obj=None):
    
    func_types_dic = {
                'spring' : nx.spring_layout,
                'random' : nx.random_layout,
                'shell' : nx.shell_layout,
                'spectral' : nx.spectral_layout,
                'viz' : graphviz_layout
                }

    print(G.edges())
    print(G.nodes())

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)

    color_nodes = [values.get(node, 0.2) for node in G.nodes()] 

    pos = func_types_dic[params.plot_type_str](G)

    nodes = nx.draw_networkx_nodes(G, pos, node_color=color_nodes, \
            alpha=.6)#, cmap=plt.get_cmap('brg'))

    nx.draw_networkx_edges(G, pos, width=2.)
    nx.draw_networkx_labels(G, pos, font_color='k', font_weight='10')
    plt.title("|V| = %d, |E| = %d"%(len(G.nodes()), len(G.edges())))
    colorbar_obj.set_array(color_nodes)
    plt.colorbar(colorbar_obj)
    plt.axis('off')
    fig.savefig(filename, format='png')
    plt.close() 
Example #26
Source File: serializer.py    From koala with GNU General Public License v3.0 5 votes vote down vote up
def plot_graph(self):
    import matplotlib.pyplot as plt

    pos=networkx.spring_layout(self.G,iterations=2000)
    #pos=networkx.spectral_layout(G)
    #pos = networkx.random_layout(G)
    networkx.draw_networkx_nodes(self.G, pos)
    networkx.draw_networkx_edges(self.G, pos, arrows=True)
    networkx.draw_networkx_labels(self.G, pos)
    plt.show() 
Example #27
Source File: lookml_grapher.py    From lookml-tools with Apache License 2.0 4 votes vote down vote up
def plot_graph(self, g, filename, title, node_size=500, label_font_size=12, text_angle=0, image_width=16, image_height=12):
        '''plot the graph and write to file

        Args:
            g (networkx): networkx graph object
            filename (str): path to write image to
            title (str): title to add to chart
            node_size (int): node size 
            label_font_size (int): font size
            text_angle (int): angle to rotate. This is angle in degrees counter clockwise from east 
            image_width (int): width of image in inches 
            image_height (int): heightof image in inches

        Returns:
            nothing but does write image to file

        '''
        # map nodes to a color for their node type
        # https://stackoverflow.com/questions/27030473/how-to-set-colors-for-nodes-in-networkx-python
        color_map = []
        colors = ['#b3cde3', '#ccebc5', '#decbe4', '#FFA500']
        for node in g:
            if self.node_map[node] == NodeType.MODEL:
                color_map.append(colors[0])
            elif self.node_map[node] == NodeType.EXPLORE:
                color_map.append(colors[1])
            elif self.node_map[node] == NodeType.VIEW:
                color_map.append(colors[2])
            else:
                color_map.append(colors[3])

        fig = plt.figure(figsize=(image_width, image_height))
        ax = plt.subplot(111)

        try:
            import pydot
            from networkx.drawing.nx_pydot import graphviz_layout
        except ImportError: # pragma: no cover
            raise ImportError("Requires Graphviz and either PyGraphviz or pydot") # pragma: no cover

        #pos = nx.spring_layout(g)
        #pos = nx.circular_layout(g)
        #pos = nx.kamada_kawai_layout(g)
        #pos = nx.shell_layout(g)
        #pos = nx.spectral_layout(g)
        pos = graphviz_layout(g, prog='dot', seed=42)
        nx.draw(g, pos, node_size=node_size, node_color = color_map, edge_color='#939393', font_size=9, font_weight='bold')

        text = nx.draw_networkx_labels(g, pos, with_labels=False, font_size=label_font_size)
        for _, t in text.items():
            t.set_rotation(text_angle)

        plt.axis('off')
        plt.title(title, fontsize=20)
        plt.tight_layout()
        plt.savefig(filename, format="PNG")
        logging.info("Graph written to %s", filename)