def _draw_graph_diffing(graph1, graph2, differences):
plt.subplot(121)
pos = nx.pygraphviz_layout(graph1, prog='dot')
nx.draw_networkx_nodes(graph1, pos,
graph1.nodes(), node_color='b', node_size=200)
nx.draw_networkx_nodes(graph1, pos, differences[0],
node_color='r', node_size=600)
nx.draw_networkx_nodes(graph1, pos, differences[2],
node_color='y', node_size=600)
nx.draw_networkx_edges(graph1, pos, graph1.edges())
nx.draw_networkx_labels(graph1, pos, font_size=8)
plt.title('Graph 1')
plt.axis('off')
plt.subplot(122)
pos = nx.pygraphviz_layout(graph2, prog='dot')
nx.draw_networkx_nodes(graph2, pos, graph2.nodes(), node_color='b',
node_size=200)
nx.draw_networkx_nodes(graph2, pos, differences[1], node_color='r',
node_size=600)
nx.draw_networkx_nodes(graph2, pos, differences[3], node_color='g',
node_size=600)
nx.draw_networkx_edges(graph2, pos, graph2.edges())
nx.draw_networkx_labels(graph2, pos, font_size=8)
plt.title('Graph 2')
plt.axis('off')
lr = plt.Circle((0, 0), 5, fc='r')
lb = plt.Circle((0, 0), 5, fc='b')
lg = plt.Circle((0, 0), 5, fc='g')
ly = plt.Circle((0, 0), 5, fc='y')
plt.legend([lb, lr, lg, ly], ['No changed', 'Changed', 'Added',
'Removed'], loc=4)
# plt.savefig(graph1.name + '-' + graph2.name + '.png')
plt.show()
python类draw_networkx_nodes()的实例源码
def Drawcomgraph(G):
#Draw the graph
pos=nx.spring_layout(G)
nx.draw_networkx_edges(G, pos, alpha=0.4)
nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')
#colorList = ['SeaGreen','yellow','brown','pink','purple','blue','green','Salmon','red','c','magenta','orange','white','black','y','skyblue','GreenYellow','cyan']#,'aqua'
nx.draw_networkx_nodes(G, pos, nodelist=G.nodes(), node_size=150)
plt.title("Network Community Analysis")
plt.show()
def plot_and_save_net(self, picpath='../output/net.png'):
net = nx.DiGraph()
edge_label = dict()
for edge in self.edges:
net.add_edge(edge[0], edge[1], weight=1)
edge_label[(edge[0], edge[1])] = edge[3]
if len(edge_label) > 8:
break
# edge_label.update({(edge[0], edge[1]) : edge[2]})
pos = nx.spring_layout(net, k=20) # positions for all nodes
# nodes
nx.draw_networkx_nodes(net, pos, node_size=6000, node_color="green")
# edges
nx.draw_networkx_edges(net, pos,
width=1.5, alpha=0.5, arrows=True, edge_color='black')
# labels
nx.draw_networkx_labels(net, pos, font_size=20)
nx.draw_networkx_edge_labels(net, pos, edge_labels=edge_label, label_pos=0.5, font_family='sans-serif')
plt.axis('off')
plt.savefig(picpath) # save as png
plt.show() # display
dependencygraph.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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()
def draw_relation_graph(G,node_ip,node_main,node_cname):
from networkx.drawing.nx_pydot import graphviz_layout
node_size =100
pos = graphviz_layout(G, prog="fdp") # neato fdp
nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_ip, node_color='red', label="IP")
nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_cname, node_color='green', label="CNAME")
nx.draw_networkx_nodes(G, pos=pos, node_size=160, nodelist=node_main, node_color='blue', label="Main")
nx.draw_networkx_edges(G, pos=pos)
# nx.draw_networkx_labels(G, pos, font_size=10) # show the node labe
plt.legend(loc='lower center', ncol=3, shadow=True, numpoints=1)
plt.axis('off')
plt.savefig('./graph/dd_type.png', dpi=75)
plt.show()
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()
def create_web_network_graph(self):
''' Functions that creates a NetworkX network visualization from the
explored pages
For documentation about NetworkX, check : https://networkx.github.io/'''
#Create a directed graph
web_graph=nx.DiGraph()
# Add our start nodes first to the graph, as the center.
web_graph.add_nodes_from(self.to_visit_urls[0])
#Now we explore our results to add the relevant websites to the graph
for base_url in os.listdir(self.main_directory+"web_content/"):
if self.is_danish_company(base_url): #Only Danish companies are added :
web_graph.add_node(base_url)
#Explore again to fill up all the edges (connections/links) between websites
for base_url in os.listdir(self.main_directory+"web_content/"):
if self.is_danish_company(base_url): # Same as before only Danish companies
#Load up the links from this Danish company to other websites
filename = self.main_directory+"web_content/"+base_url+"/external_urls_"+str(self.redirect_count)+"_redirect.p"
external_base_urls=pickle.load(open(filename, "rb" ))
#Now we also filter the list of external links
for external_link in external_base_urls:
if web_graph.has_node(external_link) : # The link is also in the graph, so the connection is added
web_graph.add_edge(base_url,external_link)
#Finally draw the network
#plt.figure(figsize=(120, 90))
plt.figure(figsize=(40, 40))
pos = nx.random_layout(web_graph)
nx.draw_networkx_nodes(web_graph,pos,node_size=2500)
nx.draw_networkx_nodes(web_graph,nodelist=self.to_visit_urls[0],pos=pos,node_size=3000,node_color='b')
#nx.draw_networkx_labels(web_graph,pos,fontsize=12)
nx.draw_networkx_edges(web_graph,pos,alpha=0.5)
plt.savefig(self.main_directory+"DTU network.png",dpi=40)
plt.show()
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()
def save_topology(adj, sample_folder, dataset_name, graph_name):
graph = nx.Graph()
path = sample_folder+'/'+dataset_name
if not os.path.isdir(path):
os.makedirs(path)
# 1. transfer adj to nx
# adj_list = list(np.squeeze(adj[0,:,:,:]))
adj_list = list(adj)
for src in range(len(adj_list)):
graph.add_node(src)
for dst in range(len(adj_list[src])):
if adj_list[src][dst] >= 0.2: # ?? sample ?? ?? [0,1]???
graph.add_edge(src,dst)
# 2. read position
pos_file = glob.glob(path+'/*.pos')
if pos_file == []:
pos = nx.spring_layout(graph)
pickle.dump(pos, open(path+'/graph.pos','wb'))
else:
pos = pickle.load(open(pos_file[0],'rb'))
# 3. draw graph
nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8)
nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8)
nx.draw_networkx_labels(graph, pos, font_color='w')
plt.savefig(path+'/'+graph_name+'.png')
plt.savefig(path+'/'+graph_name+'.pdf')
# plt.show()
# 4. store graph
pickle.dump(graph, open(path+'/'+graph_name+'.graph','wb'))
def save_topology(adj, path, graph_name, link_possibility):
graph = nx.Graph()
if not os.path.isdir(path):
os.makedirs(path)
# 1. transfer adj to nx
adj_list = list(np.squeeze(adj[0,:,:,:]))
for src in range(len(adj_list)):
graph.add_node(src)
for dst in range(len(adj_list[src])):
if adj_list[src][dst] >= link_possibility: # ?? sample ?? ?? [0,1]???
graph.add_edge(src,dst)
# 2. read position
pos_file = glob.glob(path+'*.pos')
if pos_file == []:
node_size = len(graph.nodes())
tmp_graph = nx.barabasi_albert_graph(node_size,2)
pos = nx.spring_layout(tmp_graph)
pickle.dump(pos, open(path+'graph.pos','wb'))
else:
pos = pickle.load(open(pos_file[0],'rb'))
# 3. draw graph
nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8)
nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8)
nx.draw_networkx_labels(graph, pos, font_color='w')
plt.savefig(path+'/'+graph_name+'.png')
plt.savefig(path+'/'+graph_name+'.pdf')
# plt.show()
plt.clf()
# 4. store graph
pickle.dump(graph, open(path+graph_name+'.graph','wb'))
# ------------------------------
# show_all_variables()
# @purpose: ??TF??????
# ------------------------------
def visualise(self, graph, pos):
import pylab
nx.draw_networkx_nodes(graph, pos)
nx.draw(graph, pos, with_labels=True, node_size=2000, node_color='w')
pylab.show()
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()
def drawRoads(G, edgeColorAttribute='level', edgeColorScale=9, nodeColorAttribute=None, nodeColorScale=None):
pos={}
for n in G.nodes():
pos[n] = (G.node[n]['longitude'],G.node[n]['latitude'])
# nodes
nx.draw_networkx_nodes(G,pos,node_size=0,alpha=0.5,color=colors[-1])
# edges
for i in range(0,9):
selectedEdges = [(u,v) for (u,v,d) in G.edges(data=True) if d['level'] == i]
selectedColors = [colors[i] for e in selectedEdges]
nx.draw_networkx_edges(G,pos,edgelist=selectedEdges,width=edgeWidth[i],edge_color=selectedColors, alpha=0.5)
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()
def plot_module_dependency_graph(graph):
"""
Plot a graph of specified yang modules. this function is used to plot
both the full dependency graph of all yang modules in the DB, or a
subgraph of dependencies for a specified module
:param graph: Graph to be plotted
:return: None
"""
# fixed_pos = { 'ietf-interfaces':(0.01,0.01) }
# fixed_nodes = fixed_pos.keys()
# pos = nx.spring_layout(graph, iterations=200,
# pos=fixed_pos, fixed=fixed_nodes)
#pos = nx.circular_layout(graph)
pos = nx.spring_layout(graph, iterations=2000)
# Draw RFC nodes (yang modules) in red
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, RFC_TAG), node_size=200,
node_shape='s', node_color='red', alpha=0.5, linewidths=0.5)
# Draw draft nodes (yang modules) in green
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, DRAFT_TAG), node_size=200,
node_shape='o', node_color='green', alpha=0.5, linewidths=0.5)
# Draw unknown nodes (yang modules) in orange
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, UNKNOWN_TAG), node_size=200,
node_shape='^', node_color='orange', alpha=1.0, linewidths=0.5)
# Draw edges in light gray (fairly transparent)
nx.draw_networkx_edges(graph, pos=pos, alpha=0.25, linewidths=0.1, arrows=False)
# Draw labels on nodes (modules)
nx.draw_networkx_labels(graph, pos=pos, font_size=10, font_weight='bold', alpha=1.0)
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()
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()
def get_fig(self, genes, e_color):
fixed_pair = [(self.fixed_path[i], self.fixed_path[i+1])
for i in range(len(self.fixed_path) - 1)]
for gene in genes:
gene_pair = [(gene[i], gene[i+1]) for i in range(len(gene) - 1)]
for layer_num, (pair, fixed) in enumerate(zip(gene_pair, fixed_pair)):
for first_num in pair[0]:
for second_num in pair[1]:
first_node = self.node_ids[(layer_num, first_num)]
second_node = self.node_ids[(layer_num + 1, second_num)]
if self.graph.has_edge(first_node, second_node):
self.node_upsize(first_node)
self.node_upsize(second_node)
weight = self.graph.get_edge_data(first_node, second_node)['weight']
weight += self.edge_weight_add
self.graph.add_edge(first_node, second_node, color = e_color, weight = weight)
else:
self.graph.add_edge(first_node, second_node, color = e_color, weight = self.init_edge_weight)
for fixed in fixed_pair:
for f_1 in fixed[0]:
for f_2 in fixed[1]:
if (not f_1 == None) and (not f_2 == None):
self.graph.add_edge(f_1, f_2, color = self.fixed_color, weight = self.fixed_weight)
nodes = self.graph.nodes(data = True)
node_color = 'g'
node_size = [node[1]['size'] for node in nodes]
node_shape = 's'
edges = self.graph.edges()
edge_color = [self.graph[u][v]['color'] for u,v in edges]
weights = [self.graph[u][v]['weight'] for u,v in edges]
nx.draw_networkx_nodes(self.graph, nodes = nodes, pos=nx.get_node_attributes(self.graph,'Position'), node_color = node_color, node_size = node_size, node_shape = node_shape)
nx.draw_networkx_edges(self.graph, edges = edges, pos=nx.get_node_attributes(self.graph,'Position'), edge_color = edge_color, width = weights)
def draw_glowing_nodes(self, size):
for i in range(self.glow_iter):
glowsize = [ x + (6.0 * x * (i + 1) / self.glow_iter) for x in size]
nx.draw_networkx_nodes(self.g, self.pos, alpha=0.025, cmap='gist_rainbow',
node_color=self.colors, node_size=glowsize, linewidths=0)
nx.draw_networkx_nodes(self.g, self.pos, alpha=1.0, cmap='gist_rainbow',
node_color=self.colors, node_size=size, linewidths=0)
return
def _draw_nodes(self, nodelist, **kwargs):
node_color = kwargs.get('node_color', 'r')
if isinstance(node_color, dict):
node_color = [node_color[n] for n in nodelist]
kwargs['node_color'] = node_color
labels = kwargs.get('labels', {k: k for k in nodelist})
if labels is not False:
self._draw_node_labels(labels)
return nx.draw_networkx_nodes(self._G, self._pos, nodelist=nodelist, **kwargs)