Python networkx.kamada_kawai_layout() Examples

The following are 21 code examples of networkx.kamada_kawai_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: safe_io.py    From safepy with GNU General Public License v3.0 6 votes vote down vote up
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 #2
Source File: networkx.py    From hvplot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw_kamada_kawai(G, **kwargs):
    """Draw networkx graph with circular 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, pos=nx.kamada_kawai_layout, **kwargs) 
Example #3
Source File: basics.py    From HarvestText with MIT License 6 votes vote down vote up
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 #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_plot.py    From scedar with MIT License 5 votes vote down vote up
def test_networkx_graph():
    ng = nx.Graph()
    ng.add_edge(1, 2, weight=1)
    ng.add_edge(1, 3, weight=10)
    return eda.networkx_graph(ng, nx.kamada_kawai_layout(ng),
                              figsize=(5, 5), alpha=1, node_with_labels=True) 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: test_functionality.py    From HarvestText with MIT License 5 votes vote down vote up
def test_build_word_ego_graph():
    sys.stdout, expected = open(get_current_function_name()+"_current","w"), open(get_current_function_name()+"_expected").read()
    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)

    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)


    sys.stdout.close()
    assert open(get_current_function_name() + "_current").read() == expected 
Example #16
Source File: LayoutUtil.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def layout_obs_sub_only(obs, scale=1000.0):
    n_sub = obs.n_sub
    n_line = obs.n_line
    or_sub = obs.line_or_to_subid
    ex_sub = obs.line_ex_to_subid
    
    # Create a graph of substations vertices
    G = nx.Graph()
    
    # Set lines edges
    for line_idx in range(n_line):
        lor_sub = or_sub[line_idx]
        lex_sub = ex_sub[line_idx]
        
        # Compute edge vertices indices for current graph
        left_v = lor_sub
        right_v = lex_sub
        
        # Register edge in graph
        G.add_edge(left_v, right_v)
        
    # Convert our layout to nx format
    initial_layout = {}
    for sub_idx, sub_name in enumerate(obs.name_sub):
        initial_layout[sub_idx] = obs.grid_layout[sub_name]
        
    # Use kamada_kawai algorithm
    kkl = nx.kamada_kawai_layout(G, scale=scale)
    # Convert back to our layout format
    improved_layout = {}
    for sub_idx, v in kkl.items():
        sub_key = obs.name_sub[sub_idx]
        vx = int(np.round(v[0]))
        vy = int(np.round(v[1]))
        improved_layout[sub_key] = [vx, vy]

    return improved_layout 
Example #17
Source File: LayoutUtil.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def layout_obs_sub_only(obs, scale=1000.0):
    n_sub = obs.n_sub
    n_line = obs.n_line
    or_sub = obs.line_or_to_subid
    ex_sub = obs.line_ex_to_subid
    
    # Create a graph of substations vertices
    G = nx.Graph()
    
    # Set lines edges
    for line_idx in range(n_line):
        lor_sub = or_sub[line_idx]
        lex_sub = ex_sub[line_idx]
        
        # Compute edge vertices indices for current graph
        left_v = lor_sub
        right_v = lex_sub
        
        # Register edge in graph
        G.add_edge(left_v, right_v)
        
    # Convert our layout to nx format
    initial_layout = {}
    for sub_idx, sub_name in enumerate(obs.name_sub):
        initial_layout[sub_idx] = obs.grid_layout[sub_name]
        
    # Use kamada_kawai algorithm
    kkl = nx.kamada_kawai_layout(G, scale=scale)
    # Convert back to our layout format
    improved_layout = {}
    for sub_idx, v in kkl.items():
        sub_key = obs.name_sub[sub_idx]
        vx = int(np.round(v[0]))
        vy = int(np.round(v[1]))
        improved_layout[sub_key] = [vx, vy]

    return improved_layout 
Example #18
Source File: test_plot.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_cycle_graph(self, dim):
        """Tests that the length of edges in a circular cycle graph are all of equal length."""
        graph = nx.cycle_graph(dim)
        layout = nx.kamada_kawai_layout(graph)
        coords = plot._edge_coords(graph, layout)
        x = coords["x"]
        y = coords["y"]
        dists = [
            np.sqrt((x[3 * k] - x[3 * k + 1]) ** 2 + (y[3 * k] - y[3 * k + 1]) ** 2)
            for k in range(dim)
        ]
        first_dist = np.sqrt((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2)

        assert np.allclose(dists, first_dist) 
Example #19
Source File: test_plot.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_complete_graph(self, dim):
        """Tests that nodes in a complete graph are located in the unit circle when using the
        Kamada-Kawai layout"""
        graph = nx.complete_graph(dim)
        layout = nx.kamada_kawai_layout(graph)
        coords = plot._node_coords(graph, layout)
        x = coords["x"]
        y = coords["y"]
        radii = [np.sqrt(x[i] ** 2 + y[i] ** 2) for i in range(dim)]

        assert np.allclose(radii, np.ones(dim), atol=1e-5) 
Example #20
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) 
Example #21
Source File: plot.py    From PyPSA with GNU General Public License v3.0 4 votes vote down vote up
def autogenerate_coordinates(n, assign=False, layouter=None):
    """
    Automatically generate bus coordinates for the network graph
    according to a layouting function from `networkx <https://networkx.github.io/>`_.

    Parameters
    ----------
    n : pypsa.Network
    assign : bool, default False
        Assign generated coordinates to the network bus coordinates
        at ``n.buses[['x','y']]``.
    layouter : networkx.drawing.layout function, default None
        Layouting function from `networkx <https://networkx.github.io/>`_. See
        `list <https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_
        of available options. By default coordinates are determined for a
        `planar layout <https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.layout.planar_layout.html#networkx.drawing.layout.planar_layout>`_
        if the network graph is planar, otherwise for a
        `Kamada-Kawai layout <https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.layout.kamada_kawai_layout.html#networkx.drawing.layout.kamada_kawai_layout>`_.

    Returns
    -------
    coordinates : pd.DataFrame
        DataFrame containing the generated coordinates with
        buses as index and ['x', 'y'] as columns.

    Examples
    --------
    >>> autogenerate_coordinates(network)
    >>> autogenerate_coordinates(network, assign=True, layouter=nx.circle_layout)
    """

    G = n.graph()

    if layouter is None:
        is_planar = nx.check_planarity(G)[0]
        if is_planar:
            layouter = nx.planar_layout
        else:
            layouter = nx.kamada_kawai_layout

    coordinates = pd.DataFrame(layouter(G)).T.rename({0: 'x', 1: 'y'}, axis=1)

    if assign:
        n.buses[['x', 'y']] = coordinates

    return coordinates