• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python nx_agraph.graphviz_layout函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.drawing.nx_agraph.graphviz_layout函数的典型用法代码示例。如果您正苦于以下问题:Python graphviz_layout函数的具体用法?Python graphviz_layout怎么用?Python graphviz_layout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了graphviz_layout函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

def main():
    # Create a directed graph
    G = nx.DiGraph()

    # An example
    l=[ ('a','b'),
        ('b','c'),
        ('c','d'),
        ('d','e'),
        ('e','f'),
        ('w','x'),
        ('w','t'),
        ('t','q'),
        ('q','r'),
        ('q','u')]

    # Build up a graph
    for t in l:
        G.add_edge(t[0], t[1])

    # Plot trees
    pos = graphviz_layout(G, prog='dot')
    nx.draw(G, pos, with_labels=True, arrows=False)

    plt.savefig('draw_trees_with_pygraphviz.png', bbox_inches='tight')   
    plt.show()
开发者ID:sparkandshine,项目名称:complex_network,代码行数:26,代码来源:draw_trees_with_pygraphviz.py


示例2: draw_graph

def draw_graph(nodes, edges, graphs_dir, default_lang='all'):
    lang_graph = nx.MultiDiGraph()
    lang_graph.add_nodes_from(nodes)
    for edge in edges:
        if edges[edge] == 0:
            lang_graph.add_edge(edge[0], edge[1])
        else:
            lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge]))

    # print graph info in stdout
    # degree centrality
    print('-----------------\n\n')
    print(default_lang)
    print(nx.info(lang_graph))
    try:
        # When ties are associated to some positive aspects such as friendship or collaboration,
        #  indegree is often interpreted as a form of popularity, and outdegree as gregariousness.
        DC = nx.degree_centrality(lang_graph)
        max_dc = max(DC.values())
        max_dc_list = [item for item in DC.items() if item[1] == max_dc]
    except ZeroDivisionError:
        max_dc_list = []
    # https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8
    print('maxdc', str(max_dc_list), sep=': ')
    # assortativity coef
    AC = nx.degree_assortativity_coefficient(lang_graph)
    print('AC', str(AC), sep=': ')
    # connectivity
    print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph))
    print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph))
    print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph))
    print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph))
    print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph))
    print("число вершинной связности: ", nx.node_connectivity(lang_graph))
    print("число рёберной связности: ", nx.edge_connectivity(lang_graph))
    # other info
    print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph))
    print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(),
                                              key=itemgetter(1), reverse=True))
    # best for small graphs, and our graphs are pretty small
    print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True))

    plt.figure(figsize=(16.0, 9.0), dpi=80)
    plt.axis('off')
    pos = graphviz_layout(lang_graph)
    nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True)
    nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green')
    nx.draw_networkx_edge_labels(lang_graph, pos, edges)

    # saving file to draw it with dot-graphviz
    # changing overall graph view, default is top-bottom
    lang_graph.graph['graph'] = {'rankdir': 'LR'}
    # marking with blue nodes with maximum degree centrality
    for max_dc_node in max_dc_list:
        lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue'
    write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot'))

    # plt.show()
    plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100)
    plt.close()
开发者ID:irinfox,项目名称:minor_langs_internet_analysis,代码行数:60,代码来源:get_links_info.py


示例3: draw

    def draw(self, zscale=1):
        for n in self.history:
            if len(self.history[n]) % 2 != 0:
                self.history[n].append(self.turn)
        pos = graphviz_layout(self.wot, "twopi")

        for n in self.history:
            periods = list(zip(self.history[n], self.history[n][1:]))
            for i, p in enumerate(periods):
                nbpoints = abs(p[1] - p[0])*zscale
                zline = linspace(p[0]*zscale, p[1]*zscale, nbpoints)
                xline = linspace(pos[n][0], pos[n][0], nbpoints)
                yline = linspace(pos[n][1], pos[n][1], nbpoints)
                plot = self.ax.plot(xline, zline, yline, zdir='y', color=self.colors[n][0], alpha=1/(i % 2 + 1))

        for link in self.past_links:
            nbpoints = abs(pos[link[2]][0] - pos[link[1]][1])*zscale
            zline = linspace(link[0]*zscale, link[0]*zscale, nbpoints)
            xline = linspace(pos[link[2]][0], pos[link[1]][0], nbpoints)
            yline = linspace(pos[link[2]][1], pos[link[1]][1], nbpoints)
            if link[1] in self.colors:
                self.ax.plot(xline, zline, yline, zdir='y', color=self.colors[link[1]][0], alpha=0.1)

            #txt = self.ax.text(pos[n][0], pos[n][1], self.history[n][0]*zscale, n[:5], 'z')

        self.ax.set_xlim3d(-5, max([p[0] for p in pos.values()]))
        self.ax.set_ylim3d(-5, max([p[1] for p in pos.values()]))
        self.ax.set_zlim3d(-5, (self.turn+1)*zscale)
开发者ID:Insoleet,项目名称:wot_stories,代码行数:28,代码来源:wot.py


示例4: main

def main( ):
    g = nx.DiGraph( )
    # Add x nodes.
    xs = np.arange(0, 11)
    ys = np.arange(0, 11)

    [ g.add_node( 'x=%d' % i, w = i ) for i in xs ]
    [ g.add_node( 'y=%d' % i, w = i ) for i in ys ]

    # Now add edges.
    img = { }
    for x in xs:
        for z in [1,2,3]:
            y = (x + z) % 11
            g.add_edge( 'x=%d' % x, 'y=%d' % y, label='z=%d' % z, prob=1/3)
            print( '%d + %d -> %d' % (x, z, y) )
            img[ (x, y) ] = 1/3

    mat = np.zeros( shape=(11,11) )
    for k, v in img.items( ):
        mat[ k ] = v

    nx.draw_networkx( g, pos = graphviz_layout( g, 'dot' ) )
    nx.drawing.nx_agraph.write_dot( g, 'network.dot' )
    plt.savefig( 'graph.png' )
开发者ID:dilawar,项目名称:Courses,代码行数:25,代码来源:hw51.py


示例5: drawTrie

    def drawTrie(trie_dict):
        """
        Draws the trie structure of the PHT from dictionnary.

        @param trie_dict: Dictionnary of index entries (prefix -> entry).
        @type  trie_dict: dict
        """
        prefixes = list(trie_dict.keys())
        if len(prefixes) == 0:
            return

        edges = list([])
        for prefix in prefixes:
            for i in range(-1, len(prefix)-1):
                u = prefix[:i+1]
                x = ("." if i == -1 else u, u+"0")
                y = ("." if i == -1 else u, u+"1")
                if x not in edges:
                    edges.append(x)
                if y not in edges:
                    edges.append(y)

        # TODO: use a binary tree position layout...
        #   UPDATE : In a better way [change lib]
        G = nx.Graph(sorted(edges, key=lambda x: len(x[0])))
        plt.title("PHT: Tree")
        pos=graphviz_layout(G,prog='dot')
        nx.draw(G, pos, with_labels=True, node_color='white')
        plt.show()
开发者ID:savoirfairelinux,项目名称:opendht,代码行数:29,代码来源:tests.py


示例6: visualize

def visualize(graphs, viz_path, args_viz_format):
  import matplotlib
  from networkx.drawing.nx_agraph import graphviz_layout
  meta_graph = networkx.Graph()
  for graph in graphs:
    add_graph(meta_graph, graph)
  pos = graphviz_layout(meta_graph)
  networkx.draw(meta_graph, pos)
  if viz_path:
    ext = os.path.splitext(viz_path)[1]
    if ext == '.dot':
      viz_format = 'graphviz'
    elif ext == '.png':
      viz_format = 'png'
  else:
    viz_format = args_viz_format
  if viz_format == 'graphviz':
    from networkx.drawing.nx_pydot import write_dot
    assert viz_path is not None, 'Must provide a filename to --visualize if using --viz-format "graphviz".'
    base_path = os.path.splitext(viz_path)
    write_dot(meta_graph, base_path+'.dot')
    run_command('dot', '-T', 'png', '-o', base_path+'.png', base_path+'.dot')
    logging.info('Wrote image of graph to '+base_path+'.dot')
  elif viz_format == 'png':
    if viz_path is None:
      matplotlib.pyplot.show()
    else:
      matplotlib.pyplot.savefig(viz_path)
开发者ID:galaxyproject,项目名称:dunovo,代码行数:28,代码来源:correct.py


示例7: get_tree_layout

    def get_tree_layout(self, connected_component):
        layout = None
        tree = self.get_underlying_tree(connected_component)
        try:
            # Nice circular layout if you have graphviz
            from networkx.drawing.nx_agraph import graphviz_layout
            layout = graphviz_layout(tree, prog='twopi', root=str(tree.root))

            # Scale to fit grid, since twopi seems to ignore the size option
            min_x = min(pos[0] for pos in layout.values())
            max_x = max(pos[0] for pos in layout.values())
            min_y = min(pos[1] for pos in layout.values())
            max_y = max(pos[1] for pos in layout.values())

            center_x = min_x + (max_x - min_x) / 2
            center_y = min_y + (max_y - min_y) / 2
            # Re-center, scale and shift to fit the desired bounding box
            try:
                x_scale = (0.5 - self.layout_margin - 0.005) / (center_x - min_x)
            except ZeroDivisionError:
                x_scale = 1
            try:
                y_scale = (0.5 - self.layout_margin - 0.005) / (center_y - min_y)
            except ZeroDivisionError:
                y_scale = 1
            for vert, pos in layout.iteritems():
                layout[vert] = ((pos[0] - center_x) * x_scale + 0.5,
                        (pos[1] - center_y) * y_scale + 0.5)

        except ImportError:
            # Spring layout if you do not have grahpviz
            layout = nx.spring_layout(tree, scale=1-2*self.layout_margin-0.01,
                    center=(0.5, 0.5))
        return layout
开发者ID:Yang-Ho,项目名称:BEAVr,代码行数:34,代码来源:visualizerbackend.py


示例8: plot_graph

def plot_graph(graph):
    from networkx.drawing.nx_agraph import graphviz_layout
    pos = graphviz_layout(graph, prog='dot')

    for h in nx.connected_component_subgraphs(graph.to_undirected()):
        nx.draw(h, pos, with_labels=True)

    plt.show()
开发者ID:fepz,项目名称:curso-pg-ferro-strd-2016,代码行数:8,代码来源:graphutils.py


示例9: plot_nx

def plot_nx(bn,**kwargs):
	"""
	Draw BayesNet object from networkx engine
	"""
	g = nx.DiGraph(bn.E)
	pos = graphviz_layout(g,'dot')
	#node_size=600,node_color='w',with_labels=False
	nx.draw_networkx(g,pos=pos, **kwargs)
	plt.axis('off')
	plt.show()
开发者ID:ncullen93,项目名称:neuroBN,代码行数:10,代码来源:plot.py


示例10: graph_traditional_object_file

    def graph_traditional_object_file(self, nodes_to_ignore):
        if len(self.object_list) == 0:
            return

        G = nx.DiGraph()

        node_rooms_list = []
        node_labels = {}

        for o in self.object_list:
            if o.parent_id in nodes_to_ignore:
                nodes_to_ignore.append(o.object_id)
                continue
            elif o.object_id in nodes_to_ignore:
                continue

            G.add_node(o.object_key())

            if ROOM_ATTRIBUTE_KEY in (int(attribute) for attribute in o.attributes):
                node_rooms_list.append(o.object_key())
                node_labels[o.object_key()] = o.description

        for o in self.object_list:
            if o.object_key() not in G.nodes():
                continue

            if o.parent_id != 0 and o.object_id not in nodes_to_ignore:
                parent_key = self.object_list[o.parent_id - 1].object_key()

                node_key_to_get = node_labels.get(parent_key, "")
                if node_key_to_get is not "":
                    node_labels[parent_key] = node_key_to_get + '\n\t' + o.description
                else:
                    node_labels[parent_key] = o.description

            for direction, node in o.directions.items():
                if node < len(self.object_list):
                    G.add_edge(self.object_list[node-1].object_key(), o.object_key(), direction=direction)

        pos = graphviz_layout(G, prog='dot')

        edge_labels = dict([((u, v,), d['direction'])
                            for u, v, d in G.edges(data=True)])

        nx.draw_networkx_nodes(G, pos, nodelist=node_rooms_list,
                               node_color="b", node_size=5000, alpha=0.8)

        nx.draw_networkx_edges(G, pos)

        nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=8)

        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8, alpha=0.5)

        plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
        plt.show()
开发者ID:attilathedud,项目名称:ZTree,代码行数:55,代码来源:ZObjects.py


示例11: one_layout

 def one_layout(self, func, kwargs):
     """Calculates one arbitrary layout"""
     if 'fixed' in kwargs.keys():
         if not kwargs['fixed'] is None:
             kwargs['pos'] = nx.random_layout(self.G, dim=kwargs['dim'])
     if func == 'dh_spring_layout':
         return self.dh_spring_layout(self.G, **kwargs)
     elif func == 'draw_graphviz':
         return graphviz_layout(self.G, **kwargs)
     else:
         return getattr(nx, func)(self.G, **kwargs)
开发者ID:HCsoft-RD,项目名称:shaolin,代码行数:11,代码来源:graph.py


示例12: desenhaGrafo

def desenhaGrafo(G,pngfilename): # desenha o grafo e salva numa imagem png
    edge_labels=dict([((u,v,),d['weight']) # gera os labels das arestas
                    for u,v,d in G.edges(data=True)])
    colors = [G[u][v]['color'] for u,v in G.edges()]
    pos = graphviz_layout(G,prog='neato') # obtem a posicao dos nos (para desenhalo) # TODO: desativar isso?
    nx.draw_networkx_edges(G,pos, edge_color=colors) # desenha as arestas
    nx.draw_networkx_labels(G,pos) # desenha os labels das arestas
    nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) # desenha os labels dos nos
    nx.draw_networkx_nodes(G,pos,node_color='w') # desenha os nos
    plt.axis('off') # desativa os eixos
    plt.savefig(pngfilename)
    plt.close("all")
开发者ID:caioau,项目名称:personal,代码行数:12,代码来源:grafo-1c.py


示例13: plot

    def plot(self, savepath=None):
        """
        Draw this individual.
        """

        from networkx.drawing.nx_agraph import graphviz_layout

        fig = plt.figure(figsize=(40, 30))

        tree = self.tree  # type: nx.DiGraph
        pos = graphviz_layout(tree, root=0, prog='dot')

        node_list = tree.nodes(data=True)
        edge_list = tree.edges(data=True)

        node_labels = {
            x[0]: '%s: %s\n%s' % (str(x[1]['node_id']), str(x[1]['label']), '%s/%s' % (
                str(x[1]['inst_correct']), str(x[1]['inst_total'])) if x[1]['terminal'] else '')
            for x in node_list
        }
        node_colors = [x[1]['color'] for x in node_list]
        edge_labels = {(x1, x2): d['threshold'] for x1, x2, d in edge_list}

        nx.draw_networkx_nodes(tree, pos, node_size=1000, node_color=node_colors)  # nodes
        nx.draw_networkx_edges(tree, pos, edgelist=edge_list, style='dashed')  # edges
        nx.draw_networkx_labels(tree, pos, node_labels, font_size=16)  # node labels
        nx.draw_networkx_edge_labels(tree, pos, edge_labels=edge_labels, font_size=16)

        plt.text(
            0.2,
            0.9,
            '\n'.join([
                'individual id: %03.d' % self.ind_id,
                'height: %d' % self.height,
                'n_nodes: %d' % self.n_nodes,
                'train accuracy: %0.4f' % self.train_acc_score,
                'val accuracy: %0.4f' % self.val_acc_score,
                'test accuracy: %0.4f' % self.test_acc_score if self.test_acc_score is not None else '',
                'iteration: %d' % self.iteration if self.iteration is not None else ''

            ]),
            fontsize=15,
            horizontalalignment='right',
            verticalalignment='top',
            transform=fig.transFigure
        )

        plt.axis('off')

        if savepath is not None:
            plt.savefig(savepath, bbox_inches='tight', format='pdf')
            plt.close()
开发者ID:henryzord,项目名称:forrestTemp,代码行数:52,代码来源:__init__.py


示例14: draw_circular_graph

    def draw_circular_graph(self):
        """ Draws a circular graph from the previously computed graph
        :return: None
        """

        pos = graphviz_layout(self.graph, prog="twopi", args="")
        plt.figure(figsize=(8, 8))
        nx.draw(self.graph, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
        nx.draw_networkx_labels(self.graph, pos, self.labels, font_size=6)

        plt.axis("equal")
        plt.savefig("circular_tree.png")
        plt.show()
开发者ID:doogyb,项目名称:PlotBot,代码行数:13,代码来源:plot_network.py


示例15: draw_lanl_graph

    def draw_lanl_graph(self):
        """ Draws a lanl graph from the previously computed graph.
        :return: None
        """
        lanl_graph = sorted(nx.connected_component_subgraphs(self.graph), key=len, reverse=True)[0]

        plt.figure(figsize=(8, 8))
        # use graphviz to find radial layout
        pos = graphviz_layout(self.graph, prog="twopi", root=self.root)
        # draw nodes, coloring by rtt ping time
        nx.draw(self.graph, pos, with_labels=False, alpha=0.5, node_size=15)
        # adjust the plot limits
        xmax = 1.02 * max(xx for xx, yy in pos.values())
        ymax = 1.02 * max(yy for xx, yy in pos.values())
        plt.xlim(0, xmax)
        plt.ylim(0, ymax)
        # plt.show()
        plt.savefig("lanl_routes.png")
开发者ID:doogyb,项目名称:PlotBot,代码行数:18,代码来源:plot_network.py


示例16: handle_file

def handle_file(path):
    i = open(path, "r")
    lines = i.readlines()
    g = nx.parse_edgelist(lines[1:], nodetype=int, data=(('weight', float),))
    x1, x2, vol = lines[0].rstrip("\n").split(" ")
    i.close()
    x1 = int(x1)
    x2 = int(x2)
    vol = float(vol)
    g.add_node(0)
    g.add_weighted_edges_from([(0, x1, 0), (0, x2, 0)])
    calculate(g, vol)

    # create directed graph for presentation
    result = nx.DiGraph()
    result.add_nodes_from(nx.nodes(g))
    for x1, x2 in nx.edges(g):
        sx1, sx2 = tuple(sorted((x1, x2)))
        if g[x1][x2]['current'] > 0:
            result.add_edge(sx1, sx2, current=g[x1][x2]['current'])
        else:
            result.add_edge(sx2, sx1, current=-g[x1][x2]['current'])

    pos = graphviz_layout(result, prog='sfdp',)
    nx.draw_networkx_nodes(result, pos=pos, node_size=250, node_color='white')

    edges = nx.edges(result)
    currents_dict = nx.get_edge_attributes(result, 'current')
    currents_list = tuple(currents_dict[e] for e in edges)
    widths_list = tuple(0.3 + 4 * x/max(currents_list) for x in currents_list)
    colors = ("green", "yellow", "red")
    colors_list = [colors[(math.floor(len(colors)*x/max(widths_list) - 0.1))]
                   for x in widths_list]
    for key, val in currents_dict.items():
        currents_dict[key] = "{:.1f}".format(val)
    nx.draw_networkx_edges(result, pos=pos, edgelist=edges, width=widths_list,
                           edge_color=colors_list)
    bbox_props = dict(boxstyle="square,pad=0", fc="none", ec='none', lw=2)
    nx.draw_networkx_edge_labels(result, pos=pos, edge_labels=currents_dict,
                                 font_size=8, bbox=bbox_props)
    nx.draw_networkx_labels(result, pos=pos, font_size=8)
    plt.get_current_fig_manager().full_screen_toggle()
    plt.show()
开发者ID:michalborzecki,项目名称:mownit2,代码行数:43,代码来源:main.py


示例17: dbg_draw

    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)
开发者ID:Manouchehri,项目名称:angr,代码行数:19,代码来源:function.py


示例18: plot_network_with_results

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')
开发者ID:power-system-simulation-toolbox,项目名称:psst,代码行数:42,代码来源:plot.py


示例19: main

def main(fname):
    
    try:
        cells, spacing, zones, J, _ = parse_qca_file(fname, one_zone=True)
    except:
        print('Failed to process QCA file: {0}'.format(fname))
        return None
    
    # convert J to specified adjacency
    J = 1.*(convert_adjacency(cells, spacing, J, adj=ADJ) != 0)
    
    G = nx.Graph(J)
    for k in G:
        G.node[k]['w'] = 1./len(G[k])**2
        
    pos = graphviz_layout(G)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()
    
    chlebikova(G)
开发者ID:retallickj,项目名称:qca-embed,代码行数:20,代码来源:test_bcp.py


示例20: show_tree

def show_tree(J, tree):
    ''' '''
    
    G = nx.Graph(J)
    pos = graphviz_layout(G)
    
    if not tree['children']:
        return
        
    # color nodes
    colors = ['r', 'b', 'g', 'k', 'm', 'c', 'o', 'y']
    for i, child in enumerate(tree['children']):
        inds = child['inds']
        print(inds)
        color = colors[i%len(colors)]
        nx.draw_networkx_nodes(G, pos, nodelist=inds, node_color=color)
    nx.draw_networkx_edges(G, pos)
    plt.show()

    for child in tree['children']:
        inds = child['inds']
        show_tree(J[inds, :][:, inds], child)
开发者ID:retallickj,项目名称:qca-embed,代码行数:22,代码来源:rp_coef.py



注:本文中的networkx.drawing.nx_agraph.graphviz_layout函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python classic.complete_graph函数代码示例发布时间:2022-05-27
下一篇:
Python convert._prep_create_using函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap