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

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

项目:honeyd-python    作者:sookyp    | 项目源码 | 文件源码
def network():
    global network_graph
    try:
        graph_json = request.json
    except IndexError:
        pass

    # some network nodes could be removed from the graph to avoid confusing the user
    # the graph contains 
    network_json = loads(graph_json)
    G = json_graph.node_link_graph(network_json)
    fig = plt.figure()
    plt.axis('off')
    networkx.draw_networkx(G, node_size=80, node_color='c', font_size=8)
    network_graph = BytesIO()
    fig.savefig(network_graph, format='png')

# redirect any attempts to non-existing pages to the main page
项目:taikutsu_blog_works    作者:hokekiyoo    | 项目源码 | 文件源码
def graph_visualize(G, args):
    import networkx as nx
    import numpy as np
    # ???????????????????????????
    pos = nx.spring_layout(G)
    # ?????? ????????????????????
    plt.figure()
    nx.draw_networkx(G, pos, with_labels=False, alpha=0.4,font_size=0.0,node_size=10) 
    plt.savefig(args.directory+"/graph/graph.png")
    nx.write_gml(G, args.directory+"/graph/graph.gml")
    # ??????
    plt.figure() 
    degree_sequence=sorted(nx.degree(G).values(),reverse=True) 
    dmax=max(degree_sequence) 
    dmin =min(degree_sequence)
    kukan=range(0,dmax+2) 
    hist, kukan=np.histogram(degree_sequence,kukan)
    plt.plot(hist,"o-")
    plt.xlabel('degree') 
    plt.ylabel('frequency')
    plt.grid()
    plt.savefig(args.directory+'/graph/degree_hist.png')
项目:GEM    作者:palash1992    | 项目源码 | 文件源码
def plot_embedding2D(node_pos, node_colors=None, di_graph=None):
    node_num, embedding_dimension = node_pos.shape
    if(embedding_dimension > 2):
        print("Embedding dimension greater than 2, use tSNE to reduce it to 2")
        model = TSNE(n_components=2)
        node_pos = model.fit_transform(node_pos)

    if di_graph is None:
        # plot using plt scatter
        plt.scatter(node_pos[:, 0], node_pos[:, 1], c=node_colors)
    else:
        # plot using networkx with edge structure
        pos = {}
        for i in range(node_num):
            pos[i] = node_pos[i, :]
        if node_colors:
            nx.draw_networkx_nodes(di_graph, pos,
                                   node_color=node_colors,
                                   width=0.1, node_size=100,
                                   arrows=False, alpha=0.8,
                                   font_size=5)
        else:
            nx.draw_networkx(di_graph, pos, node_color=node_colors,
                             width=0.1, node_size=300, arrows=False,
                             alpha=0.8, font_size=12)
项目:ride    作者:KyleBenson    | 项目源码 | 文件源码
def draw_overlaid_graphs(original, new_graphs, print_text=False):
    """
    Draws the new_graphs as graphs overlaid on the original topology
    :type new_graphs: list[nx.Graph]
    """
    import matplotlib.pyplot as plt

    layout = nx.spring_layout(original)
    nx.draw_networkx(original, pos=layout)
    # want to overlay edges in different colors and progressively thinner
    # so that we can see what edges are in a tree
    line_colors = 'rbgycm'
    line_width = 2.0 ** (min(len(new_graphs), len(line_colors)) - 1)  # use this for visualising on screen
    # line_width = 3.0 ** (min(len(new_graphs), len(line_colors)) - 1)  # use this for generating diagrams
    for i, g in enumerate(new_graphs):
        if print_text:
            log.info(nx.info(g))
            log.info("edges:", list(g.edges()))
        nx.draw_networkx(g, pos=layout, edge_color=line_colors[i % len(line_colors)], width=line_width)
        # advance to next line width
        line_width /= 1.7  # use this for visualising on screen
        # line_width /= 2.0  # use this for generating diagrams
    plt.show()
项目: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
项目:NetworkScraper    作者:RLesser    | 项目源码 | 文件源码
def graphNetworkx(self, buds_visible = False, filter_assym_edges = False, labels_visible = True, iterations = 1000):
        self.buds_visible = buds_visible
        self.filter_assym_edges = filter_assym_edges
        G = self.makeGraphData()
        if hasattr(self, 'nodeColorInfo'):
            nodeColors = self.useColorData(G, 'networkx')
        #print G.node
        if labels_visible:
            nx.draw_networkx(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1)
        else:
            nx.draw(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1)
        plt.show()
项目:pyBN    作者:ncullen93    | 项目源码 | 文件源码
def plot_nx(bn,**kwargs):
    """
    Draw BayesNet object from networkx engine
    """
    g = nx.DiGraph(bn.E)
    pos = graphviz_layout(g,'dot')
    #node_size=600,node_color='w',with_labels=False
    nx.draw_networkx(g,pos=pos, **kwargs)
    plt.axis('off')
    plt.show()
项目:marve    作者:khundman    | 项目源码 | 文件源码
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
#########################################
项目:Networks    作者:dencesun    | 项目源码 | 文件源码
def draw_network(DG):
    nx.draw_networkx(DG, pos=nx.spring_layout(DG), node_color = 'red')
    plt.axis('off') # turn off axis
    plt.savefig('c-elegans.svg')
    # plt.show()
项目:Networks    作者:dencesun    | 项目源码 | 文件源码
def centrality(DG):
    in_degree_centrality = nx.in_degree_centrality(DG)
    out_degree_centrality = nx.out_degree_centrality(DG)
    with open('/home/sun/PycharmProjects/Network/in_degree_centrality.csv', 'w') as f:
        for k, v in in_degree_centrality.items():
            f.write(str(k) + ': ' + str(v) + '\n')
        f.close()

    with open('/home/sun/PycharmProjects/Network/out_degree_centrality.csv', 'w') as f:
        for k, v in out_degree_centrality.items():
            f.write(str(k) + ': ' + str(v) + '\n')
        f.close()


# def main():
#     data = '/home/sun/PycharmProjects/Network/C-elegans-frontal.txt'
#     # data = 'www.adj'
#     DG = create_network(data)
#
#     # draw_network(DG)
#     # clustering_coefficient(DG)
#     # centrality(DG)
#     degree_distribution(DG)
#
# if __name__ == '__main__':
#     main()
#
#     # DG = nx.DiGraph()
#     # DG.add_edge(1,2)
#     # print(DG.edges())
#     # # pos = nx.nx_agraph.graphviz_layout(DG)
#     # nx.draw_networkx(DG, pos = nx.spring_layout(DG))
#     # plt.show()
#     # plt.ishold()
#     # plt.draw(DG)
项目: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
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def plotgraph(g):
    """Plot a grid graph, using (i,j) node labels as positions"""
    plt.figure(figsize=fig_size)
    positions = dict(zip(g.nodes(),g.nodes()))
    nx.draw_networkx(g,positions,with_labels=False,node_size=50)


# plotting of measurement results:
项目:nodeembedding-to-communityembedding    作者:andompesta    | 项目源码 | 文件源码
def graph_plot(G,
               graph_name,
               nodes_color_fn=_pos_coloring,
               node_position_path="./data",
               node_position_file=True,
               show=True):

    if node_position_file:
        spring_pos = pickle.load(open(path_join(node_position_path, graph_name, 'node_pos.bin'), "rb"))
    else:
        spring_pos = nx.spring_layout(G)
        pickle.dump(spring_pos, open(path_join(node_position_path, graph_name, 'node_pos.bin'), "wb"))

    spring_pos_values = np.array(list(spring_pos.values()))
    norm_pos = np.linalg.norm(spring_pos_values, axis=1)
    nodes_color = nodes_color_fn(G, norm_pos)

    plt.figure(figsize=(5, 5))
    plt.axis("off")
    nx.draw_networkx(G, node_color=nodes_color, pos=spring_pos, camp=plt.get_cmap(CAMP), nodelist=sorted(G.nodes()))

    if show:
        plt.show()
    else:
        plt.clf()
        plt.close()

    return nodes_color
项目:Topsorter    作者:hanfang    | 项目源码 | 文件源码
def drawDAG(self, chr):
        """
        draw a dag
        :param chr: chromosome name (str)
        :return: on disk
        """
        labels = {}
        for node in self.orders[chr]:
            #labels[node] = node[3]
            if node.data[1] != "REF":
                if node.data[1] == "DEL":
                    labels[node] = "-"
                elif node.data[1] == "DUP" or node.data[1] == "DUP_COPY":
                    labels[node] = "+"
                elif node.data[1] == "INV":
                    labels[node] = "~"
                else:
                    labels[node] = ">"
            else:
                labels[node] = " "
        sourceNode = self.orders[chr][0]
        sinkNode = self.orders[chr][-1]
        labels[sourceNode] = "Source"
        labels[sinkNode] = "Sink"
        # extract dag for each chr
        dag = self.DAGs[chr]
        pos = self.hierarchy_pos(dag, sourceNode)
        plt.figure()
        nx.draw_networkx(dag, pos=pos, node_size=30, labels=labels, font_size = 4)#, with_labels=False, arrows=False)
        plt.title(chr)
        plt.axis('off')
        plt.gcf()
        plt.savefig(self.prefix + "/DAGs/dag." + chr + ".pdf")
        plt.clf()
        plt.close()
项目:pypers    作者:frankosan    | 项目源码 | 文件源码
def plot(self, file_name=None):
        """
        Plot the DAG of the pipeline
        """
        import matplotlib.pyplot as plt
        nx.draw_networkx(self.dag)
        if not file_name:
            file_name = os.path.join(self.output_dir, self.name + '.png')
        plt.savefig(file_name)
项目:latenttrees    作者:kaltwang    | 项目源码 | 文件源码
def draw_axes(self, ax=None, id_highlight=None):
        # plt.ion()  # interactive mode on (doesn't work with pycharm)
        g = self.__nxgraph
        # new call format for networkx 1.11 (uses pygraphviz, which does not support Python 3!)
        # pos = nx.drawing.nx_agraph.graphviz_layout(g, prog='dot')
        # old call format for networkx 1.10
        # pos = nx.graphviz_layout(g, prog='dot')
        # new call format for networkx 1.11 (uses pydot)
        pos = nx.drawing.nx_pydot.graphviz_layout(g, prog='dot')

        if ax is None:
            ax = self.get_axes(self.id_axes)
        assert len(ax) == self.required_axes

        nx.draw(g, pos, ax=ax[0], hold=True, with_labels=True, arrows=True)
        # nx.draw_networkx(self.__graph)

        # plot the roots
        if id_highlight is None:
            id_highlight = self.__id_roots
        for r in id_highlight:
            ax[0].scatter(pos[r][0], pos[r][1], s=500)

        for id_node, node in self.nodes_iter(data=True):
            c = "{}".format(node.layer)
            ax[0].text(pos[id_node][0], pos[id_node][1], "\n" + c, va='top', ha='center', color='blue')

        # plt.show()  # this call blocks further execution until window is closed
项目:pythia    作者:elazarg    | 项目源码 | 文件源码
def draw(g: nx.DiGraph):
    import matplotlib.pyplot as plt
    nx.draw_networkx(g, with_labels=True)
    plt.show()
项目:BlueLines    作者:JacksYou    | 项目源码 | 文件源码
def network(self, type, start, end, factor=1.0, color=None, src=None):
        """create network of crimes

        Args: 
            type: data type
            start: start character
            end: end character
            factor: size, default 1
            color: colour, default None
            src: default None
        """
        self.load()
        df = pd.read_sql_query(con=self.con, sql=GEN_SEARCH_QUERY.format("Data", "Type = '{0}' "
                                                                            "AND Latitude is NOT NULL "
                                                                            "AND Longitude is NOT NULL "
                                                                            "AND date(Date) > date('{1}') "
                                                                            "AND date(Date) <= date('{2}')".format(type,
                                                                                                                   start,
                                                                                                                   end)))


        dg = nx.Graph()
        queue = deque()
        crimes = [Vertex(row["Case"], row["Type"], row["Longitude"], row["Latitude"]) for index, row in df.iterrows()]
        if len(crimes) == 0:
            print("none found")
            return
        copy = [vertex for vertex in crimes]
        if src is None:
            queue.append(crimes[0])
        else:
            queue.append(list(filter(lambda x: x.id == src, crimes)))

        visited = []
        for crime in crimes:
            dg.add_node(crime.id)
        while len(queue) > 0:
            current = queue.popleft()
            crimes.remove(current)
            for crime in crimes:
                if crime.distance_to(current) < factor and crime not in visited:
                    dg.add_edge(current.id, crime.id, weight=crime.distance_to(current))
                    queue.append(crime)
                    visited.append(crime)
            visited.append(current)
            if len(queue) == 0 and len(crimes) > 0:
                queue.append(crimes[0])


        pos = {copy[i].id: self.base_map(copy[i].lon, copy[i].lat) for i in range(len(copy))}

        if color is None:
            color = "red"
        nx.draw_networkx(dg, pos=pos, node_size=5, with_labels=False, ax=self.ax, node_color=color)

        plt.show()