本文整理汇总了Python中networkx.draw方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.draw方法的具体用法?Python networkx.draw怎么用?Python networkx.draw使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.draw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: time_align_visualize
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def time_align_visualize(alignments, time, y, namespace='time_align'):
plt.figure()
heat = np.flip(alignments + alignments.T +
np.eye(alignments.shape[0]), axis=0)
sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1)
plt.savefig(namespace + '_heatmap.svg')
G = nx.from_numpy_matrix(alignments)
G = nx.maximum_spanning_tree(G)
pos = {}
for i in range(len(G.nodes)):
pos[i] = np.array([time[i], y[i]])
mst_edges = set(nx.maximum_spanning_tree(G).edges())
weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8
for u, v in G.edges() ]
plt.figure()
nx.draw(G, pos, edges=G.edges(), width=10)
plt.ylim([-1, 1])
plt.savefig(namespace + '.svg')
示例2: dbg_draw
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
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)
示例3: plot_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def plot_graph(G, ax=None):
"""
Plots a networkx graph.
Parameters
----------
G:
The networkx graph of interest.
ax: Matplotlib axes object
Defaults to None. Matplotlib axes to plot on.
"""
weights = np.real([*nx.get_edge_attributes(G, 'weight').values()])
pos = nx.shell_layout(G)
nx.draw(G, pos, node_color='#A0CBE2', with_labels=True, edge_color=weights,
width=4, edge_cmap=plt.cm.Blues, ax=ax)
plt.show()
#############################################################################
# HAMILTONIANS AND DATA
#############################################################################
示例4: log_matrix
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def log_matrix(writer, mat, name, epoch, fig_size=(8, 6), dpi=200):
"""Save an image of a matrix to disk.
Args:
- writer : A file writer.
- mat : The matrix to write.
- name : Name of the file to save.
- epoch : Epoch number.
- fig_size : Size to of the figure to save.
- dpi : Resolution.
"""
plt.switch_backend("agg")
fig = plt.figure(figsize=fig_size, dpi=dpi)
mat = mat.cpu().detach().numpy()
if mat.ndim == 1:
mat = mat[:, np.newaxis]
plt.imshow(mat, cmap=plt.get_cmap("BuPu"))
cbar = plt.colorbar()
cbar.solids.set_edgecolor("face")
plt.tight_layout()
fig.canvas.draw()
writer.add_image(name, tensorboardX.utils.figure_to_image(fig), epoch)
示例5: log_assignment
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def log_assignment(assign_tensor, writer, epoch, batch_idx):
plt.switch_backend("agg")
fig = plt.figure(figsize=(8, 6), dpi=300)
# has to be smaller than args.batch_size
for i in range(len(batch_idx)):
plt.subplot(2, 2, i + 1)
plt.imshow(
assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap("BuPu")
)
cbar = plt.colorbar()
cbar.solids.set_edgecolor("face")
plt.tight_layout()
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
writer.add_image("assignment", data, epoch)
# TODO: unify log_graph and log_graph2
示例6: plot
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def plot(self, file_path: str):
try:
import matplotlib.pyplot as plt
except ImportError as err:
raise('matplotlib not installed. Failed at: {}', err)
try:
pos = nx.nx_agraph.graphviz_layout(self.directed)
nx.draw(
self.directed,
pos=pos,
node_size=1200,
node_color='lightblue',
linewidths=0.25,
font_size=8,
font_weight='bold',
with_labels=True,
dpi=5000
)
# edge_labels = nx.get_edge_attributes(self.directed, name='attr_dict')
# nx.draw_networkx_edge_labels(self.directed, pos=pos, edge_labels=edge_labels)
plt.savefig(file_path)
except IOError as err:
raise('Could not create plot image: {}', err)
示例7: draw_wstate_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [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()
示例8: print_graph_nx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def print_graph_nx(vertices, edges, print_dist=False):
import networkx as nx
G=nx.DiGraph()
labels = []
for v in vertices:
G.add_node(v)
for v in vertices:
for e in edges:
G.add_edge(e[0], e[1], weight=int(e[2]))
#labels += [(e[0], e[1]), e[2]]
print("Nodes of graph: ")
print(G.nodes())
print("Edges of graph: ")
print(G.edges())
nx.draw(G, with_labels=True, node_color='y')
#nx.draw_networkx_edge_labels(G,labels)
plt.savefig("simulation_graph.png") # save as png
plt.show()
示例9: draw_wsn
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def draw_wsn(motes=None, algo='quadrants', **kwargs):
"""
This function allows to draw the list of motes generated with one of the WSN generation functions hereafter.
:param motes: a list of motes as output by one of the WSN generation functions hereafter
"""
assert algo in __all__
import networkx as nx
from matplotlib import pyplot as plt
motes = motes or eval(algo)(**kwargs)
wsn = nx.Graph()
for mote in motes:
wsn.add_node(mote['id'])
pos = {m['id']: (m['x'], m['y']) for m in motes}
col = ['green'] + (len(motes) - 2) * ['blue'] + ['red']
nx.draw(wsn, pos, node_color=col)
plt.show()
示例10: log_assignment
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def log_assignment(assign_tensor, writer, epoch, batch_idx):
plt.switch_backend('agg')
fig = plt.figure(figsize=(8,6), dpi=300)
# has to be smaller than args.batch_size
for i in range(len(batch_idx)):
plt.subplot(2, 2, i+1)
plt.imshow(assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap('BuPu'))
cbar = plt.colorbar()
cbar.solids.set_edgecolor("face")
plt.tight_layout()
fig.canvas.draw()
#data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
#data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
data = tensorboardX.utils.figure_to_image(fig)
writer.add_image('assignment', data, epoch)
示例11: draw_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [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
示例12: build_word_ego_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [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()
示例13: get
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def get(self, id):
"""
Returns evidence graph as a png
TODO - requires matplotlib which is hard to install
"""
args = parser.parse_args()
assoc = get_association(id, user_agent=USER_AGENT)
eg = {'graphs':[assoc.get('evidence_graph')]}
digraph = convert_json_object(eg)
#fp = tempfile.TemporaryFile()
nx.draw(digraph)
fn = '/tmp/'+id+'.png' # TODO
#plt.savefig(fn)
return send_file(fn)
示例14: run
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def run(self):
with open('reservoir.output', 'a') as output:
prompt = '# ' + str(datetime.datetime.now()) + \
'\n' + json.dumps(config, indent=4) + '\n'
print(prompt, end='')
output.write(prompt)
for i in range(self.start_node, self.end_node + 1, self.step):
self.N = i
self.D = self.degree_func(self.N)
self.train()
self._run()
for j in range(1):
res = 'N = ' + str(self.N) + ', D = ' + '%.15f' % self.D + \
', RMS = ' + '%.15e' % Decimal(self.RMS[j]) + '\n'
print(res, end='')
output.write(res)
config["reservoir"]["start_node"] = i
self.draw()
# Invoke automatically when exit, write the progress back to config file
示例15: draw_shell
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw [as 别名]
def draw_shell(G, **kwargs):
"""Draw networkx graph with shell layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See networkx.draw_networkx() for a description of optional keywords,
with the exception of the pos parameter which is not used by this
function.
"""
nlist = kwargs.get('nlist', None)
if nlist is not None:
del(kwargs['nlist'])
draw(G, shell_layout(G, nlist=nlist), **kwargs)