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

Python networkx.draw_graphviz函数代码示例

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

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



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

示例1: render_community_graph

    def render_community_graph(self, show_single_nodes=True):
        added_nodes = set()
        graph = nx.Graph()
        for edge, _ in self.adjacency_matrix.iteritems():
            player_one = self.__players[edge.player_one]
            player_two = self.__players[edge.player_two]
            added = False
            if show_single_nodes:
                graph.add_node(edge.player_one)
                graph.add_node(edge.player_two)
                added = True
            if player_one.community == player_two.community:
                graph.add_edge(edge.player_one, edge.player_two)
                added = True
            if added:
                added_nodes.add(edge.player_one)
                added_nodes.add(edge.player_two)

        for node in self.nodes:
            if node.fide_id in added_nodes:
                graph.node[node.fide_id]['elo_rank'] = math.floor(node.elo/100) * 100

        min_val = self.__min_elo
        max_val = 2900
        elo_levels = range(min_val, max_val, 100)
        color_levels = np.linspace(1, 0, num=len(elo_levels), endpoint=True)
        color_value_map = {elo: color for (elo, color) in zip(elo_levels, color_levels)}
        color_values = [color_value_map.get(graph.node[n]['elo_rank'], 0.0) for n in graph.nodes()]

        nx.draw_graphviz(graph, cmap=pylab.get_cmap('jet'), node_color=color_values,
                         node_size=100)
开发者ID:RGaonkar,项目名称:from-data-with-love,代码行数:31,代码来源:graph.py


示例2: minimalColoring

def minimalColoring (probMatrix, contigs, cutoff = 0.01):
	# create a graph based on the probMatrix
	probG = nx.Graph()
	for i in range (len(contigs)):
		contigi = contigs[i]
		if contigi in excluded_utgs:
			print "yo"
			continue
		probG.add_node(contigi)
		for j in range (i+1, len(contigs)):
			contigj = contigs[j]
			if contigi in excluded_utgs:
				print "yo"
				continue
			if np.isnan(probMatrix[i][j]):
				continue
			if probMatrix[i][j] > cutoff:
				probG.add_edge(contigi, contigj)
	nx.draw_graphviz(probG)
	plt.savefig(out_tag + "_color_groups.png")
	plt.clf()	
	#print probG.nodes()
	#print probG.edges()
	#print nx.find_cliques(probG)
	components = list(nx.connected_components(probG))
	#components = list(nx.find_cliques(probG))
	return components
开发者ID:webste01,项目名称:EMMC-Assembler,代码行数:27,代码来源:graph_coloring_cut_ipds_ali.py


示例3: salva_grafoNX_imagem

def salva_grafoNX_imagem(G):
    """
    Salva grafos em formato png e dot
    """
    nx.draw_graphviz(G)
    nx.write_dot(G, 'relatorios/grafo_lei_vs_lei.dot')
    P.savefig('relatorios/grafo_lei_vs_lei.png')
开发者ID:Ralpbezerra,项目名称:Supremo,代码行数:7,代码来源:grafos.py


示例4: main

def main():

    if len(sys.argv) < 2:
        sys.exit('Usage: %s $json_file' % sys.argv[0])

    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: %s was not found!' % sys.argv[1])

    if len(sys.argv) == 2:
        G = merge_same_node(parse_saaf_json(sys.argv[1]))
        nx.draw_graphviz(G, prog = 'dot')
        plt.axis('off')
        plt.savefig("merged_by_networkx.png")
        json.dump(
            json_graph.node_link_data(G),
            open('ford3js.json', 'w'),
            sort_keys = True,
            indent = 4
        )
    if len(sys.argv) == 3:
        G1 = merge_same_node(parse_saaf_json(sys.argv[1]))
        G2 = merge_same_node(parse_saaf_json(sys.argv[2]))
        GM = isomorphism.DiGraphMatcher(G2, G1, node_match = op_match)
        #GM = isomorphism.DiGraphMatcher(G2, G1)
        print GM.is_isomorphic()
        print GM.subgraph_is_isomorphic()
        print GM.mapping
开发者ID:M157q,项目名称:Android-Repackaged-App-Detection-System,代码行数:27,代码来源:graph_networkx.py


示例5: render_graph

    def render_graph(self, max_edges=None, min_games=1):
        added_nodes = set()
        graph = nx.Graph()
        for i, (edge, num) in enumerate(self.adjacency_matrix.iteritems()):
            if max_edges and i > max_edges:
                break
            if num < min_games:
                continue
            graph.add_edge(edge.player_one, edge.player_two)
            added_nodes.add(edge.player_one)
            added_nodes.add(edge.player_two)

        for node in self.nodes:
            if node.fide_id in added_nodes:
                graph.node[node.fide_id]['elo_rank'] = int(math.floor(node.elo/100) * 100)

        min_val = self.__min_elo
        max_val = 2900
        elo_levels = range(min_val, max_val, 100)
        color_levels = np.linspace(1, 0, num=len(elo_levels), endpoint=True)
        color_value_map = {elo: color for (elo, color) in zip(elo_levels, color_levels)}
        color_values = [color_value_map.get(graph.node[n]['elo_rank'], 0.0) for n in graph.nodes()]

        nx.draw_graphviz(graph, cmap=pylab.get_cmap('jet'), node_color=color_values,
                         node_size=100)
开发者ID:RGaonkar,项目名称:from-data-with-love,代码行数:25,代码来源:graph.py


示例6: displayGraph

 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections')
         return
     weights = np.array([g.edge[e[0]][e[1]]['weight'] for e in g.edges()])
     pos = nx.graphviz_layout(g, prog='twopi')
     xmin, ymin, xmax, ymax = 1e9, 1e9, -1e9, -1e9
     for p in list(pos.values()):
         if xmin > p[0]:
             xmin = p[0]
         if xmax < p[0]:
             xmax = p[0]
         if ymin > p[1]:
             ymin = p[1]
         if ymax < p[1]:
             ymax = p[1]        
     edge_widths = 10.0 * weights / max(weights)
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
开发者ID:BhallaLab,项目名称:moose-examples,代码行数:26,代码来源:gui.py


示例7: draw_all

def draw_all(filename='out.png'):
  """
  draw every graph connected and everything yeah
  """
  def _make_abbreviation(string):
    s = string.split(" ")
    return ''.join([word[0] for word in s])
  import matplotlib.pyplot as plt
  plt.clf()
  this = sys.modules[__name__]
  relationals = [getattr(this, i) for i in this.__dict__ if isinstance(getattr(this,i), Relational)]
  biggraph = nx.DiGraph()
  for r in relationals:
    for n in r._nk.nodes():
      biggraph.add_edges_from(n._nk.edges())
  for n in biggraph.nodes():
    if n.external_parents:
      for p in n.external_parents:
        biggraph.add_edges_from(p._nk.edges())
    if n.external_childs:
      for c in n.external_childs:
        biggraph.add_edges_from(c._nk.edges())
  for n in biggraph.nodes():
    if "." not in n.name:
      n.name = n.name+"."+_make_abbreviation(n.container.name)
  nx.draw_graphviz(biggraph,prog='neato',width=1,node_size=300,font_size=4,overlap='scalexy')
  plt.savefig(filename)
开发者ID:SoftwareDefinedBuildings,项目名称:BAS,代码行数:27,代码来源:sdh.py


示例8: map_flows

def map_flows(catalog):
    import analysis as trans
    fm = trans.FlowMapper()

    read_exceptions = {}
    for i,fn in enumerate(os.listdir('.\\repository_data\\')):
        print i, fn
        try:
            sys = catalog.read(''.join(['.\\repository_data\\',fn]))
        except Exception as e:
            read_exceptions[fn] = e
            print '\t',e.message
        fm.add_system(sys)
        if i > 5:
            break

    graph = fm.transformation_graph()
    fm.stats()
    nx.draw_graphviz(graph,prog='dot',root='energy')
    print nx.to_numpy_matrix(graph) > 0
#    pdg = nx.to_pydot(graph)
#    pdg.write_png('transform.png')
#    nx.graphviz_layout(graph,prog='neato')
#    nx.draw_graphviz(graph)
    plt.show()
开发者ID:btciavol,项目名称:TechEngine,代码行数:25,代码来源:main.py


示例9: plot_co_x

def plot_co_x(cox, start, end, size = (20,20), title = '', weighted=False, weight_threshold=10):

        """ Plotting function for keyword graphs

        Parameters
        --------------------
        cox: the coword networkx graph; assumes that nodes have attribute 'topic'
        start: start year
        end: end year
        """

        plt.figure(figsize=size)
        plt.title(title +' %s - %s'%(start,end), fontsize=18)
        if weighted:
            elarge=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] >weight_threshold]
            esmall=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] <=weight_threshold]
            pos=nx.graphviz_layout(cox) # positions for all nodes
            nx.draw_networkx_nodes(cox,pos,
                node_color= [s*4500 for s in nx.eigenvector_centrality(cox).values()],
                node_size = [s*6+20  for s in nx.degree(cox).values()],
                alpha=0.7)
            # edges
            nx.draw_networkx_edges(cox,pos,edgelist=elarge,
                                width=1, alpha=0.5, edge_color='black') #, edge_cmap=plt.cm.Blues
            nx.draw_networkx_edges(cox,pos,edgelist=esmall,
                                width=0.3,alpha=0.5,edge_color='yellow',style='dotted')
            # labels
            nx.draw_networkx_labels(cox,pos,font_size=10,font_family='sans-serif')
            plt.axis('off')
        else:
            nx.draw_graphviz(cox, with_labels=True,
                         alpha = 0.8, width=0.1,
                         fontsize=9,
                         node_color = [s*4 for s in nx.eigenvector_centrality(cox).values()],
                         node_size = [s*6+20 for s in nx.degree(cox).values()])
开发者ID:datapractice,项目名称:machinelearning,代码行数:35,代码来源:net_lit_anal.py


示例10: plot_graph

def plot_graph(graph=None, path=None, dist=None, best=None, best_dist=None,
			   save=False, name=None, title=None):
	"""
	Plot a TSP graph.

	Parameters
	----------
	graph: An XML TSP graph. If None, use the default graph from parse_xml_graph.
	path: An ordered list of node indices. If given, plot the path. Otherwise, plot
		the underlying graph.
	dist: Distances of the paths in path.
	best: Empirical best path.
	best_dist: Empirical best path distance.
	save: If True, saves the graph as name.png. Otherwise, draws the graph.
	name: Graph is saved as name.png
	title: Caption of the graph.
	"""
	# Check input parameters 
	if save:
		assert (name is not None), 'If saving graph, must provide name'

	# Initialize graph
	if graph is not None:
		g = parse_xml_graph(graph)
	else:
		g = parse_xml_graph()
	G = nx.from_numpy_matrix(g)

	# Plot path, if applicable
	edges = list()
	edge_colors = list()
	if path is not None:
		edges.extend([(path[i], path[i+1]) for i in range(len(path)-1)])
		edges.append((path[-1], path[0]))
		edge_colors.extend(['r' for i in range(len(path))])
	if best is not None:
		edges.extend([(best[i], best[i+1]) for i in range(len(best)-1)])
		edges.append((best[-1], best[0]))
		edge_colors.extend(['b' for i in range(len(best))])
	if path is None and best is None:
		edges = G.edges()

	plt.clf()
	fig = plt.figure(figsize=(14, 5.5))
	ax1 = fig.add_subplot(121)
	ax2 = fig.add_subplot(122)
	nx.draw_graphviz(G, edgelist=edges, edge_color=edge_colors, with_labels=None,
		node_color='k', node_size=100, ax=ax1)
	ax1.set_title(title)
	ax2.plot(np.arange(1, len(dist)+1), dist, color='r', alpha=0.9, label='Best found path')
	ax2.hlines(best_dist, 0, len(dist)+1, color='b', label='Best path')
	ax2.set_xlim(1, max(len(dist), 2));
	ax2.legend()

	if not save:
		plt.show()
	else:
		plt.savefig('temp/{}.png'.format(name))
	fig.clf()
开发者ID:dekatzenel,项目名称:cs205-final-project,代码行数:59,代码来源:plotting.py


示例11: s_draw

def s_draw(listdata):
    '''Draw the weighted graph associated with the Seifert data 'listdata'.'''
    startree = make_graph(listdata)
    labels = dict((n, '%s,%s' %(n,a['weight'])) for n,a in 
                  startree.nodes(data=True))
    nx.draw_graphviz(startree, labels=labels, node_size=700, width=3, 
                     alpha=0.7)    
    plt.show()    
开发者ID:panaviatornado,项目名称:hfhom,代码行数:8,代码来源:seifert.py


示例12: graph_draw

def graph_draw(graph):
    nx.draw_graphviz(
        graph,
        node_size=[16 * graph.degree(n) for n in graph],
        node_color=[graph.depth[n] for n in graph],
        with_labels=False,
    )
    matplotlib.pyplot.show()
开发者ID:rhanak,项目名称:nlplearning,代码行数:8,代码来源:basics.py


示例13: update_graph

 def update_graph(self):
     '''Redraw graph in matplotlib.pyplot.'''
     plt.clf() # erase figure
     labels = dict((n, '%s,%s' %(n,a['weight'])) \
                   for n,a in self.graph.nodes(data=True))
     nx.draw_graphviz(self.graph, labels=labels, node_size=700, width=3, 
                      alpha=0.7)
     plt.show()
开发者ID:panaviatornado,项目名称:hfhom,代码行数:8,代码来源:weighted_graph.py


示例14: debug_graph

def debug_graph( graph, message="" ):
    import matplotlib.pyplot as plt
    print message

    pos = nx.layout.fruchterman_reingold_layout( graph )
    nx.draw( graph, pos )
    nx.draw_graphviz( graph )
    plt.show()
开发者ID:ilyakh,项目名称:unifi-webfaction,代码行数:8,代码来源:pool.py


示例15: test_lobster

 def test_lobster(self):
     import networkx as nx
     import matplotlib.pyplot as plt
     #g = nx.random_lobster(15, 0.8, 0.1)
     g = nx.barbell_graph(7, 5)
     #g = nx.erdos_renyi_graph(15, 0.2)
     nx.draw_graphviz(g)
     plt.savefig("/tmp/lobster.png")
     print distancematrix.matrix_calls(g.edges(), 7)
开发者ID:axiak,项目名称:pydistancematrix,代码行数:9,代码来源:simpletest.py


示例16: printGraph

def printGraph(G, gname):
  h = networkx.DiGraph()
  h.add_edges_from( G.edges() )
  networkx.draw_graphviz(h)
  fname = os.path.sep.join([config.Config.imgCacheDir, 'graph_%s.png'%(gname) ] )
  plt.savefig(fname)
  plt.clf()
  fname = os.path.sep.join([config.Config.cacheDir, 'graph_%s.gexf'%(gname) ] )
  networkx.readwrite.gexf.write_gexf( h, fname)
开发者ID:f9tech,项目名称:twiler-site-packages,代码行数:9,代码来源:graph.py


示例17: draw_neighbor

def draw_neighbor(G,compound):
	tmp = nx.all_neighbors(G,compound)
	Gpart = nx.Graph()
	for x in tmp:
		Gpart.add_edge(x,compound,color=G.edge[x][compound]['color'])
	nx.draw(Gpart)
        plt.savefig("path_test.png")
        nx.draw_graphviz(Gpart)
        nx.write_dot(Gpart,'file_test.dot')
开发者ID:keiohigh2nd,项目名称:metabolic_pathway,代码行数:9,代码来源:enzyme_method.py


示例18: PlotNetwork

def PlotNetwork(G,OutputFile="Graph.dot"):
    """Plot a graph to screen and also save output."""

    try:
        networkx.draw_graphviz(G)
    except:
        logger.error("could not plot graph to screen.  Check X / Matplotlib settings.")
        
    networkx.write_dot(G, OutputFile)
    logger.info("Wrote: %s", OutputFile)
开发者ID:chrismichel,项目名称:msmbuilder,代码行数:10,代码来源:plot_graph.py


示例19: drawGraph

 def drawGraph(self):
     lbls = {}
     for node in self._graph.nodes():
         lbls[node] = self._graph.node[node]["nName"]
     nx.draw_graphviz(self._graph, prog = "twopi",       \
                      with_labels = True, labels = lbls)
     path = "{0}.png".format(len(self._hints))
     plt.savefig(path)
     plt.show()      
     return path
开发者ID:imclab,项目名称:yatot,代码行数:10,代码来源:yatot.py


示例20: transferConditions

def transferConditions(dag, l, maxCount=2):
	"""
	Return a color (for quality of transfer) and a list
	of SynonymsList"""
	count = 0
	
	lSet = set()
	terms_to_remove = set()
	
	for term in l:
		lSet.add(getSynList(dag, term))
	
	# Colored graph
	for e in lSet:
		dag.node[e]["color"] = "blue"
	
	for synList in lSet:
		if synList is None:
			return "RED", "Error"
		
	for start in lSet:
		for a, b in nx.bfs_edges(dag, start, reverse=True):
			if b in lSet:
				terms_to_remove.add(b)
	
	for e in terms_to_remove:
		if e in lSet:
			lSet.remove(e)
	
	if len(lSet) == 1:
		finalSynList = list(lSet)[0]
		
		# Draw
		dag.node[finalSynList]["fontcolor"] = "green"
		nx.draw_graphviz(dag)
		nx.write_dot(dag, "output2.dot")
		os.popen("dot -Tpng output2.dot > output2.png")
		
		return "GREEN", list(lSet)
	
	else:
		fca = firstCommonAncestors(dag, lSet)
		
		for e in fca:
			dag.node[e]["fontcolor"] = "orange"
	
		# Draw
		nx.draw_graphviz(dag)
		nx.write_dot(dag, "output2.dot")
		os.popen("dot -Tpng output2.dot > output2.png")
		
		if count <= maxCount:
			return "ORANGE", fca
		else:
			return "RED", "Error"
开发者ID:tblabruyere,项目名称:ter-ips-bacteriophages,代码行数:55,代码来源:transfer.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python networkx.draw_networkx函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.draw_circular函数代码示例发布时间: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