python networkx 包绘制复杂网络关系图的实现

1. 创建一个图

```
import networkx as nx
g = nx.Graph()
g.clear() #将图上元素清空
```

2. 节点

```

```

```
or
a = [2,3]

```

```
g.nodes() #可以将以上5个节点打印出来看看
```

```
H = nx.path_graph(10)
```

```
g.remove_node(node_name)
g.remove_nodes_from(nodes_list)
```

3. 边

```
e = (2,3)
```

```

```

```
n = 10
H = nx.path_graph(n)

```

```
g.remove_edge(edge)
g.remove_edges_from(edges_list)
```

4. 查看图上点和边的信息

```
g.number_of_nodes() #查看点的数量
g.number_of_edges() #查看边的数量
g.nodes() #返回所有点的信息(list)
g.edges() #返回所有边的信息(list中每个元素是一个tuple)
g.neighbors(1) #所有与1这个点相连的点的信息以列表的形式返回
g[1] #查看所有与1相连的边的属性，格式输出：{0: {}, 2: {}} 表示1和0相连的边没有设置任何属性（也就是{}没有信息），同理1和2相连的边也没有任何属性
```

method explanation
Graph.has_node(n) Return True if the graph contains the node n.
Graph.__contains__(n) Return True if n is a node, False otherwise.
Graph.has_edge(u, v) Return True if the edge (u,v) is in the graph.
Graph.order() Return the number of nodes in the graph.
Graph.number_of_nodes() Return the number of nodes in the graph.
Graph.__len__() Return the number of nodes.
Graph.degree([nbunch, weight]) Return the degree of a node or nodes.
Graph.degree_iter([nbunch, weight]) Return an iterator for (node, degree).
Graph.size([weight]) Return the number of edges.
Graph.number_of_edges([u, v]) Return the number of edges between two nodes.
Graph.nodes_with_selfloops() Return a list of nodes with self loops.
Graph.selfloop_edges([data, default]) Return a list of selfloop edges.
Graph.number_of_selfloops() Return the number of selfloop edges.

5. 图的属性设置

```
g = nx.Graph(day="Monday")
g.graph # {'day': 'Monday'}
```

```
g.graph['day'] = 'Tuesday'
g.graph # {'day': 'Tuesday'}

```

6. 点的属性设置

```
print g.node['benz'] # {'fuel': '1.5L', 'money': 10000}
print g.node['benz']['money'] # 10000
print g.nodes(data=True) # data默认false就是不输出属性信息，修改为true，会将节点名字和属性信息一起输出
```

7. 边的属性设置

```
g.clear()
n = 10
H = nx.path_graph(n)
g[1][2]['color'] = 'blue'

g[1][2]['weight'] = 4.7
g.edge[1][2]['weight'] = 4

```

8. 不同类型的图（有向图Directed graphs , 重边图 Multigraphs）

Directed graphs

```
DG = nx.DiGraph()
print DG.out_degree(1) # 打印结果：2 表示：找到1的出度
print DG.out_degree(1, weight='weight') # 打印结果：0.8 表示：从1出去的边的权值和，这里权值是以weight属性值作为标准，如果你有一个money属性，那么也可以修改为weight='money'，那么结果就是对money求和了
print DG.successors(1) # [2,4] 表示1的后继节点有2和4
print DG.predecessors(1) # [3] 表示只有一个节点3有指向1的连边
```

Multigraphs

```
MG=nx.MultiGraph()
print MG.degree(weight='weight') # {1: 1.25, 2: 1.75, 3: 0.5}
GG=nx.Graph()
for nbr,edict in nbrs.items():
minvalue=min([d['weight'] for d in edict.values()])

print nx.shortest_path(GG,1,3) # [1, 2, 3]

```

9.  图的遍历

```
g = nx.Graph()
print n, nbrs
for nbr,eattr in nbrs.items():
# nbr表示跟n连接的点，eattr表示这两个点连边的属性集合，这里只设置了weight，如果你还设置了color，那么就可以通过eattr['color']访问到对应的color元素
data=eattr['weight']
if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
```

10. 图生成和图上的一些操作

```
subgraph(G, nbunch)  - induce subgraph of G on nodes in nbunch
union(G1,G2)    - graph union
disjoint_union(G1,G2) - graph union assuming all nodes are different
cartesian_product(G1,G2) - return Cartesian product graph
compose(G1,G2)   - combine graphs identifying nodes common to both
complement(G)   - graph complement
create_empty_copy(G)  - return an empty copy of the same graph class
convert_to_undirected(G) - return an undirected representation of G
convert_to_directed(G) - return a directed representation of G
```

11. 图上分析

```
g = nx.Graph()
nx.connected_components(g) # [[1, 2, 3], ['spam']] 表示返回g上的不同连通块
sorted(nx.degree(g).values())
```

```
>>> G=nx.Graph()
>>> e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
>>> print(nx.dijkstra_path(G,'a','d'))
['a', 'c', 'd']

```

12. 图的绘制

```
nx.draw(g)
nx.draw_random(g) #点随机分布
nx.draw_circular(g) #点的分布形成一个环
nx.draw_spectral(g)

```

```
import matplotlib.pyplot as plt
plt.show()

```

```
nx.draw(g)
plt.savefig("path.png")

```

```
g = nx.cubical_graph()
nx.draw(g, pos=nx.spectral_layout(g), nodecolor='r', edge_color='b')
plt.show()

```

13. 图形种类的选择

Graph Type NetworkX Class

reference：https://networkx.github.io/documentation/networkx-1.10/reference/classes.html

QQ号联系： 360901061

【本文对您有帮助就好】