本文整理汇总了Python中networkx.draw函数的典型用法代码示例。如果您正苦于以下问题:Python draw函数的具体用法?Python draw怎么用?Python draw使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了draw函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_difference
def draw_difference(self, path_old, path_new):
self.draw_path(path_old)
H = self.G.copy()
H.add_edges_from(path_edges(path_new.path))
H_ = nx.difference(self.G, H)
nx.draw(self.G, self.pos)
nx.draw(H_, self.pos, edge_color='blue')
示例2: plot_neighbourhood
def plot_neighbourhood(ax,G,direction_colors={},node_color='white',alpha=0.8,labels=True,node_size=300,font_size=12):
"""
Plots the Graph using networkx' draw method.
Each edge should have an direction assigned to it; with the direction_colors
parameter you can assign different directions different colors for plotting.
@param ax Axis-object.
@param G Graph-object.
@param direction_colors Dictionary with directions as keys and colors as values.
"""
pos_dict={}
for i in G.node:
pos_dict[i]=np.array([G.node[i]['phi'],G.node[i]['theta']])
edge_colors='black'
if len(direction_colors.keys())>0:
edge_colors=[]
for edge_origin in G.edge.keys():
for edge_target in G.edge[edge_origin].keys():
if direction_colors.keys().count(G.edge[edge_origin][edge_target]['direction']):
edge_colors.append(direction_colors[G.edge[edge_origin][edge_target]['direction']])
else:
edge_target.append('black')
nx.draw(G,pos_dict,ax,with_labels=labels,edge_color=edge_colors,node_color=node_color,alpha=alpha,node_size=node_size,font_size=font_size)
return G
示例3: display_graph_by_specific_mac
def display_graph_by_specific_mac(self, mac_address):
G = nx.Graph()
count = 0
edges = set()
edges_list = []
for pkt in self.pcap_file:
src = pkt[Dot11].addr1
dst = pkt[Dot11].addr2
if mac_address in [src, dst]:
edges_list.append((src, dst))
edges.add(src)
edges.add(dst)
plt.clf()
plt.suptitle('Communicating with ' + str(mac_address), fontsize=14, fontweight='bold')
plt.title("\n Number of Communicating Users: " + str(int(len(edges))))
plt.rcParams.update({'font.size': 10})
G.add_edges_from(edges_list)
nx.draw(G, with_labels=True, node_color=MY_COLORS)
plt.show()
示例4: draw_graph
def draw_graph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos) # networkx draw()
#P.draw() # pylab draw()
plt.show() # display
示例5: plot_graph
def plot_graph(graph, protein, Tc, nodecolor, nodesymbol):
fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)
drawkwargs = {'font_size': 10,\
'linewidths': 1,\
'width': 2,\
'with_labels': True,\
'node_size': 700,\
'node_color':nodecolor,\
'node_shape':'o',\
'style':'solid',\
'alpha':1,\
'cmap': mpl.cm.jet}
pos=nx.spring_layout(graph, iterations=200)
nx.draw(graph, pos, **drawkwargs )
if protein in Tc:
string = "Protein: %i Cancer"
string_s = (protein)
title=string%string_s
else:
string = "Protein: %i Non-Cancer"
string_s = (protein)
title=string%string_s
ax.set_title(title)
filepath = 'images'+'/'+zeros(protein, padlength=4)+'.jpg'
plt.savefig(filepath, bbox_inches='tight')
print 'Written to: '+filepath
fig.clf()
plt.close()
del fig
示例6: plot_func
def plot_func(play, stats):
generation = stats["generation"]
best = stats["generation_best"]
every = play.config["live_plot"].get("every", 100)
if generation == 0:
plt.figure(figsize=(10, 8))
if (generation % every) == 0:
plt.clf()
# create graph
graph = nx.DiGraph()
traverse_tree(best.root, graph)
labels = dict((n, d["label"]) for n, d in graph.nodes(data=True))
pos = nx.graphviz_layout(graph, prog='dot')
nx.draw(
graph,
pos,
with_labels=True,
labels=labels,
arrows=False,
node_shape=None
)
# plot graph
plt.draw()
plt.pause(0.0001) # very important else plot won't be displayed
示例7: plot
def plot(graph, **kwargs):
pos=kwargs.get('pos', nx.spring_layout(graph))
if kwargs.get('draw_edge_labels', False): edge_labels=nx.draw_networkx_edge_labels(graph,pos)
else: edge_labels=[]
nx.draw(graph, pos, edge_labels=edge_labels, **kwargs)
# plt.savefig('plot.pdf')
plt.show()
示例8: display
def display(g, title):
"""Displays a graph with the given title."""
pos = nx.circular_layout(g)
plt.figure()
plt.title(title)
nx.draw(g, pos)
nx.draw_networkx_edge_labels(g, pos, font_size=20)
示例9: add_switch
def add_switch(self):
"""Add switches to the topology graph
Extracts switches information stored in switch_list dictionary
important fields:
switch.dp.id """
print('self.sw_list_body {}'.format(self.sw_list_body))
for index,switch in enumerate( self.switch_list):
# dpid = format_dpid_str(dpid_to_str(switch.dp.id))
self.graph.add_node(switch.dp.id)
dpid=switch.dp.id
# dpid = hex2decimal(switch['ports']['dpid'])
# self.graph.add_node(switch['ports']['dpid'])
# for node in switch["ports"]:
# dpid = hex2decimal(node['dpid'])
# self.graph.add_node(dpid)
print(self.graph.nodes())
nx.draw(self.graph)
plt.show()
示例10: plot_graph
def plot_graph(graph, ax=None, cmap='Spectral', **kwargs):
"""
Parameters
----------
graph : object
A networkX or derived graph object
ax : objext
A MatPlotLib axes object
cmap : str
A MatPlotLib color map string. Default 'Spectral'
Returns
-------
ax : object
A MatPlotLib axes object. Either the argument passed in
or a new object
"""
if ax is None:
ax = plt.gca()
cmap = matplotlib.cm.get_cmap(cmap)
# Setup edge color based on the health metric
colors = []
for s, d, e in graph.edges_iter(data=True):
if hasattr(e, 'health'):
colors.append(cmap(e.health)[0])
else:
colors.append(cmap(0)[0])
nx.draw(graph, ax=ax, edge_color=colors)
return ax
示例11: main
def main():
base_layout = [("value", 32)]
packed_layout = structuring.pack_layout(base_layout, pack_factor)
rawbits_layout = [("value", 32*pack_factor)]
source = SimActor(source_gen(), ("source", Source, base_layout))
sink = SimActor(sink_gen(), ("sink", Sink, base_layout))
# A tortuous way of passing integer tokens.
packer = structuring.Pack(base_layout, pack_factor)
to_raw = structuring.Cast(packed_layout, rawbits_layout)
from_raw = structuring.Cast(rawbits_layout, packed_layout)
unpacker = structuring.Unpack(pack_factor, base_layout)
g = DataFlowGraph()
g.add_connection(source, packer)
g.add_connection(packer, to_raw)
g.add_connection(to_raw, from_raw)
g.add_connection(from_raw, unpacker)
g.add_connection(unpacker, sink)
comp = CompositeActor(g)
reporter = perftools.DFGReporter(g)
fragment = comp.get_fragment() + reporter.get_fragment()
sim = Simulator(fragment, Runner())
sim.run(1000)
g_layout = nx.spectral_layout(g)
nx.draw(g, g_layout)
nx.draw_networkx_edge_labels(g, g_layout, reporter.get_edge_labels())
plt.show()
示例12: draw_related_mashup
def draw_related_mashup(self, mashups, current_mashup=None, highlight_mashup=None):
"""
Draw the realated mashup graph
"""
self.ax.clear()
layout = {}
g = nx.Graph()
node_size = {}
node_color = {}
node_map = {}
node_id = 0
for mashup in mashups:
if node_map.get(mashup["id"]) == None:
node_map[mashup["id"]] = node_id
g.add_node(node_id)
node_size[node_id] = 20
if current_mashup and mashup["id"] == current_mashup["id"]:
node_color[node_id] = 0.7
node_size[node_id] = 180
layout[node_id] = (random.random() , random.random())
else:
node_color[node_id] = 0.5
layout[node_id] = (random.random() , random.random())
node_id = node_id + 1
for i in range(0, len(mashups)):
node_id_start = node_map.get(mashups[i]["id"])
node_id_end = node_map.get(current_mashup["id"])
g.add_edge(node_id_start, node_id_end)
try:
nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False)
except Exception, e:
print e
示例13: draw
def draw(self):
"""
Canvas for draw the relationship between apis
"""
mashup_map = data_source.mashup_with_apis()
layout = {}
g = nx.Graph()
node_size = {}
node_color = {}
node_map = {}
node_id = 0
for key in mashup_map:
if len(mashup_map[key]) == 20:
for api in mashup_map[key]:
if node_map.get(api) == None:
node_map[api] = node_id
g.add_node(node_id)
node_size[node_id] = 50
node_color[node_id] = 0.5
layout[node_id] = (random.random() , random.random())
node_id = node_id + 1
for i in range(0, len(mashup_map[key])):
for j in range(0, len(mashup_map[key])):
node_id_start = node_map.get(mashup_map[key][i])
node_id_end = node_map.get(mashup_map[key][j])
g.add_edge(node_id_start, node_id_end)
node_size[node_id_start] = node_size[node_id_start] + 5
node_size[node_id_end] = node_size[node_id_end] + 5
try:
nx.draw(g, pos=layout, node_size=[node_size[v] for v in g.nodes()], node_color=[node_color[v] for v in g.nodes()], with_labels=False)
except Exception, e:
print e
示例14: draw
def draw(graph):
pos = nx.graphviz_layout(graph, prog='sfdp', args='')
list_nodes = graph.nodes()
plt.figure(figsize=(20,10))
nx.draw(graph, pos, node_size=20, alpha=0.4, nodelist=list_nodes, node_color="blue", with_labels=False)
plt.savefig('graphNX.png')
plt.show()
示例15: show_graph_with_labels
def show_graph_with_labels(adjacency_matrix, mylabels):
rows, cols = np.where(adjacency_matrix == 1)
edges = zip(rows.tolist(), cols.tolist())
gr = nx.Graph()
gr.add_edges_from(edges)
nx.draw(gr, node_size=2000, labels=mylabels, with_labels=True)
plt.show()