Python networkx.draw() Examples

The following are 30 code examples of networkx.draw(). 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: time_align.py    From scanorama with MIT License 7 votes vote down vote up
def time_align_visualize(alignments, time, y, namespace='time_align'):
    plt.figure()
    heat = np.flip(alignments + alignments.T +
                   np.eye(alignments.shape[0]), axis=0)
    sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1)
    plt.savefig(namespace + '_heatmap.svg')

    G = nx.from_numpy_matrix(alignments)
    G = nx.maximum_spanning_tree(G)

    pos = {}
    for i in range(len(G.nodes)):
        pos[i] = np.array([time[i], y[i]])

    mst_edges = set(nx.maximum_spanning_tree(G).edges())
    
    weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8
                for u, v in G.edges() ]
    
    plt.figure()
    nx.draw(G, pos, edges=G.edges(), width=10)
    plt.ylim([-1, 1])
    plt.savefig(namespace + '.svg') 
Example #3
Source File: function.py    From angr with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def dbg_draw(self, filename):
        """
        Draw the graph and save it to a PNG file.
        """
        import matplotlib.pyplot as pyplot  # pylint: disable=import-error
        from networkx.drawing.nx_agraph import graphviz_layout  # pylint: disable=import-error

        tmp_graph = networkx.DiGraph()
        for from_block, to_block in self.transition_graph.edges():
            node_a = "%#08x" % from_block.addr
            node_b = "%#08x" % to_block.addr
            if node_b in self._ret_sites:
                node_b += "[Ret]"
            if node_a in self._call_sites:
                node_a += "[Call]"
            tmp_graph.add_edge(node_a, node_b)
        pos = graphviz_layout(tmp_graph, prog='fdp')   # pylint: disable=no-member
        networkx.draw(tmp_graph, pos, node_size=1200)
        pyplot.savefig(filename) 
Example #4
Source File: wsngenerator.py    From rpl-attacks with GNU Affero General Public License v3.0 6 votes vote down vote up
def draw_wsn(motes=None, algo='quadrants', **kwargs):
    """
    This function allows to draw the list of motes generated with one of the WSN generation functions hereafter.

    :param motes: a list of motes as output by one of the WSN generation functions hereafter
    """
    assert algo in __all__
    import networkx as nx
    from matplotlib import pyplot as plt
    motes = motes or eval(algo)(**kwargs)
    wsn = nx.Graph()
    for mote in motes:
        wsn.add_node(mote['id'])
    pos = {m['id']: (m['x'], m['y']) for m in motes}
    col = ['green'] + (len(motes) - 2) * ['blue'] + ['red']
    nx.draw(wsn, pos, node_color=col)
    plt.show() 
Example #5
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 #6
Source File: graph.py    From biolink-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self, id):
        """
        Returns evidence graph as a png

        TODO - requires matplotlib which is hard to install
        """
        args = parser.parse_args()

        assoc = get_association(id, user_agent=USER_AGENT)
        eg = {'graphs':[assoc.get('evidence_graph')]}
        digraph = convert_json_object(eg)
        #fp = tempfile.TemporaryFile()
        nx.draw(digraph)
        fn = '/tmp/'+id+'.png' # TODO
        #plt.savefig(fn)
        return send_file(fn) 
Example #7
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 #8
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 #9
Source File: io_utils.py    From gnn-model-explainer with Apache License 2.0 6 votes vote down vote up
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend("agg")
    fig = plt.figure(figsize=(8, 6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i + 1)
        plt.imshow(
            assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap("BuPu")
        )
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    writer.add_image("assignment", data, epoch)

# TODO: unify log_graph and log_graph2 
Example #10
Source File: io_utils.py    From gnn-model-explainer with Apache License 2.0 6 votes vote down vote up
def log_matrix(writer, mat, name, epoch, fig_size=(8, 6), dpi=200):
    """Save an image of a matrix to disk.

    Args:
        - writer    :  A file writer.
        - mat       :  The matrix to write.
        - name      :  Name of the file to save.
        - epoch     :  Epoch number.
        - fig_size  :  Size to of the figure to save.
        - dpi       :  Resolution.
    """
    plt.switch_backend("agg")
    fig = plt.figure(figsize=fig_size, dpi=dpi)
    mat = mat.cpu().detach().numpy()
    if mat.ndim == 1:
        mat = mat[:, np.newaxis]
    plt.imshow(mat, cmap=plt.get_cmap("BuPu"))
    cbar = plt.colorbar()
    cbar.solids.set_edgecolor("face")

    plt.tight_layout()
    fig.canvas.draw()
    writer.add_image(name, tensorboardX.utils.figure_to_image(fig), epoch) 
Example #11
Source File: utilities.py    From entropica_qaoa with Apache License 2.0 6 votes vote down vote up
def plot_graph(G, ax=None):
    """
    Plots a networkx graph.

    Parameters
    ----------
    G:
        The networkx graph of interest.
    ax: Matplotlib axes object
        Defaults to None. Matplotlib axes to plot on.
    """

    weights = np.real([*nx.get_edge_attributes(G, 'weight').values()])
    pos = nx.shell_layout(G)

    nx.draw(G, pos, node_color='#A0CBE2', with_labels=True, edge_color=weights,
            width=4, edge_cmap=plt.cm.Blues, ax=ax)
    plt.show()


#############################################################################
# HAMILTONIANS AND DATA
############################################################################# 
Example #12
Source File: train.py    From diffpool with MIT License 6 votes vote down vote up
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend('agg')
    fig = plt.figure(figsize=(8,6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i+1)
        plt.imshow(assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap('BuPu'))
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    #data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    #data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    data = tensorboardX.utils.figure_to_image(fig)
    writer.add_image('assignment', data, epoch) 
Example #13
Source File: nx_pylab.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def draw_shell(G, **kwargs):
    """Draw networkx graph with shell layout.

    Parameters
    ----------
    G : graph
       A networkx graph

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    nlist = kwargs.get('nlist', None)
    if nlist is not None:
        del(kwargs['nlist'])
    draw(G, shell_layout(G, nlist=nlist), **kwargs) 
Example #14
Source File: reservoir.py    From Reservoir with MIT License 6 votes vote down vote up
def run(self):
        with open('reservoir.output', 'a') as output:
            prompt = '# ' + str(datetime.datetime.now()) + \
                '\n' + json.dumps(config, indent=4) + '\n'
            print(prompt, end='')
            output.write(prompt)
            for i in range(self.start_node, self.end_node + 1, self.step):
                self.N = i
                self.D = self.degree_func(self.N)
                self.train()
                self._run()
                for j in range(1):
                  res = 'N = ' + str(self.N) + ', D = ' + '%.15f' % self.D + \
                      ', RMS = ' + '%.15e' % Decimal(self.RMS[j]) + '\n'
                  print(res, end='')
                output.write(res)
                config["reservoir"]["start_node"] = i
                self.draw()


# Invoke automatically when exit, write the progress back to config file 
Example #15
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 #16
Source File: hgnn_composer.py    From modular-metalearning with MIT License 6 votes vote down vote up
def visualize_graph(self):
    # import networkx as nx
    G = nx.Graph()
    G.add_nodes_from(list(range(1, self.structure["num_nodes"])))
    for i, edge in enumerate(map(tuple, self.structure['graph']["edges"])):
      type = 'r' if self.structure["edge_idx_inv"][i] else 'b'
      G.add_edge(*edge, color=type, weight=5)

    # edges = G.edges()
    # colors = [G[u][v]['color'] for u, v in edges]
    # weights = [G[u][v]['weight'] for u, v in edges]
    # nx.draw(G, edges=edges, edge_color=colors, width=5, with_labels=True, font_weight='bold')
    # # plt.show()
    # from datetime import datetime

    # plt.savefig('runs/{}.png'.format(datetime.now())) 
Example #17
Source File: igp_graph.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def draw_graph(*_):
        """Can't draw without matplotlib"""
        pass 
Example #18
Source File: structure_data.py    From lammps_interface with MIT License 5 votes vote down vote up
def show(self):
        nx.draw(self) 
Example #19
Source File: nx_pylab.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def draw_spectral(G, **kwargs):
    """Draw the graph G with a spectral layout.

    Parameters
    ----------
    G : graph
       A networkx graph

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    draw(G, spectral_layout(G), **kwargs) 
Example #20
Source File: nx_pylab.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def draw_random(G, **kwargs):
    """Draw the graph G with a random layout.

    Parameters
    ----------
    G : graph
       A networkx graph

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    draw(G, random_layout(G), **kwargs) 
Example #21
Source File: nx_pylab.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def draw_circular(G, **kwargs):
    """Draw the graph G with a circular layout.

    Parameters
    ----------
    G : graph
       A networkx graph

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    draw(G, circular_layout(G), **kwargs) 
Example #22
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 #23
Source File: datastructures.py    From sanskrit_parser with MIT License 5 votes vote down vote up
def draw(self, *args, **kwargs):
        _ncache = {}

        def _uniq(s):
            if s not in _ncache:
                _ncache[s] = 0
                return s
            else:
                _ncache[s] = _ncache[s] + 1
                return s + "_" + str(_ncache[s])

        nx.draw(self.G, *args, **kwargs,
                pos=nx.graph_layout(self),
                labels={x: _uniq(str(x)) for x in self}) 
Example #24
Source File: igp_graph.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def draw(self, dest):
        """Draw this graph to dest"""
        draw_graph(self, dest) 
Example #25
Source File: visualization.py    From PyCHAMELEON with MIT License 5 votes vote down vote up
def plot_graph(graph):
    pos = nx.get_node_attributes(graph, 'pos')
    c = [colors[i%(len(colors))] for i in nx.get_node_attributes(graph, 'cluster').values()]
    if c: # is set
        nx.draw(graph, pos, node_color=c, node_size=0.2)
    else:
        nx.draw(graph, pos)
    plt.show(block=False) 
Example #26
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 #27
Source File: graph.py    From osint-suite-tools with GNU General Public License v3.0 5 votes vote down vote up
def get_GraphNodePersonalData(target):

    print("|----[INFO][GRAPH][>] starting to draw...")

    companies = config.companiesData_list
    emails = config.emailsData_list
    phones = config.phonesData_list
    DNIs = config.DNIData_list

    print (str(companies))

    g = nx.Graph()

    g.add_edge(target, "Companies")
    g.add_edge(target, "Phones")
    g.add_edge(target, "Emails")
    g.add_edge(target, "DNI")


    for company in companies:
        g.add_edge("Companies", company)
    
    for email in emails:
        g.add_edge("Emails", email)

    for phone in phones:
        g.add_edge("Phones", phone)
    
    for dni in DNIs:
        g.add_edge("DNI", dni)

    PNG = target.replace(" ", "-")
    nx.draw(g, with_labels = True) 
    plt.savefig(f"{PNG}.png") 
Example #28
Source File: plot_graph.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def main(args,root="root"):
	# init graph
	graph = nx.DiGraph()
	node_list = set()
	node_list.add(root)

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

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

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

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

	plt.axis
	plt.show() 
Example #29
Source File: c10_22_binomial_graph.py    From Python-for-Finance-Second-Edition with MIT License 5 votes vote down vote up
def binomial_grid(n): 
    G=nx.Graph()
    for i in range(0,n+1):
        for j in range(1,i+2): 
            if i<n:
                G.add_edge((i,j),(i+1,j))
                G.add_edge((i,j),(i+1,j+1))
    posG={}
    for node in G.nodes(): 
        posG[node]=(node[0],n+2+node[0]-2*node[1])
    nx.draw(G,pos=posG) 
Example #30
Source File: test_from_joel.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def test_Snapshot_Dynamics_And_TransmissionTree(self):
        G = nx.karate_club_graph()

        nx_kwargs = {"with_labels": True}
        sim = EoN.Gillespie_SIR(G, 1, 1, return_full_data=True)
        sim.display(time=1, **nx_kwargs)
        plt.savefig('test_Snapshot_Dynamics_And_TransmissionTree_1')

        T = sim.transmission_tree()
        Tpos = EoN.hierarchy_pos(T)

        fig = plt.figure(figsize=(8, 5))
        ax = fig.add_subplot(111)
        nx.draw(T, Tpos, ax=ax, node_size=200, with_labels=True)
        plt.savefig('test_Snapshot_Dynamics_And_TransmissionTree_2')