def draw(self, label_nodes=False):
"""Draw the graph using matplotlib in a color-coordinated manner."""
try:
import matplotlib.pyplot as plt
print 'Node colors: red=core, blue=major-building, green=distribution, yellow=minor-building, cyan=server,' \
' magenta=host, black=floor-switch, white=rack-switch, white=cloud, green=gateway'
# TODO: ignore building internals?
colormap = {'c': 'r', 'b': 'b', 'd': 'g', 'm': 'y', 's': 'c', 'h': 'm', 'f': 'k', 'r': 'w', 'x': 'w', 'g': 'g'}
node_colors = [colormap[node[0]] for node in self.topo.nodes()]
# shell layout places nodes as a series of concentric circles
positions = nx.shell_layout(self.topo, [self.core_nodes,
# sort the building routers by degree in attempt to get ones connected to each other next to each other
sorted(self.major_building_routers, key=lambda n: nx.degree(self.topo, n)) + self.distribution_routers + self.server_nodes,
self.hosts + self.minor_building_routers])
# then do a spring layout, keeping the inner nodes fixed in positions
positions = nx.spring_layout(self.topo, pos=positions, fixed=self.core_nodes + self.server_nodes + self.major_building_routers + self.distribution_routers)
nx.draw(self.topo, node_color=node_colors, pos=positions, with_labels=label_nodes)
plt.show()
except ImportError:
print "ERROR: couldn't draw graph as matplotlib.pyplot couldn't be imported!"
python类draw()的实例源码
def nx_plot_tree(server, node_size=200, **options):
"""Visualize the tree using the networkx package.
This plots to the current matplotlib figure.
Args:
server: A DataServer instance.
options: Options passed to networkx.draw().
"""
import networkx as nx
edges = server.estimate_tree()
perplexity = server.latent_perplexity()
feature_names = server.feature_names
V = 1 + len(edges)
G = nx.Graph()
G.add_nodes_from(range(V))
G.add_edges_from(edges)
H = nx.relabel_nodes(G, dict(enumerate(feature_names)))
node_size = node_size * perplexity / perplexity.max()
options.setdefault('alpha', 0.2)
options.setdefault('font_size', 8)
nx.draw(H, with_labels=True, node_size=node_size, **options)
def draw(passage):
G = nx.DiGraph()
terminals = sorted(passage.layer(layer0.LAYER_ID).all, key=operator.attrgetter("position"))
G.add_nodes_from([(n.ID, {"label": n.text, "node_color": "white"}) for n in terminals])
G.add_nodes_from([(n.ID, {"label": "IMPLICIT" if n.attrib.get("implicit") else "",
"node_color": "gray" if isinstance(n, Linkage) else (
"white" if n.attrib.get("implicit") else "black")})
for n in passage.layer(layer1.LAYER_ID).all])
G.add_edges_from([(n.ID, e.child.ID, {"label": e.tag, "style": "dashed" if e.attrib.get("remote") else "solid"})
for layer in passage.layers for n in layer.all for e in n])
pos = topological_layout(passage)
nx.draw(G, pos, arrows=False, font_size=10,
node_color=[d["node_color"] for _, d in G.nodes(data=True)],
labels={n: d["label"] for n, d in G.nodes(data=True) if d["label"]},
style=[d["style"] for _, _, d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G, pos, font_size=8,
edge_labels={(u, v): d["label"] for u, v, d in G.edges(data=True)})
graph.py 文件源码
项目:uai2017_learning_to_acquire_information
作者: evanthebouncy
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def draw_graph(gv, ge, name):
Gr = nx.Graph()
for i in range(N):
Gr.add_node(i, pos=gv[i])
for i in range(N):
for j in range(N):
if ge[i][j]:
Gr.add_edge(i,j)
labels = dict()
for i in range(N):
labels[i] = str(i)
pos=nx.get_node_attributes(Gr,'pos')
nx.draw(Gr, pos=pos,
node_size=400, with_labels=False)
nx.draw_networkx_labels(Gr, pos, labels)
plt.savefig(name)
dfs_visual.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def DrawDFSPath(G, dfs_stk):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
for i in dfs_stk:
#if there is more than one node in the dfs-forest, then print the corresponding edges
if len(i) > 1:
for j in i[ :(len(i)-1)]:
if i[i.index(j)+1] in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r')
else:
#if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it.
for k in i[1::-1]:
if k in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r')
break
#main function
def _render(self, mode = "human", close = False):
if close:
return
import matplotlib.pyplot as plt
if self.tick == 0:
plt.ion()
G = self.G
attrs = nx.get_node_attributes(G, "ndd")
values = ["red" if attrs[v] else "blue" for v in G.nodes()]
plt.clf()
nx.draw(G,
pos = nx.circular_layout(G),
node_color = values)
plt.pause(0.01)
return []
def plot_workflow_graph_image(self):
"""
Show the image from workflow_graph
"""
# Change layout according to necessity
pos = nx.spring_layout(self.graph)
nx.draw(self.graph, pos, node_color='#004a7b', node_size=2000,
edge_color='#555555', width=1.5, edge_cmap=None,
with_labels=True, style='dashed',
label_pos=50.3, alpha=1, arrows=True, node_shape='s',
font_size=8,
font_color='#FFFFFF')
# Must import pyplot here!
import matplotlib.pyplot as plt
plt.show()
# If necessary save the image
# plt.savefig(filename, dpi=300, orientation='landscape', format=None,
# bbox_inches=None, pad_inches=0.1)
def vis_graph(graph, name='net2net', show=False):
path = osp.dirname(name)
name = osp.basename(name)
if path == '':
path = name
mkdir_p(osp.join(root_dir, "output", path), delete=False)
restore_path = os.getcwd()
os.chdir(osp.join(root_dir, "output", path))
with open(name + "_graph.json", "w") as f:
f.write(graph.to_json())
try:
plt.close('all')
nx.draw(graph, with_labels=True)
if show:
plt.show()
plt.savefig('graph.png')
# plt.close('all')
except Exception as inst:
logger.warning(inst)
os.chdir(restore_path)
def plot(self):
# print(list(self.root.edge_list()))
labels = {}
for i, j in self.root.edge_list():
labels[i] = i
labels[j] = j
G = nx.Graph(self.root.edge_list())
pos = graphviz_layout(G, prog='dot')
nx.draw(G, pos)
nx.draw_networkx_labels(G, pos, labels)
plt.show()
# class BST_count(BST):
# def __init__(self, url=None, file=None,tree=None):
# if tree:
# pass
# else:
# super(BST).__init__(url,file)
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()
def draw_loop():
"""
Draw the graph in a loop
"""
global G
plt.ion()
# mng = plt.get_current_fig_manager()
# mng.resize(*mng.window.maxsize())
plt.draw()
for line in fileinput.input():
if output(line):
plt.clf()
nx.draw(G)
plt.draw()
def draw_net_using_node_coords(net):
"""
Plot a networkx.Graph by using the lat and lon attributes of nodes.
Parameters
----------
net : networkx.Graph
Returns
-------
fig : matplotlib.figure
the figure object where the network is plotted
"""
import matplotlib.pyplot as plt
fig = plt.figure()
node_coords = {}
for node, data in net.nodes(data=True):
node_coords[node] = (data['lon'], data['lat'])
ax = fig.add_subplot(111)
networkx.draw(net, pos=node_coords, ax=ax, node_size=50)
return fig
def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True):
import matplotlib.pyplot as plt
# pos = nx.spring_layout(self.graph)
pos = nx.shell_layout(self.graph, dim=1024, scale=0.5)
# pos = nx.random_layout(self.graph, dim=1024, scale=0.5)
if label_edges:
edge_labels = {
(edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True)
}
nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5)
if label_nodes:
labels = {node[0]: node[1] for node in self.graph.nodes(data=True)}
nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8)
# nx.draw(self.graph, with_labels=True, arrows=True, node_size=80)
nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80)
plt.savefig(file_name, dpi=1024)
def plot_cumulative_gains(lift: pd.DataFrame):
fig, ax = plt.subplots()
fig.canvas.draw()
handles = []
handles.append(ax.plot(lift['PercentCorrect'], 'r-', label='Percent Correct Predictions'))
handles.append(ax.plot(lift['PercentCorrectBestCase'], 'g-', label='Best Case (for current model)'))
handles.append(ax.plot(lift['PercentAvgCase'], 'b-', label='Average Case (for current model)'))
ax.set_xlabel('Total Population (%)')
ax.set_ylabel('Number of Respondents (%)')
ax.set_xlim([0, 9])
ax.set_ylim([10, 100])
try:
labels = [int((label+1)*10) for label in [float(item.get_text()) for item in ax.get_xticklabels() if len(item.get_text()) > 0]]
except BaseException as e:
print([item.get_text() for item in ax.get_xticklabels()])
ax.set_xticklabels(labels)
fig.legend(handles, labels=[h[0].get_label() for h in handles])
fig.show()
def draw_tier2():
print 'loading tier2 data'
loadEntity(tier2filename)
print 'entity size: ', len(entityList)
G = nx.Graph()
G.add_node(u'???')
for entity in entityList:
name = entity.name[0].decode('utf8')
print name
G.add_node(name)
G.add_edge(u'???',name)
for child in entity.child:
cn = child.decode('utf8')
G.add_node(cn)
G.add_edge(name, cn)
pos=nx.spring_layout(G) # positions for all nodes
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
# labels
nx.draw_networkx_labels(G,pos,font_size=15,font_family='sans-serif')
plt.axis('off')
plt.show()
# draw tier 3 test
def draw_grid(ts, edgelabel='control', prop_colors=None, current_node=None):
assert edgelabel is None or nx.is_weighted(ts.g, weight=edgelabel)
pos = nx.get_node_attributes(ts.g, 'location')
if current_node == 'init':
current_node = next(ts.init.iterkeys())
colors = dict([(v, 'w') for v in ts.g])
if current_node:
colors[current_node] = 'b'
for v, d in ts.g.nodes_iter(data=True):
if d['prop']:
colors[v] = prop_colors[tuple(d['prop'])]
colors = colors.values()
labels = nx.get_node_attributes(ts.g, 'label')
nx.draw(ts.g, pos=pos, node_color=colors)
nx.draw_networkx_labels(ts.g, pos=pos, labels=labels)
edge_labels = nx.get_edge_attributes(ts.g, edgelabel)
nx.draw_networkx_edge_labels(ts.g, pos=pos,
edge_labels=edge_labels)
def draw(self):
"""Draw the topology"""
try:
import matplotlib.pyplot as plt
except ImportError:
log.warning("matplotlib could not be found")
return
node_color = range(len(self.graph.nodes()))
pos = nx.spring_layout(self.graph,iterations=200)
nx.draw(self.graph,pos,node_color=node_color,
node_size=[100*(nx.degree(self.graph,x)**1.25) for x in self.graph.nodes()],
edge_color=['blue' for x,y,z in self.graph.edges(data=True)],
edge_cmap=plt.cm.Blues,
with_labels=True,
cmap=plt.cm.Blues)
plt.show()
def test_subgraph_within_box(self):
bounding_box = box(121.428387, 31.027371, 121.430863, 31.030227)
a = time.time()
subgraph = self.sg.subgraph_within_box(bounding_box)
print(time.time() - a)
if self.show_plots:
plt.figure()
nx.draw(subgraph, pos=self.sg.node_xy, node_size=50)
plt.show()
def graphNetworkx(self, buds_visible = False, filter_assym_edges = False, labels_visible = True, iterations = 1000):
self.buds_visible = buds_visible
self.filter_assym_edges = filter_assym_edges
G = self.makeGraphData()
if hasattr(self, 'nodeColorInfo'):
nodeColors = self.useColorData(G, 'networkx')
#print G.node
if labels_visible:
nx.draw_networkx(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1)
else:
nx.draw(G, pos=nx.spring_layout(G, iterations = iterations), node_color = nodeColors, linewidths = 1)
plt.show()
assignment_prob_hungarian.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def DrawGraph(B):
l, r = nx.bipartite.sets(B)
pos = {}
# Update position for node from each group
pos.update((node, (1, index)) for index, node in enumerate(l))
pos.update((node, (2, index)) for index, node in enumerate(r))
nx.draw(B, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u, v), d['length']) for u, v, d in B.edges(data = True)])
nx.draw_networkx_edge_labels(B, pos, edge_labels = edge_labels, label_pos = 0.2, font_size = 11) #prints weight on all the edges
return pos
#main function
topological_sort.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def CreateResultGraph(sorted_list):
D = nx.DiGraph()
for i in range(len(sorted_list)-1):
D.add_edge(sorted_list[i], sorted_list[i+1])
pos = nx.spring_layout(D)
val_map = {}
val_map[sorted_list[0]] = 'green'
val_map[sorted_list[len(sorted_list)-1]] = 'red'
values = [val_map.get(node, 'blue') for node in D.nodes()]
nx.draw(D, pos, with_labels = True, node_color =values)
#takes input from the file and creates a directed graph
topological_sort.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, node_color ='blue') #with_labels=true is to show the node number in the output graph
return pos
#main function
tsp_christofides.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def DrawGraph(G,color):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = color) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G,'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
return pos
#main function
graph_coloring.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def DrawGraph(G,col_val):
pos = nx.spring_layout(G)
values = [col_val.get(node, 'blue') for node in G.nodes()]
nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'black' ,width = 1, alpha = 0.7) #with_labels=true is to show the node number in the output graph
#main function
bfs.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
return pos
#main function
greedy_bfs.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def DrawPath(G, source, dest):
pos = nx.spring_layout(G)
val_map = {}
val_map[source] = 'green'
val_map[dest] = 'red'
values = [val_map.get(node, 'blue') for node in G.nodes()]
nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'b' ,width = 1, alpha = 0.7) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u, v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.5, font_size = 11) #prints weight on all the edges
return pos
#main function
k_centers_problem.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def DrawGraph(G, centers):
pos = nx.spring_layout(G)
color_map = ['blue'] * len(G.nodes())
#all the center nodes are marked with 'red'
for c in centers:
color_map[c] = 'red'
nx.draw(G, pos, node_color = color_map, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G, 'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
#main function
prims.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G,'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
return pos
#main function
egocentric_network_2.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.2) #with_labels=true is to show the node number in the output graph
nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'blue')
nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'blue', alpha = 0.5)
return pos
egocentric_network_2.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_list, vert):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8) #with_labels=true is to show the node number in the output graph
nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
return pos