Python networkx.draw_networkx_labels() Examples

The following are 30 code examples of networkx.draw_networkx_labels(). 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: svm_utils.py    From ilf with Apache License 2.0 9 votes vote down vote up
def draw_wstate_tree(svm):
    import matplotlib.pyplot as plt
    import networkx as nx
    from networkx.drawing.nx_agraph import write_dot, graphviz_layout

    G = nx.DiGraph()
    pending_list = [svm.root_wstate]
    while len(pending_list):
        root = pending_list.pop()
        for trace, children in root.trace_to_children.items():
            for c in children:
                G.add_edge(repr(root), repr(c), label=trace)
                pending_list.append(c)
    # pos = nx.spring_layout(G)
    pos = graphviz_layout(G, prog='dot')
    edge_labels = nx.get_edge_attributes(G, 'label')
    nx.draw(G, pos)
    nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8)
    nx.draw_networkx_labels(G, pos, font_size=10)
    plt.show() 
Example #2
Source File: igp_graph.py    From FibbingNode with GNU General Public License v2.0 6 votes vote down vote up
def draw_graph(graph, output):
        """If matplotlib is available, draw the given graph to output file"""
        try:
            layout = nx.spring_layout(graph)
            metrics = {
                (src, dst): data['metric']
                for src, dst, data in graph.edges_iter(data=True)
            }
            nx.draw_networkx_edge_labels(graph, layout, edge_labels=metrics)
            nx.draw(graph, layout, node_size=20)
            nx.draw_networkx_labels(graph, layout,
                                    labels={n: n for n in graph})
            if os.path.exists(output):
                os.unlink(output)
            plt.savefig(output)
            plt.close()
            log.debug('Graph of %d nodes saved in %s', len(graph), output)
        except:
            pass 
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: basics.py    From HarvestText with MIT License 6 votes vote down vote up
def build_word_ego_graph():
    import networkx as nx
    import matplotlib.pyplot as plt
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)
    from harvesttext import get_sanguo, get_sanguo_entity_dict, get_baidu_stopwords

    ht0 = HarvestText()
    entity_mention_dict, entity_type_dict = get_sanguo_entity_dict()
    ht0.add_entities(entity_mention_dict, entity_type_dict)
    sanguo1 = get_sanguo()[0]
    stopwords = get_baidu_stopwords()
    docs = ht0.cut_sentences(sanguo1)
    G = ht0.build_word_ego_graph(docs,"刘备",min_freq=3,other_min_freq=2,stopwords=stopwords)
    pos = nx.kamada_kawai_layout(G)
    nx.draw(G,pos)
    nx.draw_networkx_labels(G,pos)
    plt.show()
    G = ht0.build_entity_ego_graph(docs, "刘备", min_freq=3, other_min_freq=2)
    pos = nx.spring_layout(G)
    nx.draw(G, pos)
    nx.draw_networkx_labels(G, pos)
    plt.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: 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 #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: graph_network.py    From network_traffic_modeler_py3 with Apache License 2.0 5 votes vote down vote up
def _draw_node_labels(G):
  # Given networkx graph G, draw node labels
  nx.draw_networkx_labels(G, pos=nx.get_node_attributes(G, 'pos'),
                          labels={data['name']: data['name']
                                  for data in G.nodes.values()}) 
Example #9
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 #10
Source File: test_functionality.py    From HarvestText with MIT License 5 votes vote down vote up
def test_build_word_ego_graph():
    sys.stdout, expected = open(get_current_function_name()+"_current","w"), open(get_current_function_name()+"_expected").read()
    import networkx as nx
    import matplotlib.pyplot as plt
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)
    from harvesttext import get_sanguo, get_sanguo_entity_dict, get_baidu_stopwords

    ht0 = HarvestText()
    entity_mention_dict, entity_type_dict = get_sanguo_entity_dict()
    ht0.add_entities(entity_mention_dict, entity_type_dict)
    sanguo1 = get_sanguo()[0]
    stopwords = get_baidu_stopwords()
    docs = ht0.cut_sentences(sanguo1)
    G = ht0.build_word_ego_graph(docs,"刘备",min_freq=3,other_min_freq=2,stopwords=stopwords)
    pos = nx.kamada_kawai_layout(G)
    nx.draw(G,pos)
    nx.draw_networkx_labels(G,pos)

    G = ht0.build_entity_ego_graph(docs, "刘备", min_freq=3, other_min_freq=2)
    pos = nx.spring_layout(G)
    nx.draw(G, pos)
    nx.draw_networkx_labels(G, pos)


    sys.stdout.close()
    assert open(get_current_function_name() + "_current").read() == expected 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: graph.py    From interact with MIT License 5 votes vote down vote up
def plot_graph(
    interactions, pos=None, node_color='orange',
    edge_color='black', title='',
    fixed_weight=None, weight_offset=1, weight_factor=4,
    layout='spring_layout', layout_parameters={},
    figsize=(12, 12), output_filepath=''
):
    """Plot graph from list of pandas df with interactions."""
    G = nx.Graph()
    G.add_weighted_edges_from(interactions.to_records(index=False))
    weights = [
        (
            fixed_weight if fixed_weight is not None else
            (weight_offset + G[u][v]['weight']) * weight_factor
        )
        for u, v in G.edges()
    ]
    if pos is None:
        pos = layout_factory[layout](G, **layout_parameters)
    plt.figure(figsize=figsize)
    plt.title(title)
    nx.draw(
        G, pos=pos, node_color=node_color, width=weights, edge_color=edge_color
    )
    nx.draw_networkx_labels(
        G, pos=pos,
        bbox=dict(
            boxstyle='round', ec=(0.0, 0.0, 0.0),
            alpha=0.9, fc=node_color, lw=1.5
        )
    )
    if output_filepath:
        plt.savefig(output_filepath, bbox_inches='tight')
    return pos 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: __init__.py    From psst with MIT License 5 votes vote down vote up
def _draw_node_labels(self, labels, **kwargs):
        pos = kwargs.pop('pos', self._pos)
        return nx.draw_networkx_labels(self._G, pos, labels=labels, **kwargs) 
Example #23
Source File: serializer.py    From koala with GNU General Public License v3.0 5 votes vote down vote up
def plot_graph(self):
    import matplotlib.pyplot as plt

    pos=networkx.spring_layout(self.G,iterations=2000)
    #pos=networkx.spectral_layout(G)
    #pos = networkx.random_layout(G)
    networkx.draw_networkx_nodes(self.G, pos)
    networkx.draw_networkx_edges(self.G, pos, arrows=True)
    networkx.draw_networkx_labels(self.G, pos)
    plt.show() 
Example #24
Source File: graph.py    From nelpy with MIT License 5 votes vote down vote up
def draw_transmat_graph(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

    labels = {}
    labels[0] = '1'
    labels[1]= '2'
    labels[2]= '3'
    labels[num_states-1] = str(num_states)

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

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

    nx.draw_networkx_nodes(G, npos, node_size=node_size, node_color='k',alpha=0.8)
    ax = plt.gca()
    nx.draw_networkx_labels(G, lpos, labels, fontsize=18, ax=ax); # fontsize does not seem to work :/

    ax.set_aspect('equal')

    return ax 
Example #25
Source File: animation.py    From YAFS with MIT License 5 votes vote down vote up
def make_snap(self, step, output_file="None",draw_connection_line=False,G=None):
        self.track_code_last_position = self.get_all_points_from_videoframe(step)

        self.axarr.texts = []
        self.clear_frequency()
        self.update_coverage_regions()
        self.show_frequency(draw_connection_line=draw_connection_line)

        # showing the STEP in the upper left corner of the figure
        size = self.fig.get_size_inches() * self.fig.dpi
        plt.text(size[0]*0.02, size[1]*0.05,"Step: %i"%step, dict(size=10, color='b'))

        # showing the GRAPH
        if G !=None:
            pos = nx.spring_layout(G,seed=1)
            # pos = map_endpoints
            pos = [[pos[x][0], pos[x][1]] for x in G.nodes()]
            pos = np.array(pos)
            pos[:, 0] = (pos[:, 0] - pos[:, 0].min()) / (pos[:, 0].max() - pos[:, 0].min())
            pos[:, 1] = (pos[:, 1] - pos[:, 1].min()) / (pos[:, 1].max() - pos[:, 1].min())
            size = self.fig.get_size_inches() * self.fig.dpi * 1.5
            pos = [self.point_network_map(x, size) for x in pos]
            pos = dict(zip(G.nodes(),pos))

            nx.draw(G, pos,with_labels=False,node_size=100,nodelist=self.sim.name_endpoints.values(),node_color="#1260A0",node_shape="o")
            # rest_nodes = [e for e in G.nodes() if e not in self.sim.name_endpoints.values()]
            nodes_level_mobile = self.get_nodes_by_level(G,-1)
            nobes_upper_level = self.get_nodes_by_upper_level(G,1)
            nx.draw(G, pos,with_labels=False,node_size=100,nodelist=nodes_level_mobile,node_shape="^",node_color="orange")
            nx.draw(G, pos,with_labels=True,node_size=100,nodelist=nobes_upper_level,node_shape="s",node_color="red",font_size=8)
            # labels = nx.draw_networkx_labels(G, pos)



        canvas = plt.get_current_fig_manager().canvas
        canvas.draw()
        pil_image = Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb())
        pil_image.save(output_file+".png")
        plt.close('all') 
Example #26
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 #27
Source File: topology.py    From YAFS with MIT License 5 votes vote down vote up
def draw_png(self,path_file):
        fig, ax = plt.subplots(nrows=1, ncols=1)
        pos = nx.spring_layout(self.G)
        nx.draw(self.G, pos)
        labels = nx.draw_networkx_labels(self.G, pos)
        fig.savefig(path_file)  # save the figure to file
        plt.close(fig)  # close the figure 
Example #28
Source File: em_help.py    From mapper-tda with MIT License 5 votes vote down vote up
def plot_graph(G, filename='prova.png', values=None, colorbar_obj=None):
    
    func_types_dic = {
                'spring' : nx.spring_layout,
                'random' : nx.random_layout,
                'shell' : nx.shell_layout,
                'spectral' : nx.spectral_layout,
                'viz' : graphviz_layout
                }

    print(G.edges())
    print(G.nodes())

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)

    color_nodes = [values.get(node, 0.2) for node in G.nodes()] 

    pos = func_types_dic[params.plot_type_str](G)

    nodes = nx.draw_networkx_nodes(G, pos, node_color=color_nodes, \
            alpha=.6)#, cmap=plt.get_cmap('brg'))

    nx.draw_networkx_edges(G, pos, width=2.)
    nx.draw_networkx_labels(G, pos, font_color='k', font_weight='10')
    plt.title("|V| = %d, |E| = %d"%(len(G.nodes()), len(G.edges())))
    colorbar_obj.set_array(color_nodes)
    plt.colorbar(colorbar_obj)
    plt.axis('off')
    fig.savefig(filename, format='png')
    plt.close() 
Example #29
Source File: syngraph.py    From atap with Apache License 2.0 5 votes vote down vote up
def draw_text_graph(G):
    plt.figure(figsize=(18,12))
    pos = nx.spring_layout(G, scale=18)
    nx.draw_networkx_nodes(G, pos, node_color="white", linewidths=0, node_size=500)
    nx.draw_networkx_labels(G, pos, font_size=10)
    nx.draw_networkx_edges(G, pos)
    plt.xticks([])
    plt.yticks([]) 
Example #30
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()