本文整理匯總了Python中networkx.draw_networkx_labels方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.draw_networkx_labels方法的具體用法?Python networkx.draw_networkx_labels怎麽用?Python networkx.draw_networkx_labels使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.draw_networkx_labels方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: plot_alerts
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def plot_alerts(_g, _bank_accts, _output_png):
bank_ids = _bank_accts.keys()
cmap = plt.get_cmap("tab10")
pos = nx.nx_agraph.graphviz_layout(_g)
plt.figure(figsize=(12.0, 8.0))
plt.axis('off')
for i, bank_id in enumerate(bank_ids):
color = cmap(i)
members = _bank_accts[bank_id]
nx.draw_networkx_nodes(_g, pos, members, node_size=300, node_color=color, label=bank_id)
nx.draw_networkx_labels(_g, pos, {n: n for n in members}, font_size=10)
edge_labels = nx.get_edge_attributes(_g, "label")
nx.draw_networkx_edges(_g, pos)
nx.draw_networkx_edge_labels(_g, pos, edge_labels, font_size=6)
plt.legend(numpoints=1)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.savefig(_output_png, dpi=120)
示例2: graph_att_head
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def graph_att_head(M, N, weight, ax, title):
"credit: Jinjing Zhou"
in_nodes=len(M)
out_nodes=len(N)
g = nx.bipartite.generators.complete_bipartite_graph(in_nodes,out_nodes)
X, Y = bipartite.sets(g)
height_in = 10
height_out = height_in
height_in_y = np.linspace(0, height_in, in_nodes)
height_out_y = np.linspace((height_in - height_out) / 2, height_out, out_nodes)
pos = dict()
pos.update((n, (1, i)) for i, n in zip(height_in_y, X)) # put nodes from X at x=1
pos.update((n, (3, i)) for i, n in zip(height_out_y, Y)) # put nodes from Y at x=2
ax.axis('off')
ax.set_xlim(-1,4)
ax.set_title(title)
nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes), node_color='r', node_size=50, ax=ax)
nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes, in_nodes + out_nodes), node_color='b', node_size=50, ax=ax)
for edge in g.edges():
nx.draw_networkx_edges(g, pos, edgelist=[edge], width=weight[edge[0], edge[1] - in_nodes] * 1.5, ax=ax)
nx.draw_networkx_labels(g, pos, {i:label + ' ' for i,label in enumerate(M)},horizontalalignment='right', font_size=8, ax=ax)
nx.draw_networkx_labels(g, pos, {i+in_nodes:' ' + label for i,label in enumerate(N)},horizontalalignment='left', font_size=8, ax=ax)
示例3: draw_wstate_tree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
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()
示例4: draw_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
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
示例5: build_word_ego_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
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()
示例6: plot_subgraph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def plot_subgraph(self, region_start, region_stop, seq_name, neighbours=0):
"""
Return a plot of a sub-graph from a defined region with positions relative to some of the sequences.
:param region_start: Start position (bp)
:param region_stop: Stop position (bp)
:param seq_name: Sequence ID that the bp positions are relative to.
:param neighbours: Number of neighbours to be included. Currently testing, only 1 level available.
:return: Plots a netowrkx + matplotlib figure of the region subgraph.
"""
sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours)
pos = nx.spring_layout(sub_graph)
nx.draw_networkx_nodes(sub_graph, pos, cmap=plt.get_cmap('jet'), node_size=300)
nx.draw_networkx_labels(sub_graph, pos)
nx.draw_networkx_edges(sub_graph, pos, arrows=True)
plt.show()
示例7: replay
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def replay(self, graph):
"""Draw the given graph."""
fig, ax = plt.subplots(frameon=False) # pylint:disable=invalid-name
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
node_pos = graph.node_coordinates
def _update(num):
ax.clear()
fig.canvas.set_window_title(f'{graph.name} - Iteration ({num+1}/{len(self.__edge_colors)})')
nodes_artist = nx.draw_networkx_nodes(graph.networkx_graph, pos=node_pos, ax=ax, node_color=self.__node_color)
labels_artist = nx.draw_networkx_labels(graph.networkx_graph, pos=node_pos, ax=ax)
edges_artist = nx.draw_networkx_edges(graph.networkx_graph, pos=node_pos, width=self.__edge_widths[num], edge_color=self.__edge_colors[num], ax=ax)
return nodes_artist, labels_artist, edges_artist
_ = animation.FuncAnimation(fig, _update, frames=len(self.__edge_colors), interval=self.__interval, repeat=self.__continuous)
plt.show()
示例8: draw_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def draw_graph(self):
nx.draw_shell(self.G, with_labels=True, font_weight='bold')
# pos = graphviz_layout(self.G)
# plt.axis('off')
# nx.draw_networkx_nodes(self.G,pos,node_color='g',alpha = 0.8)
# nx.draw_networkx_edges(self.G,pos,edge_color='b',alpha = 0.6)
# nx.draw_networkx_edge_labels(self.G,pos,edge_labels = \
# nx.get_edge_attributes(self.G,'weight'))
# nx.draw_networkx_labels(self.G,pos) # node lables
plt.savefig('graph.png')
示例9: malt_demo
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
示例10: plot
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def plot(cg):
"""
Plot the call graph using matplotlib
For larger graphs, this should not be used, as it is very slow
and probably you can not see anything on it.
:param cg: A networkx call graph to plot
"""
from androguard.core.analysis.analysis import ExternalMethod
import matplotlib.pyplot as plt
import networkx as nx
pos = nx.spring_layout(cg)
internal = []
external = []
for n in cg.node:
if isinstance(n, ExternalMethod):
external.append(n)
else:
internal.append(n)
nx.draw_networkx_nodes(cg, pos=pos, node_color='r', nodelist=internal)
nx.draw_networkx_nodes(cg, pos=pos, node_color='b', nodelist=external)
nx.draw_networkx_edges(cg, pos, arrow=True)
nx.draw_networkx_labels(cg, pos=pos,
labels={x: "{} {}".format(x.get_class_name(),
x.get_name())
for x in cg.edge})
plt.draw()
plt.show()
示例11: _draw_node_labels
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def _draw_node_labels(self, labels, **kwargs):
pos = kwargs.pop('pos', self._pos)
return nx.draw_networkx_labels(self._G, pos, labels=labels, **kwargs)
示例12: plot_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def plot_graph(self):
import matplotlib.pyplot as plt
pos=networkx.spring_layout(self.G,iterations=2000)
#pos=networkx.spectral_layout(G)
#pos = networkx.random_layout(G)
networkx.draw_networkx_nodes(self.G, pos)
networkx.draw_networkx_edges(self.G, pos, arrows=True)
networkx.draw_networkx_labels(self.G, pos)
plt.show()
示例13: draw_transmat_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def draw_transmat_graph(G, edge_threshold=0, lw=1, ec='0.2', node_size=15):
num_states = G.number_of_nodes()
edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]
edgewidth = np.array(edgewidth)
edgewidth[edgewidth<edge_threshold] = 0
labels = {}
labels[0] = '1'
labels[1]= '2'
labels[2]= '3'
labels[num_states-1] = str(num_states)
npos=circular_layout(G, scale=1, direction='CW')
lpos=circular_layout(G, scale=1.15, direction='CW')
nx.draw_networkx_edges(G, npos, alpha=0.8, width=edgewidth*lw, edge_color=ec)
nx.draw_networkx_nodes(G, npos, node_size=node_size, node_color='k',alpha=0.8)
ax = plt.gca()
nx.draw_networkx_labels(G, lpos, labels, fontsize=18, ax=ax); # fontsize does not seem to work :/
ax.set_aspect('equal')
return ax
示例14: make_snap
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def make_snap(self, step, output_file="None",draw_connection_line=False,G=None):
self.track_code_last_position = self.get_all_points_from_videoframe(step)
self.axarr.texts = []
self.clear_frequency()
self.update_coverage_regions()
self.show_frequency(draw_connection_line=draw_connection_line)
# showing the STEP in the upper left corner of the figure
size = self.fig.get_size_inches() * self.fig.dpi
plt.text(size[0]*0.02, size[1]*0.05,"Step: %i"%step, dict(size=10, color='b'))
# showing the GRAPH
if G !=None:
pos = nx.spring_layout(G,seed=1)
# pos = map_endpoints
pos = [[pos[x][0], pos[x][1]] for x in G.nodes()]
pos = np.array(pos)
pos[:, 0] = (pos[:, 0] - pos[:, 0].min()) / (pos[:, 0].max() - pos[:, 0].min())
pos[:, 1] = (pos[:, 1] - pos[:, 1].min()) / (pos[:, 1].max() - pos[:, 1].min())
size = self.fig.get_size_inches() * self.fig.dpi * 1.5
pos = [self.point_network_map(x, size) for x in pos]
pos = dict(zip(G.nodes(),pos))
nx.draw(G, pos,with_labels=False,node_size=100,nodelist=self.sim.name_endpoints.values(),node_color="#1260A0",node_shape="o")
# rest_nodes = [e for e in G.nodes() if e not in self.sim.name_endpoints.values()]
nodes_level_mobile = self.get_nodes_by_level(G,-1)
nobes_upper_level = self.get_nodes_by_upper_level(G,1)
nx.draw(G, pos,with_labels=False,node_size=100,nodelist=nodes_level_mobile,node_shape="^",node_color="orange")
nx.draw(G, pos,with_labels=True,node_size=100,nodelist=nobes_upper_level,node_shape="s",node_color="red",font_size=8)
# labels = nx.draw_networkx_labels(G, pos)
canvas = plt.get_current_fig_manager().canvas
canvas.draw()
pil_image = Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb())
pil_image.save(output_file+".png")
plt.close('all')
示例15: draw_png
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import draw_networkx_labels [as 別名]
def draw_png(self,path_file):
fig, ax = plt.subplots(nrows=1, ncols=1)
pos = nx.spring_layout(self.G)
nx.draw(self.G, pos)
labels = nx.draw_networkx_labels(self.G, pos)
fig.savefig(path_file) # save the figure to file
plt.close(fig) # close the figure