Python networkx 模块,shell_layout() 实例源码

我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用networkx.shell_layout()

项目:ride    作者:KyleBenson    | 项目源码 | 文件源码
def draw(self, label_nodes=False):
        """Draw the graph using matplotlib in a color-coordinated manner."""
        try:
            import matplotlib.pyplot as plt
            print 'Node colors: red=core, blue=major-building, green=distribution, yellow=minor-building, cyan=server,' \
                  ' magenta=host, black=floor-switch, white=rack-switch, white=cloud, green=gateway'
            # TODO: ignore building internals?
            colormap = {'c': 'r', 'b': 'b', 'd': 'g', 'm': 'y', 's': 'c', 'h': 'm', 'f': 'k', 'r': 'w', 'x': 'w', 'g': 'g'}
            node_colors = [colormap[node[0]] for node in self.topo.nodes()]
            # shell layout places nodes as a series of concentric circles
            positions = nx.shell_layout(self.topo, [self.core_nodes,
                                                    # sort the building routers by degree in attempt to get ones connected to each other next to each other
                                                    sorted(self.major_building_routers, key=lambda n: nx.degree(self.topo, n)) + self.distribution_routers + self.server_nodes,
                                                    self.hosts + self.minor_building_routers])
            # then do a spring layout, keeping the inner nodes fixed in positions
            positions = nx.spring_layout(self.topo, pos=positions, fixed=self.core_nodes + self.server_nodes + self.major_building_routers + self.distribution_routers)
            nx.draw(self.topo, node_color=node_colors, pos=positions, with_labels=label_nodes)
            plt.show()
        except ImportError:
            print "ERROR: couldn't draw graph as matplotlib.pyplot couldn't be imported!"
项目:dankdungeon    作者:d4rch0n    | 项目源码 | 文件源码
def save(self, path='out.png'):
        import networkx
        import matplotlib.pyplot as plt
        pos = networkx.spring_layout(self.graph, iterations=500)
        # pos = networkx.spectral_layout(self.graph)
        # pos = networkx.shell_layout(self.graph)
        # pos = networkx.fruchterman_reingold_layout(self.graph)
        nodelist = list(range(self.num_rooms))
        networkx.draw_networkx_nodes(self.graph, pos, nodelist=nodelist)
        edgelist = sorted(self.edges - self.secret_edges)
        secret = sorted(self.secret_edges)
        networkx.draw_networkx_edges(self.graph, pos, edgelist=edgelist,
                                     edge_color='k')
        networkx.draw_networkx_edges(self.graph, pos, edgelist=secret,
                                     edge_color='r')
        networkx.draw_networkx_labels(self.graph, pos, self.labels)
        plt.savefig(path)
项目:GOApy    作者:leopepe    | 项目源码 | 文件源码
def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True):
        import matplotlib.pyplot as plt
        # pos = nx.spring_layout(self.graph)
        pos = nx.shell_layout(self.graph, dim=1024, scale=0.5)
        # pos = nx.random_layout(self.graph, dim=1024, scale=0.5)

        if label_edges:
            edge_labels = {
                (edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True)
            }
            nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5)

        if label_nodes:
            labels = {node[0]: node[1] for node in self.graph.nodes(data=True)}
            nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8)

        # nx.draw(self.graph, with_labels=True, arrows=True, node_size=80)
        nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80)
        plt.savefig(file_name, dpi=1024)
项目:GraphTime    作者:GlooperLabs    | 项目源码 | 文件源码
def draw(self, layout='circular', figsize=None):
        """Draw all graphs that describe the DGM in a common figure

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        rocls = np.ceil(np.sqrt(len(self.graphs)))
        for i, graph in enumerate(self.graphs):
            ax = fig.add_subplot(rocls, rocls, i+1)
            ax.set_title('Graph ' + str(i+1))
            ax.axis('off')
            ax.set_frame_on(False)
            g = graph.nxGraph
            weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
            nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                             width=2, edge_color=weights)
        return fig
项目:GraphTime    作者:GlooperLabs    | 项目源码 | 文件源码
def draw(self, layout='circular', figsize=None):
        """Draw graph in a matplotlib environment

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(1, 1, 1)
        ax.axis('off')
        ax.set_frame_on(False)
        g = self.nxGraph
        weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
        nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                         width=2, edge_color=weights)
        return fig
项目:STAR-SEQR    作者:ExpressionAnalysis    | 项目源码 | 文件源码
def prune_homology_graph(df, chim_dir):
    to_remove = []
    df['brk_left_cut'] = df['name'].str.split(":").str[0:3].str.join(sep=":")
    df['brk_right_cut'] = df['name'].str.split(":").str[3:6].str.join(sep=":")
    left_nodes = set(df[df['brk_left_cut'].duplicated()]['brk_left_cut'])
    right_nodes = df[df['brk_right_cut'].duplicated()]['brk_right_cut']
    all_nodes = list(zip(left_nodes, itertools.repeat("left"))) + list(zip(right_nodes, itertools.repeat("right")))
    for node, hom_side in all_nodes:
        node_members = df[((df['brk_' + hom_side + '_cut'] == node))]['name']
        node_graph = nx.Graph()
        node_graph.add_nodes_from(node_members, exprs=10)
        for jxn1, jxn2 in itertools.combinations(node_members, 2):
            pair_score = get_pairwise_hom(jxn1, jxn2, chim_dir, hom_side)
            if pair_score != 0:
                node_graph.add_edge(jxn1, jxn2, weight=pair_score)
        # nx.draw_networkx(node_graph, pos=nx.shell_layout(node_graph), node_size=100)
        # plt.show()
        adj_mat = nx.to_pandas_dataframe(node_graph)
        node_compare = adj_mat[adj_mat.sum()> 0].index.tolist()
        if len(node_compare) > 0:
            node_homdf = df[df['name'].isin(node_compare)][['name', 'TPM_Fusion', 'TPM_Left', 'TPM_Right']].set_index('name')
            node_homdf['max_pairs'] = node_homdf[['TPM_Left','TPM_Right']].max(axis=1)
            node_homdf = node_homdf.sort_values(['TPM_Fusion', 'max_pairs'] , ascending=False)
            node_remove = node_homdf.iloc[1:].index.tolist()
            to_remove.extend(node_remove)
    # use list of to_remove to mark homologous fusions
    return to_remove