Python networkx.draw_networkx_edge_labels() Examples

The following are 19 code examples of networkx.draw_networkx_edge_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: Measurements.py    From marve with Apache License 2.0 7 votes vote down vote up
def _build_graph(show=False):
    """Load word dependencies into graph using networkx. Enables easy traversal of dependencies for parsing particular patterns.
    One graph is created for each sentence.

    Args:
        show (bool): If set to True, labeled visualization of network will be opened via matplotlib for each sentence

    Returns:
        None: Global variable G is set from within function

    """
    global G
    G = nx.Graph()
    node_labels, edge_labels = {}, {}
    for idx, dep in enumerate(A.deps):

        types = ["dependent", "governor"]

        # nodes, labels
        for x in types:
            G.add_node(str(dep[x]), word=dep[x + "Gloss"], pos=A.lookup[dep[x]]["pos"])
            node_labels[str(dep[x])] = dep[x + "Gloss"] + " : " + A.lookup[dep[x]]["pos"]

        # edges, labels
        G.add_edge(str(dep[types[0]]), str(dep[types[1]]), dep=dep["dep"])
        edge_labels[(str(dep[types[0]]), str(dep[types[1]]))] = dep["dep"]

    if show == True:
        pos = nx.spring_layout(G)
        nx.draw_networkx(G, pos=pos, labels=node_labels, node_color="white", alpha=.5)
        nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
        plt.show()


#########################################
# Dependency / POS parsing functions
######################################### 
Example #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: 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 #5
Source File: analyze_graph.py    From flee-release with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_graph_nx(vertices, edges, print_dist=False):
  import networkx as nx
  G=nx.DiGraph()
  labels = []

  for v in vertices:
    G.add_node(v)

  for v in vertices:
    for e in edges:
      G.add_edge(e[0], e[1], weight=int(e[2]))
      #labels += [(e[0], e[1]), e[2]]

  print("Nodes of graph: ")
  print(G.nodes())
  print("Edges of graph: ")
  print(G.edges())

  nx.draw(G, with_labels=True, node_color='y')
  #nx.draw_networkx_edge_labels(G,labels)
  plt.savefig("simulation_graph.png") # save as png
  plt.show() 
Example #6
Source File: Planner.py    From GOApy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot(self, file_path: str):
        try:
            import matplotlib.pyplot as plt
        except ImportError as err:
            raise('matplotlib not installed. Failed at: {}', err)

        try:
            pos = nx.nx_agraph.graphviz_layout(self.directed)
            nx.draw(
                self.directed,
                pos=pos,
                node_size=1200,
                node_color='lightblue',
                linewidths=0.25,
                font_size=8,
                font_weight='bold',
                with_labels=True,
                dpi=5000
            )
            # edge_labels = nx.get_edge_attributes(self.directed, name='attr_dict')
            # nx.draw_networkx_edge_labels(self.directed, pos=pos, edge_labels=edge_labels)
            plt.savefig(file_path)
        except IOError as err:
            raise('Could not create plot image: {}', err) 
Example #7
Source File: visualise_graph.py    From IDTxl with GNU General Public License v3.0 5 votes vote down vote up
def _plot_graph(graph, axis, weights=None, display_edge_labels=True):
    """Plot graph using networkx."""
    pos = nx.circular_layout(graph)
    nx.draw_circular(graph, with_labels=True, node_size=600, alpha=1.0,
                     ax=axis, node_color='Gainsboro', hold=True, font_size=14,
                     font_weight='bold')
    if display_edge_labels:
        edge_labels = nx.get_edge_attributes(graph, weights)
        nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels,
                                     font_size=13)  # font_weight='bold' 
Example #8
Source File: visualise_graph.py    From IDTxl with GNU General Public License v3.0 5 votes vote down vote up
def plot_mute_graph():
    """Plot MuTE example network.

    Network of 5 AR-processes, which is used as an example the paper
    on the MuTE toolbox (Montalto, PLOS ONE, 2014, eq. 14). The
    network consists of five autoregressive (AR) processes with model
    orders 2 and les and the following (non-linear) couplings:

        >>> 0 -> 1, u = 2
        >>> 0 -> 2, u = 3
        >>> 0 -> 3, u = 2 (non-linear)
        >>> 3 -> 4, u = 1
        >>> 4 -> 3, u = 1

    Returns:
        Figure handle
            Figure object from the matplotlib package
    """
    graph = nx.DiGraph()
    graph.add_nodes_from(np.arange(5))
    # graph.add_edges_from([(0, 1), (0, 2), (0, 3), (3, 4), (4, 3)])
    graph.add_weighted_edges_from([(0, 1, 2), (0, 2, 3), (0, 3, 2), (3, 4, 1),
                                   (4, 3, 1)], weight='delay')
    pos = {
        0: np.array([1, 1]),
        1: np.array([0, 2]),
        2: np.array([0, 0]),
        3: np.array([2, 1]),
        4: np.array([3, 1]),
    }
    fig = plt.figure()
    nx.draw(graph, pos=pos, with_labels=True, node_size=900, alpha=1.0,
            node_color='cadetblue', font_weight='bold',
            edge_color=['r', 'k', 'r', 'k', 'k'], hold=True)
    nx.draw_networkx_edge_labels(graph, pos=pos)
    plt.text(2, 0.1, 'non-linear interaction in red')
    # see here for an example on how to plot edge labels:
    # http://stackoverflow.com/questions/10104700/how-to-set-networkx-edge-labels-offset-to-avoid-label-overlap
    return fig 
Example #9
Source File: representations.py    From KG-A2C with MIT License 5 votes vote down vote up
def visualize(self):
        # import matplotlib.pyplot as plt
        pos = nx.spring_layout(self.graph_state)
        edge_labels = {e: self.graph_state.edges[e]['rel'] for e in self.graph_state.edges}
        print(edge_labels)
        nx.draw_networkx_edge_labels(self.graph_state, pos, edge_labels)
        nx.draw(self.graph_state, pos=pos, with_labels=True, node_size=200, font_size=10)
        #plt.show() 
Example #10
Source File: main.py    From network-programmability-stream with MIT License 5 votes vote down vote up
def draw_and_save_topology(graph: nx.Graph, edge_labels: List[Dict[Tuple[str, str], str]]) -> None:
    plt.figure(1, figsize=(12, 12))
    pos = nx.spring_layout(graph)
    nx.draw_networkx(graph, pos, node_size=1300, node_color='orange')
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[0], label_pos=0.8)
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[1], label_pos=0.2)
    filename = "topology.png"
    plt.savefig(filename)
    logger.info("The network topology diagram has been saved to %r", filename) 
Example #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: 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 #13
Source File: __init__.py    From psst with MIT License 5 votes vote down vote up
def _draw_edge_labels(self, edge_labels, **kwargs):
        pos = kwargs.pop('pos', self._pos)
        return nx.draw_networkx_edge_labels(self._G, pos, edge_labels=edge_labels, **kwargs) 
Example #14
Source File: plotnxgraph.py    From complex_network with GNU General Public License v2.0 5 votes vote down vote up
def plot_graph(G, out_file=None, node_size=1500, font_size=10,
				node_and_labels=None, edge_and_labels=None):
	"""
	plot a graph
	"""

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

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

	plt.axis('off')	

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

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

	plt.show() 
Example #15
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 #16
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 #17
Source File: plot.py    From psst with MIT License 4 votes vote down vote up
def plot_network_with_results(psstc, model, time=0):
    G = create_network(psstc)

    fig, axs = plt.subplots(1, 1, figsize=(12, 9))
    ax = axs

    line_color_dict = dict()
    hour = 0
    for i, b in branch_df.iterrows():
        if model.ThermalLimit[i] != 0:
            line_color_dict[(b['F_BUS'], b['T_BUS'])] = round(abs(model.LinePower[i, hour].value / model.ThermalLimit[i]), 2)
        else:
            line_color_dict[(b['F_BUS'], b['T_BUS'])] = 0

    gen_color_dict = dict()
    hour = 0
    for i, g in generator_df.iterrows():
        gen_color_dict[(i, g['GEN_BUS'])] = round(abs(model.PowerGenerated[i, hour].value / model.MaximumPowerOutput[i]), 2)

    color_dict = line_color_dict.copy()
    color_dict.update(gen_color_dict)

    edge_color = list()

    for e in G.edges():
        try:
            edge_color.append( color_dict[(e[0], e[1])] )
        except KeyError:
            edge_color.append( color_dict[(e[1], e[0])] )

    ax.axis('off')
    pos = graphviz_layout(G, prog='sfdp')
    nx.draw_networkx_nodes(G, pos, list(generator_df.index),)
    nx.draw_networkx_nodes(G, pos, list(bus_df.index), node_color='black',)
    edges = nx.draw_networkx_edges(G, pos, edge_color=edge_color, edge_cmap=cmap, width=3)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=color_dict)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("left", size="5%", pad=0.05)
    cb = plt.colorbar(edges, cax=cax)
    cax.yaxis.set_label_position('left')
    cax.yaxis.set_ticks_position('left')
    # cb.set_label('Voltage (V)') 
Example #18
Source File: graphviz.py    From complex_network with GNU General Public License v2.0 4 votes vote down vote up
def plot_graph(cls, G, filename=None, node_attribute_name='id', edge_attribute_name=None, 
                    colored_nodes=None, colored_edges=None, colored_path=None, **kwargs):
    #def plot_graph(self, G, out_file, **kwd):
        """plot graph"""
        plt.clf()

        # get the layout of G
        pos = nx.get_node_attributes(G, 'pos')
        if not pos:
            pos = nx.spring_layout(G)

        # get node attributes
        with_labels = False
        node_labels = None
        if node_attribute_name == 'id':
            with_labels = True
        elif node_attribute_name:
            node_labels = nx.get_node_attributes(G, node_attribute_name)

        # get edge attributes
        if not edge_attribute_name:
            edge_labels = nx.get_edge_attributes(G, edge_attribute_name)

        # colored nodes
        node_default_color = '0.75' # Gray shades 

        node_color = node_default_color
        if colored_nodes:
            node_color = ['r' if node in colored_nodes else node_default_color
                            for node in G.nodes()]

        # colored path
        if colored_path:
            nrof_nodes = len(colored_path)
            idx = 0
            colored_edges = list()
            while idx < nrof_nodes-1:
                colored_edges.append((colored_path[idx], colored_path[idx+1]))
                idx += 1

        # colored edges
        edge_default_color = 'k' # black
        edge_color = edge_default_color
        if colored_edges:
            set_colored_edges = {frozenset(t) for t in colored_edges}  # G.edges returns a list of 2-tuples

            edge_color = ['r' if frozenset([u, v]) in set_colored_edges else edge_default_color
                            for u, v in G.edges()]


        # draw 
        nx.draw(G, pos, with_labels=with_labels, node_color=node_color, edge_color=edge_color, **kwargs)
        if node_labels:
            nx.draw_networkx_labels(G, pos, labels=node_labels)
        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

        if filename:
            plt.savefig(filename, bbox_inches='tight', pad_inches=0)
        else:
            plt.show() 
Example #19
Source File: bpmn_diagram_visualizer.py    From bpmn-python with GNU General Public License v3.0 4 votes vote down vote up
def visualize_diagram(bpmn_diagram):
    """
    Shows a simple visualization of diagram

    :param bpmn_diagram: an instance of BPMNDiagramGraph class.
    """
    g = bpmn_diagram.diagram_graph
    pos = bpmn_diagram.get_nodes_positions()
    nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task))
    nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess))
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway))
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway))
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway))
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway))
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway))
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event))
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event))
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event))
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
                           nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event))

    node_labels = {}
    for node in g.nodes(data=True):
        node_labels[node[0]] = node[1].get(consts.Consts.node_name)
    nx.draw_networkx_labels(g, pos, node_labels)

    nx.draw_networkx_edges(g, pos)

    edge_labels = {}
    for edge in g.edges(data=True):
        edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name)
    nx.draw_networkx_edge_labels(g, pos, edge_labels)

    plt.show()