Python networkx.draw_networkx_nodes() Examples

The following are 30 code examples of networkx.draw_networkx_nodes(). 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: 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 #2
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 #3
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 #4
Source File: plots.py    From oopt-gnpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_baseline(network):
    edges = set(network.edges())
    pos = {n: (n.lng, n.lat) for n in network.nodes()}
    labels = {n: n.location.city for n in network.nodes() if isinstance(n, Transceiver)}
    city_labels = set(labels.values())
    for n in network.nodes():
        if n.location.city and n.location.city not in city_labels:
            labels[n] = n.location.city
            city_labels.add(n.location.city)
    label_pos = pos

    fig = figure()
    kwargs = {'figure': fig, 'pos': pos}
    plot = draw_networkx_nodes(network, nodelist=network.nodes(), node_color='#ababab', **kwargs)
    draw_networkx_edges(network, edgelist=edges, edge_color='#ababab', **kwargs)
    draw_networkx_labels(network, labels=labels, font_size=14, **{**kwargs, 'pos': label_pos})
    axis('off')
    show() 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: eval_metric.py    From valan with Apache License 2.0 5 votes vote down vote up
def _draw_path(path, pos, color='black'):
  """Draw one path in one networkx graph."""
  path_graph = networkx.DiGraph()
  path_graph.add_node(path[0])
  edges = collections.defaultdict(list)
  for idx in range(len(path) - 1):
    if path[idx +
            1] not in [constants.STOP_NODE_NAME, constants.INVALID_NODE_NAME]:
      path_graph.add_edge(path[idx], path[idx + 1])
      start = min(path[idx], path[idx + 1])
      end = max(path[idx], path[idx + 1])
      edges[(start, end)].append((path[idx], path[idx + 1], color))
  networkx.draw_networkx_nodes(
      path_graph, pos, edge_color=color, node_color=color, **DEFAULT_PARAM)
  return path_graph, edges 
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: class_based_visualization.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def _animation_update(self, t, drawn_nodes, drawn_I, time_markers):
        status = EoN.get_statuses(self.G, self.node_history, t)
        Inodelist = [node for node in self.nodelist if status[node] == 'I']
        drawn_nodes.set_color([self.colordict[status[node]] for node in self.nodelist])
        drawn_I[0].remove()
        drawn_I[0] = nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=Inodelist, color = self.colordict['I'], ax = self.network_axes, **self.kwargs)
        for tm in time_markers:
            tm.remove()
        self._highlight_time(t, time_markers) 
Example #14
Source File: simulation_investigation.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def _draw_specific_status(self, pos, nodes, status, ax, **nx_kwargs):
        drawn = nx.draw_networkx_nodes(self.G, pos, nodelist = nodes, node_color = self.sim_color_dict[status], **nx_kwargs) 
        return drawn 
Example #15
Source File: simulation_investigation.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def _update_ani_(self, time, pos, nodelist, drawn_nodes, drawn_elevated, status_order, graph_ax, ts_axes, time_markers, nx_kwargs):
        '''
        '''
        nodestatus = self.get_statuses(self.G, time)
        
        drawn_nodes.set_color([self.sim_color_dict[nodestatus[node]] for node in nodelist])
        for status in reversed(status_order):
            nodes_with_status = [node for node in nodelist if nodestatus[node] == status]
            drawn_elevated[status][0].remove()
            drawn_elevated[status][0] =  nx.draw_networkx_nodes(self.G, pos, nodelist=nodes_with_status, color = self.sim_color_dict[status], ax = graph_ax, **nx_kwargs)
        for index, ax in enumerate(ts_axes):
            time_markers[index].remove()
            time_markers[index] = ax.axvline(x=time, linestyle='--', color='k')
        return 
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: 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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
Source File: test_pylab.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_alpha_iter(self):
        pos = nx.random_layout(self.G)
        # with fewer alpha elements than nodes
        plt.subplot(131)
        nx.draw_networkx_nodes(self.G, pos, alpha=[0.1, 0.2])
        # with equal alpha elements and nodes
        num_nodes = len(self.G.nodes)
        alpha = [x / num_nodes for x in range(num_nodes)]
        colors = range(num_nodes)
        plt.subplot(132)
        nx.draw_networkx_nodes(self.G, pos, node_color=colors, alpha=alpha)
        # with more alpha elements than nodes
        alpha.append(1)
        plt.subplot(133)
        nx.draw_networkx_nodes(self.G, pos, alpha=alpha) 
Example #26
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 #27
Source File: test_pylab.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_alpha_iter(self):
        pos = nx.random_layout(self.G)
        # with fewer alpha elements than nodes
        plt.subplot(131)
        nx.draw_networkx_nodes(self.G, pos, alpha=[0.1, 0.2])
        # with equal alpha elements and nodes
        num_nodes = len(self.G.nodes)
        alpha = [x / num_nodes for x in range(num_nodes)]
        colors = range(num_nodes)
        plt.subplot(132)
        nx.draw_networkx_nodes(self.G, pos, node_color=colors, alpha=alpha)
        # with more alpha elements than nodes
        alpha.append(1)
        plt.subplot(133)
        nx.draw_networkx_nodes(self.G, pos, alpha=alpha) 
Example #28
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 #29
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 #30
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::