Python networkx.draw_networkx() Examples

The following are 29 code examples of networkx.draw_networkx(). 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: Measurements.py    From marve with Apache License 2.0 7 votes vote down vote up
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 #2
Source File: visualize_embedding.py    From GEM with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_embedding2D(node_pos, node_colors=None, di_graph=None, labels=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 is not None:
            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, labels=labels)
        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, labels=labels) 
Example #3
Source File: drawing.py    From markov_clustering with MIT License 6 votes vote down vote up
def draw_graph(matrix, clusters, **kwargs):
    """
    Visualize the clustering
    
    :param matrix: The unprocessed adjacency matrix
    :param clusters: list of tuples containing clusters as returned
                     by 'get_clusters'
    :param kwargs: Additional keyword arguments to be passed to
                   networkx.draw_networkx
    """
    # make a networkx graph from the adjacency matrix
    graph = nx.Graph(matrix)
    
    # map node to cluster id for colors
    cluster_map = {node: i for i, cluster in enumerate(clusters) for node in cluster}
    colors = [cluster_map[i] for i in range(len(graph.nodes()))]
    
    # if colormap not specified in kwargs, use a default
    if not kwargs.get("cmap", False):
        kwargs["cmap"] = cm.tab20
    
    # draw
    nx.draw_networkx(graph, node_color=colors, **kwargs)
    axis("off")
    show(block=False) 
Example #4
Source File: pathways.py    From CatKit with GNU General Public License v3.0 6 votes vote down vote up
def plot_reaction_network(self, file_name=None):
        """Plot the reaction network present in the database."""

        pathways = []
        load_paths = self.load_pathways()
        for path in load_paths:
            for R in path[:2]:
                for P in path[2:]:
                    if R and P:
                        pathways += [[R, P]]

        network = nx.Graph(pathways)

        plt.figure(figsize=(6, 6))
        nx.draw_networkx(network)
        plt.draw()
        plt.axis('off')

        if file_name:
            plt.savefig(file_name)
        plt.close() 
Example #5
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 #6
Source File: simulation_investigation.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def set_pos(self, pos):
        r'''Set the position of the nodes.
        
        :Arguments: 
        **pos** (dict)
            as in ``nx.draw_networkx``
        '''
        self.pos = pos 
Example #7
Source File: graphs.py    From PyCV-time with MIT License 5 votes vote down vote up
def buildGraph(simList, plot=False):
	g = distanceGraph(simList)
	trim(g, 0.15)

	#mst = nx.minimum_spanning_tree(g.to_undirected())
	#el = [(i, o, w) for (i, o, w) in g.edges_iter(data=True)  
	#                    if (i, o) in mst.edges() 
	#        			or (o, i) in mst.edges()]
	#g = nx.DiGraph()
	#g.add_edges_from(el)
	if plot:
		nx.draw_networkx(g, with_labels = True)
		plt.show()
	return json.dumps(json_graph.node_link_data(g)) 
Example #8
Source File: test_pylab.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multigraph_edgelist_tuples(self):
        # See Issue #3295
        G = nx.path_graph(3, create_using=nx.MultiDiGraph)
        nx.draw_networkx(G, edgelist=[(0, 1, 0)])
        nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20]) 
Example #9
Source File: plot.py    From pyBN with MIT License 5 votes vote down vote up
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() 
Example #10
Source File: visualization.py    From treeano with Apache License 2.0 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #11
Source File: plotnxgraph.py    From complex_network with GNU General Public License v2.0 5 votes vote down vote up
def plot_graph(G, out_file=None, node_size=1500, font_size=10,
				node_and_labels=None, edge_and_labels=None):
	"""
	plot a graph
	"""

	pos = nx.get_node_attributes(G, 'pos')
	if not pos:
		pos = nx.spring_layout(G)

	nx.draw_networkx(G, pos, node_size=node_size, 
						node_color='w', 
						edge_color='k', 
						labels = node_and_labels,
						font_size=font_size,
						font_color='r',
						arrows=True,
						with_labels=True)

	plt.axis('off')	

	if edge_and_labels:
		nx.draw_networkx_edge_labels(G, pos, 
										edge_labels=edge_and_labels, 
										font_color='r',
										label_pos=0.4, 
										alpha=0.0)

	if out_file:
		plt.savefig(out_file, bbox_inches='tight')

	plt.show() 
Example #12
Source File: visualization.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #13
Source File: visualization.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #14
Source File: visualization.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #15
Source File: visualization.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #16
Source File: visualization.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_graph(graph, filename=None, node_size=500):
    nx.draw_networkx(
        graph,
        nx.graphviz_layout(graph),
        node_size=node_size)
    if filename is None:
        pylab.show()
    else:
        pylab.savefig(filename) 
Example #17
Source File: emp_model.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def draw(self):
        """
        Draw a network graph of the employee relationship.
        """
        if self.graph is not None:
            nx.draw_networkx(self.graph)
            plt.show() 
Example #18
Source File: device.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def nx_qubit_layout(graph: nx.Graph) \
        -> Dict[cirq.Qid, Tuple[float, float]]:
    """Return a layout for a graph for nodes which are qubits.

    This can be used in place of nx.spring_layout or other networkx layouts.
    GridQubits are positioned according to their row/col. LineQubits are
    positioned in a line.

    >>> import cirq.contrib.routing as ccr
    >>> import networkx as nx
    >>> import matplotlib.pyplot as plt
    >>> # Clear plot state to prevent issues with pyplot dimensionality.
    >>> plt.clf()
    >>> g = ccr.xmon_device_to_graph(cirq.google.Foxtail)
    >>> pos = ccr.nx_qubit_layout(g)
    >>> nx.draw_networkx(g, pos=pos)

    """
    pos: Dict[cirq.Qid, Tuple[float, float]] = {}

    _node_to_i_cache = None
    for node in graph.nodes:
        if isinstance(node, cirq.GridQubit):
            pos[node] = (node.col, -node.row)
        elif isinstance(node, cirq.LineQubit):
            # Offset to avoid overlap with gridqubits
            pos[node] = (node.x, 0.5)
        else:
            if _node_to_i_cache is None:
                _node_to_i_cache = {
                    n: i for i, n in enumerate(sorted(graph.nodes))
                }
            # Position in a line according to sort order
            # Offset to avoid overlap with gridqubits
            pos[node] = (0.5, _node_to_i_cache[node] + 1)
    return pos 
Example #19
Source File: pymc2_posterior.py    From pynoddy with GNU General Public License v2.0 5 votes vote down vote up
def plot_section(self, i, n=0, plot_topo=False):
        block = self.block_generate(i)
        plt.imshow(block[:, n, :].T, origin="lower", cmap="YlOrRd")
        if plot_topo:
            pos_2d = {}
            for key in self.topo_centroids[0].keys():
                pos_2d[key] = [self.topo_centroids[0][key][0], self.topo_centroids[0][key][2]]

            nx.draw_networkx(self.topo_graphs[i], pos=pos_2d) 
Example #20
Source File: apiutils.py    From aurum-datadiscovery with MIT License 5 votes vote down vote up
def visualize_provenance(self, labels=False):
        if labels:
            nx.draw_networkx(self.get_provenance().prov_graph())
        else:
            nx.draw(self.get_provenance().prov_graph())
        plt.show() 
Example #21
Source File: visualize_embedding.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_embedding2D(node_pos, node_colors=None, di_graph=None):
    """Function to plot the embedding in two dimension.
        Args:
            node_pos (Vector): High dimensional embedding values of each nodes.
            node_colors (List): List consisting of node colors. 
            di_graph (Object): network graph object of the original network.
    """
    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 is not None:
            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) 
Example #22
Source File: module_tree.py    From msticpy with MIT License 5 votes vote down vote up
def plot_graph(call_graph: nx.Graph, size: Tuple[int, int] = (10, 10)):
    """
    Plot circular graph using matplotlib.

    Parameters
    ----------
    call_graph : nx.Graph
        The graph to plot.
    size : Tuple[int, int]
        size of plot, default is(10,10)

    """
    # if circos:
    #     c = CircosPlot(
    #         call_graph,
    #         node_color='degree',
    #         node_grouping='degree',
    #         node_order="degree",
    #         node_labels=True,
    #         fontsize="large",
    #         node_label_layout="rotation",
    #         figsize=(20,20)
    #     )
    #     c.draw()
    # else:
    pos = nx.circular_layout(call_graph)
    nx.draw_networkx(call_graph, pos=pos)
    plt.gcf().set_size_inches(size)
    plt.show() 
Example #23
Source File: main.py    From network-programmability-stream with MIT License 5 votes vote down vote up
def draw_and_save_topology(graph: nx.Graph, edge_labels: List[Dict[Tuple[str, str], str]]) -> None:
    plt.figure(1, figsize=(12, 12))
    pos = nx.spring_layout(graph)
    nx.draw_networkx(graph, pos, node_size=1300, node_color='orange')
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[0], label_pos=0.8)
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[1], label_pos=0.2)
    filename = "topology.png"
    plt.savefig(filename)
    logger.info("The network topology diagram has been saved to %r", filename) 
Example #24
Source File: 6_line_graph.py    From dgl with Apache License 2.0 5 votes vote down vote up
def visualize(labels, g):
    pos = nx.spring_layout(g, seed=1)
    plt.figure(figsize=(8, 8))
    plt.axis('off')
    nx.draw_networkx(g, pos=pos, node_size=50, cmap=plt.get_cmap('coolwarm'),
                     node_color=labels, edge_color='k',
                     arrows=False, width=0.5, style='dotted', with_labels=False) 
Example #25
Source File: 1_first.py    From dgl with Apache License 2.0 5 votes vote down vote up
def draw(i):
    cls1color = '#00FFFF'
    cls2color = '#FF00FF'
    pos = {}
    colors = []
    for v in range(34):
        pos[v] = all_logits[i][v].numpy()
        cls = pos[v].argmax()
        colors.append(cls1color if cls else cls2color)
    ax.cla()
    ax.axis('off')
    ax.set_title('Epoch: %d' % i)
    nx.draw_networkx(nx_G.to_undirected(), pos, node_color=colors,
            with_labels=True, node_size=300, ax=ax) 
Example #26
Source File: draw.py    From skan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def overlay_skeleton_networkx(csr_graph, coordinates, *, axis=None,
                              image=None, cmap=None, **kwargs):
    """Draw the skeleton as a NetworkX graph, optionally overlaid on an image.

    Due to the size of NetworkX drawing elements, this is only recommended
    for very small skeletons.

    Parameters
    ----------
    csr_graph : SciPy Sparse matrix
        The skeleton graph in SciPy CSR format.
    coordinates : array, shape (N_points, 2)
        The coordinates of each point in the skeleton. ``coordinates.shape[0]``
        should be equal to ``csr_graph.shape[0]``.

    Other Parameters
    ----------------
    axis : Matplotlib Axes object, optional
        The Axes on which to plot the data. If None, a new figure and axes will
        be created.
    image : array, shape (M, N[, 3])
        An image on which to overlay the skeleton. ``image.shape`` should be
        greater than ``np.max(coordinates, axis=0)``.
    **kwargs : keyword arguments
        Arguments passed on to `nx.draw_networkx`. Particularly useful ones
        include ``node_size=`` and ``font_size=``.
    """
    if axis is None:
        _, axis = plt.subplots()
    if image is not None:
        cmap = cmap or 'gray'
        axis.imshow(image, cmap=cmap)
    gnx = nx.from_scipy_sparse_matrix(csr_graph)
    # Note: we invert the positions because Matplotlib uses x/y for
    # scatterplot, but the coordinates are row/column NumPy indexing
    positions = dict(zip(range(coordinates.shape[0]), coordinates[:, ::-1]))
    _clean_positions_dict(positions, gnx)  # remove nodes not in Graph
    nx.draw_networkx(gnx, pos=positions, ax=axis, **kwargs)
    return axis 
Example #27
Source File: graphs.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_graph(variables, relations):
    """
    Display the variables and relation as a graph, using networkx and
    matplotlib.

    Parameters
    ----------

    variables: list
        a list of Variable objets
    relations: list
        a list of Relation objects
    """
    graph = as_networkx_graph(variables, relations)

    # Do not crash if matplotlib is not installed
    try:
        import matplotlib.pyplot as plt

        nx.draw_networkx(graph, with_labels=True)
        # nx.draw_random(graph)
        # nx.draw_circular(graph)
        # nx.draw_spectral(graph)
        plt.show()
    except ImportError:
        print("ERROR: cannot display graph, matplotlib is not installed") 
Example #28
Source File: statistical.py    From kenchi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_graphical_model(self, **kwargs):
        """Plot the Gaussian Graphical Model (GGM).

        Parameters
        ----------
        ax : matplotlib Axes, default None
            Target axes instance.

        figsize : tuple, default None
            Tuple denoting figure size of the plot.

        filename : str, default None
            If provided, save the current figure.

        random_state : int, RandomState instance, default None
            Seed of the pseudo random number generator.

        title : string, default 'GGM (n_clusters, n_features, n_isolates)'
            Axes title. To disable, pass None.

        **kwargs : dict
            Other keywords passed to ``nx.draw_networkx``.

        Returns
        -------
        ax : matplotlib Axes
            Axes on which the plot was drawn.
        """

        self._check_is_fitted()

        n_clusters  = np.max(self.labels_) + 1
        n_isolates, = self.isolates_.shape
        title       = (
            f'GGM ('
            f'n_clusters={n_clusters}, '
            f'n_features={self.n_features_}, '
            f'n_isolates={n_isolates}'
            f')'
        )
        kwargs['G'] = self.graphical_model_

        kwargs.setdefault('node_color', self.labels_)
        kwargs.setdefault('title', title)

        return plot_graphical_model(**kwargs) 
Example #29
Source File: exploration_chain.py    From coach with Apache License 2.0 4 votes vote down vote up
def render(self, mode='human', close=False):
        if self.simple_render:
            observation = np.zeros((20, 20*self.chain_length))
            observation[:, self.state*20:(self.state+1)*20] = 255
            return observation
        else:
            # lazy loading of networkx and matplotlib to allow using the environment without installing them if
            # necessary
            import networkx as nx
            from networkx.drawing.nx_agraph import graphviz_layout
            import matplotlib.pyplot as plt

            if not hasattr(self, 'G'):
                self.states = list(range(self.chain_length))
                self.G = nx.DiGraph(directed=True)
                for i, origin_state in enumerate(self.states):
                    if i < self.chain_length - 1:
                        self.G.add_edge(origin_state,
                                        origin_state + 1,
                                        weight=0.5)
                    if i > 0:
                        self.G.add_edge(origin_state,
                                        origin_state - 1,
                                        weight=0.5, )
                    if i == 0 or i < self.chain_length - 1:
                        self.G.add_edge(origin_state,
                                        origin_state,
                                        weight=0.5, )

            fig = plt.gcf()
            if np.all(fig.get_size_inches() != [10, 2]):
                fig.set_size_inches(5, 1)
            color = ['y']*(len(self.G))
            color[self.state] = 'r'
            options = {
                'node_color': color,
                'node_size': 50,
                'width': 1,
                'arrowstyle': '-|>',
                'arrowsize': 5,
                'font_size': 6
            }
            pos = graphviz_layout(self.G, prog='dot', args='-Grankdir=LR')
            nx.draw_networkx(self.G, pos, arrows=True, **options)
            fig.canvas.draw()
            data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
            data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
            return data