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 Project: ilf   Author: eth-sri   File:    License: Apache License 2.0 8 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)
    # 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) 
Example #2
Source Project: marve   Author: khundman   File:    License: 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.

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

        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)

# Dependency / POS parsing functions
Example #3
Source Project: AMLSim   Author: IBM   File:    License: 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))

    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.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.savefig(_output_png, dpi=120) 
Example #4
Source Project: GOApy   Author: leopepe   File:    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot(self, file_path: str):
            import matplotlib.pyplot as plt
        except ImportError as err:
            raise('matplotlib not installed. Failed at: {}', err)

            pos = nx.nx_agraph.graphviz_layout(self.directed)
            # edge_labels = nx.get_edge_attributes(self.directed, name='attr_dict')
            # nx.draw_networkx_edge_labels(self.directed, pos=pos, edge_labels=edge_labels)
        except IOError as err:
            raise('Could not create plot image: {}', err) 
Example #5
Source Project: flee-release   Author: djgroen   File:    License: 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
  labels = []

  for v in vertices:

  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("Edges of graph: ")

  nx.draw(G, with_labels=True, node_color='y')
  plt.savefig("simulation_graph.png") # save as png 
Example #6
Source Project: FibbingNode   Author: Fibbing   File:    License: 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"""
            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):
            log.debug('Graph of %d nodes saved in %s', len(graph), output)
Example #7
Source Project: indras_net   Author: gcallah   File:    License: 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

Example #8
Source Project: psst   Author: power-system-simulation-toolbox   File:    License: 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 #9
Source Project: network-programmability-stream   Author: dmfigol   File:    License: 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)"The network topology diagram has been saved to %r", filename) 
Example #10
Source Project: KG-A2C   Author: rajammanabrolu   File:    License: 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}
        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) 
Example #11
Source Project: IDTxl   Author: pwollstadt   File:    License: 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,
    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 #12
Source Project: IDTxl   Author: pwollstadt   File:    License: 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

        Figure handle
            Figure object from the matplotlib package
    graph = nx.DiGraph()
    # 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:
    return fig 
Example #13
Source Project: indra   Author: sorgerlab   File:    License: 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

    stmts : list[indra.statements.Statement]
        A list of one or more INDRA Statements whose attribute graph should
        be drawn.
    import networkx
        import matplotlib.pyplot as plt
    except Exception:
        logger.error('Could not import matplotlib, not drawing graph.')
    try:  # This checks whether networkx has this package to work with.
        import pygraphviz
    except Exception:
        logger.error('Could not import pygraphviz, not drawing graph.')
    import numpy
    g = networkx.compose_all([stmt.to_graph() for stmt in stmts])
    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)
    # 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)
Example #14
Source Project: costar_plan   Author: jhu-lcsr   File:    License: Apache License 2.0 5 votes vote down vote up
def showTask(task, root="ROOT()", filename=""):
    import matplotlib.pyplot as plt

    g = nx.DiGraph()

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


    while len(nodes) > 0:
        node = nodes.pop()
        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))
                if child not in visited:
                    print("\t\tadding", 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')
    #a = nx.nx_agraph.to_agraph(g)
    #a.draw('ex.png', prog='dot')
Example #15
Source Project: complex_network   Author: sparkandshine   File:    License: 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, 
						labels = node_and_labels,


	if edge_and_labels:
		nx.draw_networkx_edge_labels(G, pos, 

	if out_file:
		plt.savefig(out_file, bbox_inches='tight') 
Example #16
Source Project: zincbase   Author: tomgrek   File:    License: 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)
        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)
Example #17
Source Project: psst   Author: power-system-simulation-toolbox   File:    License: 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)
            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()

    edge_color = list()

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

    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)
    # cb.set_label('Voltage (V)') 
Example #18
Source Project: complex_network   Author: sparkandshine   File:    License: 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"""

        # 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)
Example #19
Source Project: bpmn-python   Author: KrzyHonk   File:    License: 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',
    nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
    nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',

    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(
    nx.draw_networkx_edge_labels(g, pos, edge_labels)