Python包networkx处理图结构数据

NetworkX是一款Python的软件包,用于创造、操作复杂网络,以及学习复杂网络的结构、动力学及其功能。

import networkx as nx
### 1 图的构建
## 一步步构建
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2, 3])
# G.add_edge(1, 2) # 直接加边,同时加了顶点
G.add_nodes_from([(4, {"color": "red"}),(5, {"color": "green"})])
G.add_edges_from([(1, 2), (1, 3)])
print(G.nodes)
print(G.edges)

## 通过边列表构建
edgelist = [(0, 1), (1, 2), (2, 3)]
G = nx.Graph(edgelist)  # create a graph from an edge list

## 通过相邻定点字典构建
adjacency_dict = {0: (1, 2), 1: (0, 2), 2: (0, 1)}
G = nx.Graph(adjacency_dict)  # create a Graph dict mapping nodes to nbrs
list(G.edges())

## 利用其他图的顶点和边构建图
# 双向图 create a DiGraph using the connections from G
H = nx.DiGraph(G)  
list(H.edges())
nx.draw(H, with_labels=True, font_weight='bold')

G2 = nx.Graph()
H = nx.path_graph(10)
#nx.draw(H, with_labels=True, font_weight='bold')
G2.add_nodes_from(H)
# G2.add_edges_from(H.edges)
G2.add_edges_from([(1, 2), (3, 5),(7,9)])
nx.draw(G2, with_labels=True, font_weight='bold')

## 读取文件,生成图
# Read a graph from a list of edges.
G = nx.read_edgelist("/Users/zhengxueming/test/demo_edge_list.txt") 
nx.draw(G, with_labels=True, font_weight='bold')
# 更多函数,参考
# https://networkx.org/documentation/stable/reference/readwrite/edgelist.html#format

### 2 查看图的元素
G = nx.complete_graph(['a','b','c','d','e'])
nx.draw(G, with_labels=True, font_weight='bold')
# 顶点列表 
print(list(G.nodes))
# 边列表
print(list(G.edges))
# 顶点b和d的所有边
print(G.edges(['b', 'd']))
# 顶点1的所有相邻顶点
print(list(G.adj['a']))
# 顶点c的度数
print(G.degree['c'])
print(G.degree(['c']))
# 顶点d,e的度数
print(G.degree(['d','e'])) # [('d', 4), ('e', 4)] 前面的是顶点名称,后面的度数

print(G.number_of_nodes())
print(G.number_of_edges())

### 3 删除图的元素
G = nx.complete_graph(10)
# 删除顶点
G.remove_node(2)
G.remove_nodes_from([1,5])
print(list(G.nodes))
# 删除边
G.remove_edge(7, 8)

print(list(G.nodes))
nx.draw(G, with_labels=True, font_weight='bold')
# 去除所有的nodes和edges
G.clear()

### 4 设置图、定点和边的属性

# 图属性
G = nx.Graph(day="Friday")
print(G.graph)

G.graph['day'] = "Monday"
print(G.graph)

# 顶点属性
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')

G.nodes[1]['room'] = 714
print(G.nodes.data())

# 边属性
G.add_edge(1, 2, weight=4.7 )
G.add_edges_from([(3, 4), (4, 5)], color='red')
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2
print(G.edges.data())
print(G.edges.data('weight'))

nx.draw(G, with_labels=True, font_weight='bold')

### 5. 有向图
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
nx.draw(DG, with_labels=True, font_weight='bold')

# 出度
print(DG.out_degree(1, weight='weight'))
print(DG.out_degree(1))
# 入度
print(DG.degree(1, weight='weight'))
print(DG.degree(1))

print(list(DG.successors(1)))
print(list(DG.neighbors(1)))

### 6 多边图
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
print(dict(MG.degree(weight='weight')))
nx.draw(MG, with_labels=True, font_weight='bold')

### 7 图合并、子图
# 合并
G = nx.Graph([(0, 1), (0, 2), (1, 2)])
H = nx.Graph([(0, 1), (0, 3), (1, 3), (1, 2)])
U = nx.union(G, H, rename=("G", "H"))
print(U.nodes)
print(U.edges)
nx.draw(U, with_labels=True, font_weight='bold')

# 子图
G = nx.path_graph(6)
def filter_node(n1):
    return n1 != 5

def filter_edge(n1, n2):
    return G[n1][n2].get("cross_me", True)

G[3][4]["cross_me"] = False
view = nx.subgraph_view(G, filter_node=filter_node, filter_edge=filter_edge,)

print(view.nodes())
nx.draw(view, with_labels=True, font_weight='bold')

### 8 图的分析
G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3)])
G.add_node("spam")       # adds node "spam"

# 图中相连通的组分
print(list(nx.connected_components(G)))
# 按顶点度数排序
print(sorted(d for n, d in G.degree()))

# 图所有顶点的连通性
G = nx.cycle_graph(3)
G.add_edge(2, 3)
import pprint  # for nice dictionary formatting
pprint.pprint(nx.all_pairs_node_connectivity(G))

from networkx.algorithms import approximation as approx
G = nx.octahedral_graph()
approx.node_connectivity(G)

# 连个顶点之间的连通性
from networkx.algorithms import approximation as approx
G = nx.octahedral_graph()
nx.draw(G, with_labels=True, font_weight='bold')
approx.local_node_connectivity(G, 0, 5)

# 度中心性
G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
nx.degree_centrality(G)

# 更多请参考
# https://networkx.org/documentation/stable/reference/algorithms/component.html

### 9 图的可视化
# 边可视化
G = nx.dodecahedral_graph()
edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))

# 顶点可视化
G = nx.dodecahedral_graph()
nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))

# label可视化
G = nx.dodecahedral_graph()
labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))

# 图可视化
G = nx.dodecahedral_graph()
nx.draw(G)
nx.draw(G, pos=nx.spring_layout(G))  # use spring layout

G = nx.complete_graph(5)
pos = nx.shell_layout(G)
# Draw the original graph
# nx.draw(G, pos=pos)  
# Draw a subgraph, reusing the same node positions
nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")

import matplotlib.pyplot as plt
G = nx.petersen_graph()
subax1 = plt.subplot(121)
nx.draw(G, with_labels=True, font_weight='bold')
subax2 = plt.subplot(122)
# Draw networkx graph G with shell layout.
nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
plt.show()  


# 更多,参考
# https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx_edges.html

参考

https://networkx.org/documentation/stable/reference/introduction.html

https://networkx.org/documentation/stable/tutorial.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值