本文整理汇总了Python中networkx.draw_graphviz函数的典型用法代码示例。如果您正苦于以下问题:Python draw_graphviz函数的具体用法?Python draw_graphviz怎么用?Python draw_graphviz使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了draw_graphviz函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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')
示例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
示例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)
示例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, )
示例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)
示例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()
示例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()])
示例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()
示例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()
示例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()
示例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()
示例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()
示例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)