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类spring_layout()的实例源码
def create_image(g, path):
path = os.path.relpath(path)
if pygraphviz:
a = nx.nx_agraph.to_agraph(g)
# ['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop']
a.layout(prog='neato', args="-Goverlap=false -Gsplines=true") # splines=true
a.draw(path)
elif plt:
nodes = g.nodes(True)
colors = [attrs['color'] for n, attrs in nodes]
labels = {n: attrs['label'] for n, attrs in nodes}
if graphviz_layout:
pos = graphviz_layout(g)
else:
pos = nx.spring_layout(g)
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color=colors, alpha=0.3)
nx.draw_networkx_edges(g, pos, style='solid', alpha=0.2)
nx.draw_networkx_labels(g, pos, labels, alpha=0.5)
# plt.show()
plt.imsave(path) # todo: this is not tested!
print 'Image saved to', path
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 save(self, path='out.png'):
import networkx
import matplotlib.pyplot as plt
pos = networkx.spring_layout(self.graph, iterations=500)
# pos = networkx.spectral_layout(self.graph)
# pos = networkx.shell_layout(self.graph)
# pos = networkx.fruchterman_reingold_layout(self.graph)
nodelist = list(range(self.num_rooms))
networkx.draw_networkx_nodes(self.graph, pos, nodelist=nodelist)
edgelist = sorted(self.edges - self.secret_edges)
secret = sorted(self.secret_edges)
networkx.draw_networkx_edges(self.graph, pos, edgelist=edgelist,
edge_color='k')
networkx.draw_networkx_edges(self.graph, pos, edgelist=secret,
edge_color='r')
networkx.draw_networkx_labels(self.graph, pos, self.labels)
plt.savefig(path)
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 Drawsubgraph(HG, DrawGraph):
#Draw the graph
#print HG.nodes()
pos=nx.spring_layout(HG)
nx.draw_networkx_edges(HG, pos, alpha=0.4)
#nx.draw_networkx_labels(HG, pos, font_size=10, font_family='sans-serif')
i = 0
colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua'
for key in DrawGraph.keys():
nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=20,node_color=colorList[i%len(colorList)])
i = i + 1
plt.title("Network Community Analysis")
plt.show()
###========================================================================================
def drawcomgraph(HG, DrawGraph):
#Draw the graph
#print HG.nodes()
pos=nx.spring_layout(HG)
nx.draw_networkx_edges(HG, pos, alpha=0.4)
nx.draw_networkx_labels(HG, pos, font_size=6, font_family='sans-serif')
i = 0
colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua'
for key in DrawGraph.keys():
nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=100,node_color=colorList[i%len(colorList)])
i = i + 1
plt.title("Network Community Analysis")
plt.show()
#************************************************************************
def drawcomgraph(HG, DrawGraph):
#Draw the graph
#print HG.nodes()
pos=nx.spring_layout(HG)
nx.draw_networkx_edges(HG, pos, alpha=0.4)
nx.draw_networkx_labels(HG, pos, font_size=6, font_family='sans-serif')
i = 0
colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua'
for key in DrawGraph.keys():
nx.draw_networkx_nodes(HG, pos, nodelist=DrawGraph[key], node_size=100,node_color=colorList[i%len(colorList)])
i = i + 1
plt.title("Network Community Analysis")
plt.show()
#************************************************************************
def graph_visualize(G, args):
import networkx as nx
import numpy as np
# ???????????????????????????
pos = nx.spring_layout(G)
# ?????? ????????????????????
plt.figure()
nx.draw_networkx(G, pos, with_labels=False, alpha=0.4,font_size=0.0,node_size=10)
plt.savefig(args.directory+"/graph/graph.png")
nx.write_gml(G, args.directory+"/graph/graph.gml")
# ??????
plt.figure()
degree_sequence=sorted(nx.degree(G).values(),reverse=True)
dmax=max(degree_sequence)
dmin =min(degree_sequence)
kukan=range(0,dmax+2)
hist, kukan=np.histogram(degree_sequence,kukan)
plt.plot(hist,"o-")
plt.xlabel('degree')
plt.ylabel('frequency')
plt.grid()
plt.savefig(args.directory+'/graph/degree_hist.png')
def draw_graph(edges):
G = nx.DiGraph()
G.add_edges_from(edges)
values = [1.0 for node in G.nodes()]
# Specify the edges you want here
edge_colours = ['black' for edge in G.edges()]
black_edges = [edge for edge in G.edges()]
# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('Reds'), node_color = values, node_size=4800)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True)
nx.draw_networkx_labels(G,pos,font_size=12,font_family='sans-serif')
plt.axis('off')
plt.show()
# In[183]:
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 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_overlaid_graphs(original, new_graphs, print_text=False):
"""
Draws the new_graphs as graphs overlaid on the original topology
:type new_graphs: list[nx.Graph]
"""
import matplotlib.pyplot as plt
layout = nx.spring_layout(original)
nx.draw_networkx(original, pos=layout)
# want to overlay edges in different colors and progressively thinner
# so that we can see what edges are in a tree
line_colors = 'rbgycm'
line_width = 2.0 ** (min(len(new_graphs), len(line_colors)) - 1) # use this for visualising on screen
# line_width = 3.0 ** (min(len(new_graphs), len(line_colors)) - 1) # use this for generating diagrams
for i, g in enumerate(new_graphs):
if print_text:
log.info(nx.info(g))
log.info("edges:", list(g.edges()))
nx.draw_networkx(g, pos=layout, edge_color=line_colors[i % len(line_colors)], width=line_width)
# advance to next line width
line_width /= 1.7 # use this for visualising on screen
# line_width /= 2.0 # use this for generating diagrams
plt.show()
def __init__(self):
self.ticks_in_week = 10
self.tick = 0
self.current_date = 0
self.real_sizes = None
self.nodes = self.get_graph_nodes()
self.nodesizes = self.get_node_sizes()
self.dates = self.get_dates()
self.edges = self.get_edges()
self.iters = (len(self.dates)-1)*self.ticks_in_week - 2
self.curr_edges = self.recalc_edges()
self.sizes = self.nodesizes[self.dates[self.current_date]]
self.size_inc = self.calc_size_inc()
self.g = nx.Graph()
self.g.add_nodes_from(self.nodes)
self.fig = plt.figure(figsize=(16,9),dpi=240)
#self.pos = nx.spring_layout(self.g)
self.load_positions()
self.resize_pos()
self.colors = [random.random() for _ in self.nodes]
self.glow_iter = 20
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 draw(self, layout='circular', figsize=None):
"""Draw all graphs that describe the DGM in a common figure
Parameters
----------
layout : str
possible are 'circular', 'shell', 'spring'
figsize : tuple(int)
tuple of two integers denoting the mpl figsize
Returns
-------
fig : figure
"""
layouts = {
'circular': nx.circular_layout,
'shell': nx.shell_layout,
'spring': nx.spring_layout
}
figsize = (10, 10) if figsize is None else figsize
fig = plt.figure(figsize=figsize)
rocls = np.ceil(np.sqrt(len(self.graphs)))
for i, graph in enumerate(self.graphs):
ax = fig.add_subplot(rocls, rocls, i+1)
ax.set_title('Graph ' + str(i+1))
ax.axis('off')
ax.set_frame_on(False)
g = graph.nxGraph
weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
width=2, edge_color=weights)
return fig
def draw(self, layout='circular', figsize=None):
"""Draw graph in a matplotlib environment
Parameters
----------
layout : str
possible are 'circular', 'shell', 'spring'
figsize : tuple(int)
tuple of two integers denoting the mpl figsize
Returns
-------
fig : figure
"""
layouts = {
'circular': nx.circular_layout,
'shell': nx.shell_layout,
'spring': nx.spring_layout
}
figsize = (10, 10) if figsize is None else figsize
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(1, 1, 1)
ax.axis('off')
ax.set_frame_on(False)
g = self.nxGraph
weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
width=2, edge_color=weights)
return fig
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()
def show_graph_communities(graph, partition, color_map=None, with_labels=False):
if color_map is None:
color_map = generate_color_map(partition)
pos = nx.spring_layout(graph,k=0.1,iterations=50)
comm_nodes = utils.partition_to_comm_nodes_map(partition)
for comm, nodes in comm_nodes.items():
nx.draw_networkx_nodes(graph, pos, nodelist=nodes, node_size=400,
node_color=color_map.get(comm), label=comm, cmap=plt.cm.jet)
if with_labels:
nx.draw_networkx_labels(graph, pos, font_size=12)
nx.draw_networkx_edges(graph, pos, alpha=0.3)
plt.legend()
plt.axis('off')
plt.show()
def show_graph(graph, with_labels=False):
pos = nx.spring_layout(graph)
nx.draw_networkx_nodes(graph, pos, node_size=200, node_color='red')
if with_labels:
nx.draw_networkx_labels(graph, pos, font_size=12)
nx.draw_networkx_edges(graph, pos, alpha=0.3)
plt.axis('off')
plt.show()
def draw_partition(graph, partition):
# requires matplotlib.pyplot, uncomment above
# uses community code and sample from http://perso.crans.org/aynaud/communities/ to draw matplotlib graph in shades of gray
g = graph
count = 0
size = float(len(set(partition.values())))
pos = nx.spring_layout(g)
for com in set(partition.values()):
count = count + 1
list_nodes = [nodes for nodes in partition.keys()
if partition[nodes] == com]
nx.draw_networkx_nodes(g, pos, list_nodes, node_size=20,
node_color=str(count / size))
nx.draw_networkx_edges(g, pos, alpha=0.5)
plt.show()
def ped_group(pedgraph, nlist, nscale=600, nalpha=0.95, nsize=15, ealpha=0.2, ewidth=0.3, ecolor="#000000",
atName="attr1", atCol=4):
'''
Receives a networkx graph and plots.
- needs matplotlib package
:param pedgraph: networkX graph object (pedigree)
:param nscale: scale of the plot
:param nalpha: node transparency
:param nsize: node size
:param ncolor: node color
:param ealpha: edge transparency
:param ewidth: edge width
:param ecolor: edge color
:return:
'''
grpList = [line.strip() for line in open(nlist, 'r')]
part = add_node_attribute("ped_testherd.in", pedgraph, atName=atName, atCol=atCol)
values = [part.get(node) for node in grpList]
pos = nx.spring_layout(pedgraph, scale=nscale)
nx.draw_networkx_nodes(pedgraph, pos, nodelist=grpList,
alpha=nalpha, node_color=values, node_size=nsize, linewidths=0.1,
cmap=plt.get_cmap('Paired'))
# label plot not feasable for larger networks
# nx.draw_networkx_labels(pedgraph, pos)
# nx.draw_networkx_edges(pedgraph, pos, alpha=ealpha, width=ewidth, edge_color=ecolor)
plt.axis("off")
plt.show()
topological_sort.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 28
收藏 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
项目源码
文件源码
阅读 32
收藏 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
项目源码
文件源码
阅读 27
收藏 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
项目源码
文件源码
阅读 31
收藏 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
a_star_search.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 26
收藏 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
greedy_bfs.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 28
收藏 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
项目源码
文件源码
阅读 28
收藏 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
项目源码
文件源码
阅读 35
收藏 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