Python networkx.draw_networkx_edges() Examples

The following are 30 code examples of networkx.draw_networkx_edges(). 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: plot_alert_pattern_subgraphs.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
def plot_alerts(_g, _bank_accts, _output_png):
    bank_ids = _bank_accts.keys()
    cmap = plt.get_cmap("tab10")
    pos = nx.nx_agraph.graphviz_layout(_g)

    plt.figure(figsize=(12.0, 8.0))
    plt.axis('off')

    for i, bank_id in enumerate(bank_ids):
        color = cmap(i)
        members = _bank_accts[bank_id]
        nx.draw_networkx_nodes(_g, pos, members, node_size=300, node_color=color, label=bank_id)
        nx.draw_networkx_labels(_g, pos, {n: n for n in members}, font_size=10)

    edge_labels = nx.get_edge_attributes(_g, "label")
    nx.draw_networkx_edges(_g, pos)
    nx.draw_networkx_edge_labels(_g, pos, edge_labels, font_size=6)

    plt.legend(numpoints=1)
    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.savefig(_output_png, dpi=120) 
Example #2
Source File: class_based_visualization.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def plot_network(self, G, status, pos=None, nodelist=None, colordict={'S':'#009a80','I':'#ff2020', 'R':'gray'}, **nx_kwargs):
        r'''
        Plots the network in the axes self.networkx_ax.  Nodes are colored according to their status.
        if no ordered nodelist is provided, then the nodes are plotted so that 'I' nodes appear on top, while the order of the 'S' and 'R' nodes is random.  When the network is very dense this highlights 'I' nodes and allows the final state to more accurately represent the proportion of nodes having each status.
        '''
        colorlist = []
        if pos is None:
            pos = nx.spring_layout(G)
        if nodelist is None:
            nodelist = list(G.nodes())
            I_nodes = [node for node in nodelist if status[node] == 'I']
            other_nodes = [node for node in nodelist if status[node]!='I']
            random.shuffle(other_nodes)
            nodelist = other_nodes + I_nodes
            edgelist = list(G.edges())
        else:
            nodeset = set(nodelist)
            edgelist = [edge for edge in G.edges() if edge[0] in nodeset and edge[1] in nodeset]
        for node in nodelist:
            colorlist.append(colordict[status[node]])
        nx.draw_networkx_edges(G, pos, edgelist=edgelist, ax = self.network_axes, **nx_kwargs)
        nx.draw_networkx_nodes(G, pos, nodelist = nodelist, node_color=colorlist, ax=self.network_axes, **nx_kwargs)
        self.network_axes.set_xticks([])
        self.network_axes.set_yticks([]) 
Example #3
Source File: graph.py    From nelpy with MIT License 6 votes vote down vote up
def draw_transmat_graph_outer(Go, Gi, edge_threshold=0, lw=1, ec='0.2', nc='k', node_size=15):

    num_states = Go.number_of_nodes()

    edgewidth = [ d['weight'] for (u,v,d) in Go.edges(data=True)]
    edgewidth = np.array(edgewidth)
    edgewidth[edgewidth<edge_threshold] = 0

    npos=double_circular_layout(Gi, scale=1, direction='CW')

    nx.draw_networkx_edges(Go, npos, alpha=1.0, width=edgewidth*lw, edge_color=ec)

    nx.draw_networkx_nodes(Go, npos, node_size=node_size, node_color=nc,alpha=1.0)

    ax = plt.gca()
    ax.set_aspect('equal')

    return ax 
Example #4
Source File: viz.py    From dgl with Apache License 2.0 6 votes vote down vote up
def graph_att_head(M, N, weight, ax, title):
    "credit: Jinjing Zhou"
    in_nodes=len(M)
    out_nodes=len(N)

    g = nx.bipartite.generators.complete_bipartite_graph(in_nodes,out_nodes)
    X, Y = bipartite.sets(g)
    height_in = 10
    height_out = height_in 
    height_in_y = np.linspace(0, height_in, in_nodes)
    height_out_y = np.linspace((height_in - height_out) / 2, height_out, out_nodes)
    pos = dict()
    pos.update((n, (1, i)) for i, n in zip(height_in_y, X))  # put nodes from X at x=1
    pos.update((n, (3, i)) for i, n in zip(height_out_y, Y))  # put nodes from Y at x=2
    ax.axis('off')
    ax.set_xlim(-1,4)
    ax.set_title(title)
    nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes), node_color='r', node_size=50, ax=ax)
    nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes, in_nodes + out_nodes), node_color='b', node_size=50, ax=ax)
    for edge in g.edges():
        nx.draw_networkx_edges(g, pos, edgelist=[edge], width=weight[edge[0], edge[1] - in_nodes] * 1.5, ax=ax)
    nx.draw_networkx_labels(g, pos, {i:label + '  ' for i,label in enumerate(M)},horizontalalignment='right', font_size=8, ax=ax)
    nx.draw_networkx_labels(g, pos, {i+in_nodes:'  ' + label for i,label in enumerate(N)},horizontalalignment='left', font_size=8, ax=ax) 
Example #5
Source File: graph.py    From nelpy with MIT License 6 votes vote down vote up
def draw_transmat_graph_inner(G, edge_threshold=0, lw=1, ec='0.2', node_size=15):

    num_states = G.number_of_nodes()

    edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]
    edgewidth = np.array(edgewidth)
    edgewidth[edgewidth<edge_threshold] = 0

    npos=circular_layout(G, scale=1, direction='CW')

    nx.draw_networkx_edges(G, npos, alpha=1.0, width=edgewidth*lw, edge_color=ec)

    nx.draw_networkx_nodes(G, npos, node_size=node_size, node_color='k',alpha=1.0)
    ax = plt.gca()
    ax.set_aspect('equal')

    return ax 
Example #6
Source File: class_based_visualization.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def _initialize(self):
        initial_status = EoN.get_statuses(self.G, self.node_history, self.frame_times[0])
        colorlist = [self.colordict[initial_status[node]] for node in self.nodelist]

        nodeset = {node for node in self.nodelist}
        edgelist = [edge for edge in self.G.edges() if edge[0] in nodeset and edge[1] in nodeset]
        nx.draw_networkx_edges(self.G, pos=self.pos, edgelist=edgelist, ax = self.network_axes)

        drawn_nodes = nx.draw_networkx_nodes(self.G, pos=self.pos, ax = self.network_axes, nodelist = self.nodelist, color=colorlist, **self.kwargs)
        Inodelist = [node for node in self.nodelist if initial_status[node] == 'I']
        drawn_I = [nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=Inodelist, color = self.colordict['I'], ax = self.network_axes, **self.kwargs)]

        self.network_axes.set_xticks([])
        self.network_axes.set_yticks([])
        
        time_markers = [None for ax in self.timeseries_axi]
        self._highlight_time(self.frame_times[0], time_markers)
        return drawn_nodes, drawn_I, time_markers 
Example #7
Source File: visualizer.py    From swarmlib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def replay(self, graph):
        """Draw the given graph."""
        fig, ax = plt.subplots(frameon=False)  # pylint:disable=invalid-name
        plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

        node_pos = graph.node_coordinates

        def _update(num):
            ax.clear()

            fig.canvas.set_window_title(f'{graph.name} - Iteration ({num+1}/{len(self.__edge_colors)})')

            nodes_artist = nx.draw_networkx_nodes(graph.networkx_graph, pos=node_pos, ax=ax, node_color=self.__node_color)
            labels_artist = nx.draw_networkx_labels(graph.networkx_graph, pos=node_pos, ax=ax)
            edges_artist = nx.draw_networkx_edges(graph.networkx_graph, pos=node_pos, width=self.__edge_widths[num], edge_color=self.__edge_colors[num], ax=ax)

            return nodes_artist, labels_artist, edges_artist

        _ = animation.FuncAnimation(fig, _update, frames=len(self.__edge_colors), interval=self.__interval, repeat=self.__continuous)
        plt.show() 
Example #8
Source File: gengraph.py    From GenGraph with GNU General Public License v3.0 6 votes vote down vote up
def plot_subgraph(self, region_start, region_stop, seq_name, neighbours=0):
		"""
		Return a plot of a sub-graph from a defined region with positions relative to some of the sequences.
		:param region_start: Start position (bp)
		:param region_stop: Stop position (bp)
		:param seq_name: Sequence ID that the bp positions are relative to.
		:param neighbours: Number of neighbours to be included. Currently testing, only 1 level available.
		:return: Plots a netowrkx + matplotlib figure of the region subgraph.
		"""

		sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours)
		pos = nx.spring_layout(sub_graph)
		nx.draw_networkx_nodes(sub_graph, pos, cmap=plt.get_cmap('jet'), node_size=300)
		nx.draw_networkx_labels(sub_graph, pos)
		nx.draw_networkx_edges(sub_graph, pos, arrows=True)
		plt.show() 
Example #9
Source File: _utils.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_edges(axs, adata, basis, edges_width, edges_color, neighbors_key=None):
    import networkx as nx

    if not isinstance(axs, cabc.Sequence):
        axs = [axs]

    if neighbors_key is None:
        neighbors_key = 'neighbors'
    if neighbors_key not in adata.uns:
        raise ValueError('`edges=True` requires `pp.neighbors` to be run before.')
    neighbors = NeighborsView(adata, neighbors_key)
    g = nx.Graph(neighbors['connectivities'])
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        for ax in axs:
            edge_collection = nx.draw_networkx_edges(
                g,
                adata.obsm['X_' + basis],
                ax=ax,
                width=edges_width,
                edge_color=edges_color,
            )
            edge_collection.set_zorder(-2)
            edge_collection.set_rasterized(settings._vector_friendly) 
Example #10
Source File: build_retweet_network.py    From smappPy with GNU General Public License v2.0 5 votes vote down vote up
def display_retweet_network(network, outfile=None, show=False):
    """
    Take a DiGraph (retweet network?) and display+/save it to file.
    Nodes must have a 'color' property, represented literally and indicating their type
    Edges must have a 'weight' property, represented as edge width
    """

    # Create a color list corresponding to nodes.
    node_colors = [ n[1]["color"] for n in network.nodes(data=True) ]

    # Get edge weights from graph
    edge_weights = [ e[2]["weight"] for e in network.edges(data=True) ]

    # Build up graph figure
    #pos = nx.random_layout(network)
    pos = nx.spring_layout(network)
    nx.draw_networkx_edges(network, pos, alpha=0.3 , width=edge_weights, edge_color='m')
    nx.draw_networkx_nodes(network, pos, node_size=400, node_color=node_colors, alpha=0.4)
    #nx.draw_networkx_labels(network, pos, fontsize=6)

    plt.title("Retweet Network", { 'fontsize': 12 })
    plt.axis('off')

    if outfile:
        print "Saving network to file: {0}".format(outfile)
        plt.savefig(outfile)

    if show:
        print "Displaying graph. Close graph window to resume python execution"
        plt.show() 
Example #11
Source File: io.py    From indra with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def draw_stmt_graph(stmts):
    """Render the attributes of a list of Statements as directed graphs.

    The layout works well for a single Statement or a few Statements at a time.
    This function displays the plot of the graph using plt.show().

    Parameters
    ----------
    stmts : list[indra.statements.Statement]
        A list of one or more INDRA Statements whose attribute graph should
        be drawn.
    """
    import networkx
    try:
        import matplotlib.pyplot as plt
    except Exception:
        logger.error('Could not import matplotlib, not drawing graph.')
        return
    try:  # This checks whether networkx has this package to work with.
        import pygraphviz
    except Exception:
        logger.error('Could not import pygraphviz, not drawing graph.')
        return
    import numpy
    g = networkx.compose_all([stmt.to_graph() for stmt in stmts])
    plt.figure()
    plt.ion()
    g.graph['graph'] = {'rankdir': 'LR'}
    pos = networkx.drawing.nx_agraph.graphviz_layout(g, prog='dot')
    g = g.to_undirected()

    # Draw nodes
    options = {
        'marker': 'o',
        's': 200,
        'c': [0.85, 0.85, 1],
        'facecolor': '0.5',
        'lw': 0,
    }
    ax = plt.gca()
    nodelist = list(g)
    xy = numpy.asarray([pos[v] for v in nodelist])
    node_collection = ax.scatter(xy[:, 0], xy[:, 1], **options)
    node_collection.set_zorder(2)
    # Draw edges
    networkx.draw_networkx_edges(g, pos, arrows=False, edge_color='0.5')
    # Draw labels
    edge_labels = {(e[0], e[1]): e[2].get('label') for e in g.edges(data=True)}
    networkx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels)
    node_labels = {n[0]: n[1].get('label') for n in g.nodes(data=True)}
    for key, label in node_labels.items():
        if len(label) > 25:
            parts = label.split(' ')
            parts.insert(int(len(parts)/2), '\n')
            label = ' '.join(parts)
            node_labels[key] = label
    networkx.draw_networkx_labels(g, pos, labels=node_labels)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.show() 
Example #12
Source File: good_structure.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def draw_graph(self):
        nx.draw_shell(self.G, with_labels=True, font_weight='bold')

        # pos = graphviz_layout(self.G)
        # plt.axis('off')
        # nx.draw_networkx_nodes(self.G,pos,node_color='g',alpha = 0.8)
        # nx.draw_networkx_edges(self.G,pos,edge_color='b',alpha = 0.6)
        # nx.draw_networkx_edge_labels(self.G,pos,edge_labels = \
        # nx.get_edge_attributes(self.G,'weight'))
        # nx.draw_networkx_labels(self.G,pos) # node lables

        plt.savefig('graph.png') 
Example #13
Source File: show_task.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def showTask(task, root="ROOT()", filename="task.dot"):
    import matplotlib.pyplot as plt

    g = nx.DiGraph()

    nodes = [root]
    visited = set()
    nodelist = []

    print(root)
    print(task.nodeSummary())

    while len(nodes) > 0:
        node = nodes.pop()
        visited.add(node)
        children = task.children[node]
        print("NODE =", node, "CHILDREN =")
        weights = task.weights[node]
        if len(weights) > 0:
            for child, wt in zip(children, weights):
                print("\t",child,"weight =", wt)
                g.add_edge(node, child, weight=int(wt))
                nodelist.append(child)
                if child not in visited:
                    print("\t\tadding", child)
                    nodes.append(child)
        elif len(children) > 0:
            raise RuntimeError('weights not initialized')

    pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
    nx.draw_networkx_edges(g, pos, width=1.0, alpha=1., arrows=False)
    nx.draw(g, pos, prog='dot', node_size=1000, nodelist=nodelist,
            width=1.0, alpha=1., arrows=True, with_labels=True,)
    labels = nx.get_edge_attributes(g,'weight')
    nx.draw_networkx_edge_labels(g,pos,edge_labels=labels)
    #a = nx.nx_agraph.to_agraph(g)
    #a.draw('ex.png', prog='dot')
    plt.axis('off')
    plt.show() 
Example #14
Source File: plot_graph.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def main(args,root="root"):
	# init graph
	graph = nx.DiGraph()
	node_list = set()
	node_list.add(root)

	# Read data
	for filename in os.listdir(args['path']): 
		if filename.startswith('.'):
			continue
		idx = int(filename[7:13])
		if idx < args['start'] or idx > args['end']:
			continue
		
        if args['ignore_failure'] and 'failure' in filename:
                continue

		data = h5py.File(args['path']+filename,'r')
		labels = list(data[args['name']])
		prev_label = root

		for label in labels:
			if not label == prev_label:
				graph.add_edge(prev_label,label,weight=1)
			prev_label = label
			node_list.add(label)

	pos = nx.nx_agraph.graphviz_layout(graph, prog="dot")
	nx.draw_networkx_edges(graph, pos, width=1.0, alpha=1., arrows=False)
	nx.draw(graph, pos, prog='dot', node_size=1000, nodelist=node_list,
            width=1.0, alpha=1., arrows=True, with_labels=True,)

	plt.axis
	plt.show() 
Example #15
Source File: dependencygraph.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def malt_demo(nx=False):
    """
    A demonstration of the result of reading a dependency
    version of the first sentence of the Penn Treebank.
    """
    dg = DependencyGraph("""Pierre  NNP     2       NMOD
Vinken  NNP     8       SUB
,       ,       2       P
61      CD      5       NMOD
years   NNS     6       AMOD
old     JJ      2       NMOD
,       ,       2       P
will    MD      0       ROOT
join    VB      8       VC
the     DT      11      NMOD
board   NN      9       OBJ
as      IN      9       VMOD
a       DT      15      NMOD
nonexecutive    JJ      15      NMOD
director        NN      12      PMOD
Nov.    NNP     9       VMOD
29      CD      16      NMOD
.       .       9       VMOD
""")
    tree = dg.tree()
    print tree.pprint()
    if nx:
        #currently doesn't work
        import networkx as NX
        import pylab as P

        g = dg.nx_graph()
        g.info()
        pos = NX.spring_layout(g, dim=1)
        NX.draw_networkx_nodes(g, pos, node_size=50)
        #NX.draw_networkx_edges(g, pos, edge_color='k', width=8)
        NX.draw_networkx_labels(g, pos, dg.nx_labels)
        P.xticks([])
        P.yticks([])
        P.savefig('tree.png')
        P.show() 
Example #16
Source File: zincbase.py    From zincbase with MIT License 5 votes vote down vote up
def plot(self, density=1.0):
        """Plots a network diagram from (triple) nodes and edges in the KB.

        :param float density: Probability (0-1) that a given edge will be plotted, \
        useful to thin out dense graphs for visualization."""
        edgelist = [e for e in self.G.edges(data=True) if random.random() < density]
        newg = nx.DiGraph(edgelist)
        pos = nx.spring_layout(newg)
        plt.figure(1,figsize=(12,12))
        nx.draw_networkx_nodes(newg, pos, node_size=200)
        nx.draw_networkx_edges(newg, pos, edgelist=edgelist, width=1, font_size=8)
        nx.draw_networkx_labels(newg, pos, font_size=10, font_family='sans-serif')
        nx.draw_networkx_edge_labels(newg, pos)
        plt.axis('off')
        plt.show() 
Example #17
Source File: render.py    From NetworkAttackSimulator with MIT License 5 votes vote down vote up
def _draw_graph(self, G):
        pos = {}
        colors = []
        labels = {}
        for n in list(G.nodes):
            colors.append(G.nodes[n]["color"])
            labels[n] = G.nodes[n]["label"]
            pos[n] = G.nodes[n]["pos"]

        # clear window and redraw graph
        self.axes.cla()
        nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=1500, ax=self.axes)
        nx.draw_networkx_labels(G, pos, labels, font_size=12, font_weight="bold")
        nx.draw_networkx_edges(G, pos)
        plt.axis('off')
        # generate and plot legend
        # legend_entries = self.legend()
        # plt.legend(handles=legend_entries, fontsize=16)
        # add title
        state, action, reward, done = self.episode[self.timestep]
        if done:
            title = "t = {0}\nGoal reached\ntotal reward = {1}".format(self.timestep, reward)
        else:
            title = "t = {0}\n{1}\nReward = {2}".format(self.timestep, action, reward)
        ax_title = self.axes.set_title(title, fontsize=16, pad=10)
        ax_title.set_y(1.05)

        xticks = self.axes.get_xticks()
        yticks = self.axes.get_yticks()
        # shift half a step to the left
        xmin = (3*xticks[0] - xticks[1])/2.
        ymin = (3*yticks[0] - yticks[1])/2.
        # shaft half a step to the right
        xmax = (3*xticks[-1] - xticks[-2])/2.
        ymax = (3*yticks[-1] - yticks[-2])/2.

        self.axes.set_xlim(left=xmin, right=xmax)
        self.axes.set_ylim(bottom=ymin, top=ymax)
        # self.fig.savefig("t_{}.png".format(self.timestep))
        self.canvas.draw() 
Example #18
Source File: plot_utils.py    From graph-convnet-tsp with MIT License 5 votes vote down vote up
def plot_tsp(p, x_coord, W, W_val, W_target, title="default"):
    """
    Helper function to plot TSP tours.
    
    Args:
        p: Matplotlib figure/subplot
        x_coord: Coordinates of nodes
        W: Edge adjacency matrix
        W_val: Edge values (distance) matrix
        W_target: One-hot matrix with 1s on groundtruth/predicted edges
        title: Title of figure/subplot
    
    Returns:
        p: Updated figure/subplot
    
    """

    def _edges_to_node_pairs(W):
        """Helper function to convert edge matrix into pairs of adjacent nodes.
        """
        pairs = []
        for r in range(len(W)):
            for c in range(len(W)):
                if W[r][c] == 1:
                    pairs.append((r, c))
        return pairs
    
    G = nx.from_numpy_matrix(W_val)
    pos = dict(zip(range(len(x_coord)), x_coord.tolist()))
    adj_pairs = _edges_to_node_pairs(W)
    target_pairs = _edges_to_node_pairs(W_target)
    colors = ['g'] + ['b'] * (len(x_coord) - 1)  # Green for 0th node, blue for others
    nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=50)
    nx.draw_networkx_edges(G, pos, edgelist=adj_pairs, alpha=0.3, width=0.5)
    nx.draw_networkx_edges(G, pos, edgelist=target_pairs, alpha=1, width=1, edge_color='r')
    p.set_title(title)
    return p 
Example #19
Source File: plot_utils.py    From graph-convnet-tsp with MIT License 5 votes vote down vote up
def plot_tsp_heatmap(p, x_coord, W_val, W_pred, title="default"):
    """
    Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction.
    
    Args:
        p: Matplotlib figure/subplot
        x_coord: Coordinates of nodes
        W_val: Edge values (distance) matrix
        W_pred: Edge predictions matrix
        title: Title of figure/subplot
    
    Returns:
        p: Updated figure/subplot
    
    """

    def _edges_to_node_pairs(W):
        """Helper function to convert edge matrix into pairs of adjacent nodes.
        """
        pairs = []
        edge_preds = []
        for r in range(len(W)):
            for c in range(len(W)):
                if W[r][c] > 0.25:
                    pairs.append((r, c))
                    edge_preds.append(W[r][c])
        return pairs, edge_preds
        
    G = nx.from_numpy_matrix(W_val)
    pos = dict(zip(range(len(x_coord)), x_coord.tolist()))
    node_pairs, edge_color = _edges_to_node_pairs(W_pred)
    node_color = ['g'] + ['b'] * (len(x_coord) - 1)  # Green for 0th node, blue for others
    nx.draw_networkx_nodes(G, pos, node_color=node_color, node_size=50)
    nx.draw_networkx_edges(G, pos, edgelist=node_pairs, edge_color=edge_color, edge_cmap=plt.cm.Reds, width=0.75)
    p.set_title(title)
    return p 
Example #20
Source File: component.py    From pynsim with GNU General Public License v3.0 5 votes vote down vote up
def draw(self, block=True):
        """
            Draw the pynsim network as a matplotlib plot.
        """
        try:
            import matplotlib.pyplot as plt
            import networkx as nx

            g = nx.Graph()
            #Nodes
            pos = {}
            labels = {}
            for n in self.nodes:
                g.add_node(n)
                pos[n] = (n.x, n.y)
                labels[n] = n.name
            colours = [n.colour for n in g.nodes()]
            nx.draw_networkx_nodes(g, pos, width=8, alpha=0.5,
                                   node_color=colours)
            nx.draw_networkx_labels(g, pos, labels, font_size=10)
            #links
            for l in self.links:
                g.add_edge(l.start_node, l.end_node, name=l.name,
                           colour=l.colour)
            colours = [g[a][b]['colour'] for a, b in g.edges()]

            nx.draw_networkx_edges(g, pos, width=2, alpha=0.5,
                                   edge_color=colours)
            mng = plt.get_current_fig_manager()
            mng.resize(1000, 700)
            plt.show(block=block)

        except ImportError:
            logging.critical("Cannot draw network. Please ensure matplotlib "
                             "and networkx are installed.") 
Example #21
Source File: plotting.py    From metaknowledge with GNU General Public License v2.0 5 votes vote down vote up
def quickVisual(G, showLabel = False):
    """Just makes a simple _matplotlib_ figure and displays it, with each node coloured by its type. You can add labels with _showLabel_. This looks a bit nicer than the one provided my _networkx_'s defaults.

    # Parameters

    _showLabel_ : `optional [bool]`

    > Default `False`, if `True` labels will be added to the nodes giving their IDs.
    """
    colours = "brcmykwg"
    f = plt.figure(1)
    ax = f.add_subplot(1,1,1)
    ndTypes = []
    ndColours = []
    layout = nx.spring_layout(G, k = 4 / math.sqrt(len(G.nodes())))
    for nd in G.nodes(data = True):
        if 'type' in nd[1]:
            if nd[1]['type'] not in ndTypes:
                ndTypes.append(nd[1]['type'])
            ndColours.append(colours[ndTypes.index(nd[1]['type']) % len(colours)])
        elif len(ndColours) > 1:
            raise RuntimeError("Some nodes do not have a type")
    if len(ndColours) < 1:
        nx.draw_networkx_nodes(G, pos = layout, node_color = colours[0], node_shape = '8', node_size = 100, ax = ax)
    else:
        nx.draw_networkx_nodes(G, pos = layout, node_color = ndColours, node_shape = '8', node_size = 100, ax = ax)
    nx.draw_networkx_edges(G, pos = layout, width = .7, ax = ax)
    if showLabel:
        nx.draw_networkx_labels(G, pos = layout, font_size = 8, ax = ax)
    plt.axis('off')
    f.set_facecolor('w') 
Example #22
Source File: causal_graph.py    From dowhy with MIT License 5 votes vote down vote up
def view_graph(self, layout="dot"):
        out_filename = "causal_model.png"
        try:
            import pygraphviz as pgv
            agraph = nx.drawing.nx_agraph.to_agraph(self._graph)
            agraph.draw(out_filename, format="png", prog=layout)
        except:
            self.logger.warning("Warning: Pygraphviz cannot be loaded. Check that graphviz and pygraphviz are installed.")
            self.logger.info("Using Matplotlib for plotting")
            import matplotlib.pyplot as plt

            solid_edges = [(n1,n2) for n1,n2, e in self._graph.edges(data=True) if 'style' not in e ]
            dashed_edges =[(n1,n2) for n1,n2, e in self._graph.edges(data=True) if ('style' in e and e['style']=="dashed") ]
            plt.clf()

            pos = nx.layout.shell_layout(self._graph)
            nx.draw_networkx_nodes(self._graph, pos, node_color='yellow',node_size=400 )
            nx.draw_networkx_edges(
                    self._graph,
                    pos,
                    edgelist=solid_edges,
                    arrowstyle="-|>",
                    arrowsize=12)
            nx.draw_networkx_edges(
                    self._graph,
                    pos,
                    edgelist=dashed_edges,
                    arrowstyle="-|>",
                    style="dashed",
                    arrowsize=12)
            
            labels = nx.draw_networkx_labels(self._graph, pos)

            plt.axis('off')
            plt.savefig(out_filename)
            plt.draw() 
Example #23
Source File: test_pylab.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_labels_and_colors(self):
        G = nx.cubical_graph()
        pos = nx.spring_layout(G)  # positions for all nodes
        # nodes
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[0, 1, 2, 3],
                               node_color='r',
                               node_size=500,
                               alpha=0.8)
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[4, 5, 6, 7],
                               node_color='b',
                               node_size=500,
                               alpha=0.8)
        # edges
        nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
        nx.draw_networkx_edges(G, pos,
                               edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
                               width=8, alpha=0.5, edge_color='r')
        nx.draw_networkx_edges(G, pos,
                               edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
                               width=8, alpha=0.5, edge_color='b')
        # some math labels
        labels = {}
        labels[0] = r'$a$'
        labels[1] = r'$b$'
        labels[2] = r'$c$'
        labels[3] = r'$d$'
        labels[4] = r'$\alpha$'
        labels[5] = r'$\beta$'
        labels[6] = r'$\gamma$'
        labels[7] = r'$\delta$'
        nx.draw_networkx_labels(G, pos, labels, font_size=16)
        plt.show() 
Example #24
Source File: test_pylab.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_labels_and_colors(self):
        G = nx.cubical_graph()
        pos = nx.spring_layout(G)  # positions for all nodes
        # nodes
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[0, 1, 2, 3],
                               node_color='r',
                               node_size=500,
                               alpha=0.8)
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[4, 5, 6, 7],
                               node_color='b',
                               node_size=500,
                               alpha=0.8)
        # edges
        nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
        nx.draw_networkx_edges(G, pos,
                               edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
                               width=8, alpha=0.5, edge_color='r')
        nx.draw_networkx_edges(G, pos,
                               edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
                               width=8, alpha=0.5, edge_color='b')
        # some math labels
        labels = {}
        labels[0] = r'$a$'
        labels[1] = r'$b$'
        labels[2] = r'$c$'
        labels[3] = r'$d$'
        labels[4] = r'$\alpha$'
        labels[5] = r'$\beta$'
        labels[6] = r'$\gamma$'
        labels[7] = r'$\delta$'
        nx.draw_networkx_labels(G, pos, labels, font_size=16)
        plt.show() 
Example #25
Source File: visualize.py    From pathnet-pytorch with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_fig(self, genes, e_color):

        fixed_pair = [(self.fixed_path[i], self.fixed_path[i+1]) 
                      for i in range(len(self.fixed_path) - 1)]

        for gene in genes:
            gene_pair = [(gene[i], gene[i+1]) for i in range(len(gene) - 1)]

            for layer_num, (pair, fixed) in enumerate(zip(gene_pair, fixed_pair)):
                for first_num in pair[0]:
                    for second_num in pair[1]:
                        first_node = self.node_ids[(layer_num, first_num)]
                        second_node = self.node_ids[(layer_num + 1, second_num)]
                        if self.graph.has_edge(first_node, second_node):
                            self.node_upsize(first_node)
                            self.node_upsize(second_node)
                            weight =  self.graph.get_edge_data(first_node, second_node)['weight']
                            weight += self.edge_weight_add
                            self.graph.add_edge(first_node, second_node, color = e_color, weight = weight)
                        else:
                            self.graph.add_edge(first_node, second_node, color = e_color, weight = self.init_edge_weight)
                        
        for fixed in fixed_pair:
            for f_1 in fixed[0]:
                for f_2 in fixed[1]:
                    if (not f_1 == None) and (not f_2 == None):
                        self.graph.add_edge(f_1, f_2, color = self.fixed_color, weight = self.fixed_weight)

        nodes = self.graph.nodes(data = True)
        node_color = 'g'
        node_size = [node[1]['size'] for node in nodes]
        node_shape = 's'

        edges = self.graph.edges()
        edge_color = [self.graph[u][v]['color'] for u,v in edges]
        weights = [self.graph[u][v]['weight'] for u,v in edges]
        nx.draw_networkx_nodes(self.graph, nodes = nodes, pos=nx.get_node_attributes(self.graph,'Position'), node_color = node_color, node_size = node_size, node_shape = node_shape)
        nx.draw_networkx_edges(self.graph, edges = edges, pos=nx.get_node_attributes(self.graph,'Position'), edge_color = edge_color, width = weights) 
Example #26
Source File: f_t_parser_ff.py    From ryu with Apache License 2.0 5 votes vote down vote up
def draw_fault_scenario(title, fault_edge, pp, dp, fwp):
    nx.draw(G, pos, node_size=300, font_size=10, node_color='w', alpha=1, with_labels=True)

    if title is not None:
        plt.text(0.5, 0.5, title, fontsize=12)

    if pp is not None:
        draw_edge_node(pp, 0.8, 'b')
        # Source
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[pp[0]],
                               node_color='black',
                               node_size=500,
                               label='S',
                               font_size=10,
                               node_shape='s',
                               alpha=0.5)
    # Detour path
    if dp is not None:
        draw_edge_node(dp, 0.8, 'g')

    # Fault edge
    if fault_edge is not None:
        nx.draw_networkx_edges(G, pos,
                               edgelist=[fault_edge],
                               width=4, alpha=0.8,
                               edge_color='r')
    # FW Back path
    if fwp is not None:
        draw_edge_node(fwp, 0.8, 'y', 'dashed') 
Example #27
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def draw_adjacency_graph(adjacency_matrix,
                         node_color=None,
                         size=10,
                         layout='graphviz',
                         prog='neato',
                         node_size=80,
                         colormap='autumn'):
    """draw_adjacency_graph."""
    graph = nx.from_scipy_sparse_matrix(adjacency_matrix)

    plt.figure(figsize=(size, size))
    plt.grid(False)
    plt.axis('off')

    if layout == 'graphviz':
        pos = nx.graphviz_layout(graph, prog=prog)
    else:
        pos = nx.spring_layout(graph)

    if len(node_color) == 0:
        node_color = 'gray'
    nx.draw_networkx_nodes(graph, pos,
                           node_color=node_color,
                           alpha=0.6,
                           node_size=node_size,
                           cmap=plt.get_cmap(colormap))
    nx.draw_networkx_edges(graph, pos, alpha=0.5)
    plt.show()


# draw a whole set of graphs:: 
Example #28
Source File: dependencygraph.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def malt_demo(nx=False):
    """
    A demonstration of the result of reading a dependency
    version of the first sentence of the Penn Treebank.
    """
    dg = DependencyGraph("""Pierre  NNP     2       NMOD
Vinken  NNP     8       SUB
,       ,       2       P
61      CD      5       NMOD
years   NNS     6       AMOD
old     JJ      2       NMOD
,       ,       2       P
will    MD      0       ROOT
join    VB      8       VC
the     DT      11      NMOD
board   NN      9       OBJ
as      IN      9       VMOD
a       DT      15      NMOD
nonexecutive    JJ      15      NMOD
director        NN      12      PMOD
Nov.    NNP     9       VMOD
29      CD      16      NMOD
.       .       9       VMOD
""")
    tree = dg.tree()
    tree.pprint()
    if nx:
        # currently doesn't work
        import networkx
        from matplotlib import pylab

        g = dg.nx_graph()
        g.info()
        pos = networkx.spring_layout(g, dim=1)
        networkx.draw_networkx_nodes(g, pos, node_size=50)
        # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
        networkx.draw_networkx_labels(g, pos, dg.nx_labels)
        pylab.xticks([])
        pylab.yticks([])
        pylab.savefig('tree.png')
        pylab.show() 
Example #29
Source File: main.py    From dcc with Apache License 2.0 5 votes vote down vote up
def plot(cg):
    """
    Plot the call graph using matplotlib
    For larger graphs, this should not be used, as it is very slow
    and probably you can not see anything on it.

    :param cg: A networkx call graph to plot
    """
    from androguard.core.analysis.analysis import ExternalMethod
    import matplotlib.pyplot as plt
    import networkx as nx
    pos = nx.spring_layout(cg)

    internal = []
    external = []

    for n in cg.node:
        if isinstance(n, ExternalMethod):
            external.append(n)
        else:
            internal.append(n)

    nx.draw_networkx_nodes(cg, pos=pos, node_color='r', nodelist=internal)
    nx.draw_networkx_nodes(cg, pos=pos, node_color='b', nodelist=external)
    nx.draw_networkx_edges(cg, pos, arrow=True)
    nx.draw_networkx_labels(cg, pos=pos,
                            labels={x: "{} {}".format(x.get_class_name(),
                                                      x.get_name())
                                    for x in cg.edge})
    plt.draw()
    plt.show() 
Example #30
Source File: __init__.py    From psst with MIT License 5 votes vote down vote up
def _draw_edges(self, edgelist, **kwargs):
        edge_labels = kwargs.get('edge_labels', False)
        if edge_labels is not False:
            if edge_labels is True:
                edge_labels = {(f, t): '({},{})'.format(f, t) for f, t in edgelist}
            self._draw_edge_labels(edge_labels)
        return nx.draw_networkx_edges(self._G, self._pos, edgelist=edgelist, **kwargs)