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