# 【3】数据分析-7-由煮面条到图论到图论--NetworkX

## 一、NetworkX概论

NetworkX是一个用Python语言开发的图论与复杂网络建模工具，内置了常用的图与复杂网络分析算法，可以方便的进行复杂网络数据分析、仿真建模等工作。networkx支持创建简单无向图、有向图和多重图（multigraph）；内置许多标准的图论算法，节点可为任意数据；支持任意的边值维度，功能丰富，简单易用。

pip install networkx


import networkx as nx
print nx


#!-*- coding:utf8-*-
import networkx as nx
#linux系统下没有作图系统，需要如下生成图片
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#windows下直接
import matplotlib.pyplot as plt
G = nx.Graph() #建立一个空的无向图G G.add_node(1) #添加一个节点1
print "nodes:", G.nodes() #输出全部的节点： [1, 2, 3]
print "edges:", G.edges() #输出全部的边：[(2, 3)]
print "number of edges:", G.number_of_edges() #输出边的数量：1
nx.draw(G,with_labels=True) #nodes的标签加上
plt.savefig("wuxiangtu.png")
plt.show()


nodes: [1, 2, 3]
edges: [(2, 3)]
number of edges: 1


#-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


#!-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


Graph.to_undirected()
Graph.to_directed()


#!-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G = G.to_undirected()
nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.show()


#-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

road_nodes = {'a': 1, 'b': 2, 'c': 3}
road_edges = [('a', 'b'), ('b', 'c')]

nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


#-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

#road_nodes = {'a': 1, 'b': 2, 'c': 3}
road_edges = [('a', 'b'), ('b', 'c')]

nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()                                        #建立一个空的无向图G
G.add_weighted_edges_from([(3, 4, 3.5),(3, 5, 7.0)])                                     #对于无向图，边3-2与边2-3被认为是一条边

print G.get_edge_data(2, 3)
print G.get_edge_data(3, 4)
print G.get_edge_data(3, 5)

nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.show()


{}
{'weight': 3.5}
{'weight': 7.0}


import networkx as nx
import matplotlib.pyplot as plt

#计算1：求无向图的任意两点间的最短路径
G = nx.Graph()
path = nx.all_pairs_shortest_path(G)
print path[1]


• 强连通：有向图中任意两点v1、v2间存在v1到v2的路径（path）及v2到v1的路径。
• 弱联通：将有向图的所有的有向边替换为无向边，所得到的图称为原图的基图。如果一个有向图的基图是连通图，则有向图是弱连通图。

import networkx as nx
import matplotlib.pyplot as plt
#G = nx.path_graph(4, create_using=nx.Graph())
#0 1 2 3
G = nx.path_graph(4, create_using=nx.DiGraph())    #默认生成节点0 1 2 3，生成有向变0->1,1->2,2->3

for c in nx.weakly_connected_components(G):
print c

print [len(c) for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)]

nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


set([0, 1, 2, 3, 7, 8])
[6]


import networkx as nx
import matplotlib.pyplot as plt
#G = nx.path_graph(4, create_using=nx.Graph())
#0 1 2 3
G = nx.path_graph(4, create_using=nx.DiGraph())

#for c in nx.strongly_connected_components(G):
#    print c
#
#print [len(c) for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)]

con = nx.strongly_connected_components(G)
print con
print type(con)
print list(con)

nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()


<type 'generator'>
[set([8, 1, 2, 3]), set([0])]


import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
sub_graph = G.subgraph([5, 6, 8])
#sub_graph = G.subgraph((5, 6, 8))  #ok  一样

nx.draw(sub_graph)
plt.savefig("youxiangtu.png")
plt.show()


## 二、案例：

import networkx as nx
from networkx.algorithms.approximation.clique import max_clique, clique_removal

G = nx.Graph()
nx.draw(G, with_labels=True)
plt.savefig('temp/network.png')
plt.show()

cliques_primers1 = list(nx.find_cliques(G))

cliques_primers2 = list(list(clique_removal(G))[1])


## 三、讨论：

1.加颜色

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

nx.draw(G, cmap=plt.get_cmap('jet'), node_color=values)
plt.show()


http://stackoverflow.com/questions/13517614/draw-different-color-for-nodes-in-networkx-based-on-their-node-value

http://www.cnblogs.com/kaituorensheng/p/5423131.html