import networkx as nx
# 创建一个空图(不包含节点和边)
G = nx.Graph()
# 添加节点
G.add_nodes_from([1,2,3,4])
# 添加边
G.add_edges_from([(1,2),(1,3),(2,3),(2,4)])
# 可视化
nx.draw(G, node_size=500, with_labels=True)
As = nx.adjacency_matrix(G)
print(As)
As.todense()
已知图的邻接矩阵,创建图
import numpy as np
A = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
G = nx.from_numpy_array(A)
nx.draw(G, node_size=500, with_labels=True)
加权图
G = nx.Graph()
G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5), (0, 2, 1.5)])
As = nx.adjacency_matrix(G)
print(As.todense())
有向图
G = nx.DiGraph()
# 添加节点
G.add_nodes_from([1,2,3,4])
# 添加边
G.add_edges_from([(1,2),(1,3),(2,3),(3,4)])
nx.draw(G, node_size=500, with_labels=True)
度、平均度以及度分布
G = nx.Graph()
# 添加节点
G.add_nodes_from([1,2,3,4])
# 添加边
G.add_edges_from([(1,2),(2,3),(2,4),(3,4)])
nx.draw(G, node_size=500, with_labels=True)
# 获取网络G的度
d = nx.degree(G)
d
d = dict(nx.degree(G))
print("平均度为:", sum(d.values())/len(G.nodes))
# 获取度分布
nx.degree_histogram(G) # 返回所有位于区间[0, dmax]的度值的频率列表
绘制度分布直方图
import matplotlib.pyplot as plt
x = list(range(max(d.values())+1))
y = [i/len(G.nodes) for i in nx.degree_histogram(G)]
print(x)
print(y)
plt.bar(x, y, width=0.5, color="red")
plt.xlabel("$k$", fontsize=14)
plt.ylabel("$p_k$", fontsize=14)
plt.xlim([0,4])
路径和距离
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5])
G.add_edges_from([(1,2),(2,3),(2,5),(3,4),(4,5)])
nx.draw(G, node_size=500, with_labels=True)
nx.shortest_path(G, source=1, target=4)
# 两个节点之间所有的最短路径
list(nx.all_shortest_paths(G, source=1, target=4))
# 求两个节点的最短路径长度(距离)
nx.shortest_path_length(G, source=1, target=4)
# 求整个网络的平均距离
nx.average_shortest_path_length(G)
连通性
Ga = nx.Graph()
Ga.add_nodes_from([1,2,3,4,5,6,7])
Ga.add_edges_from([(1,2),(1,3),(2,3),(4,7),(5,6),(5,7),(6,7)])
nx.draw(Ga, node_size=500, with_labels=True)
Gb = nx.Graph()
Gb.add_nodes_from([1,2,3,4,5,6,7])
Gb.add_edges_from([(1,2),(1,3),(2,3),(2,4),(4,7),(5,6),(5,7),(6,7)])
nx.draw(Gb, node_size=500, with_labels=True)
print(nx.is_connected(Ga))
print(nx.is_connected(Gb))
集聚系数
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5])
G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(2,3),(2,4),(2,5),(3,4),(3,5),(4,5)])
nx.draw(G, node_size=500, with_labels=True)
print(nx.clustering(G, 1))
G.remove_edges_from([(2,4),(3,4),(3,5)])
nx.draw(G, node_size=500, with_labels=True)
print(nx.clustering(G, 1))
平均集聚系数与全局集聚系数的区别
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5,6,7])
G.add_edges_from([(1,2),(2,3),(2,4),(2,5),(4,5),(4,6),(4,7),(5,7)])
nx.draw(G, node_size=500, with_labels=True)
# 平均集聚系数
print(nx.average_clustering(G))
# 全局集聚系数
print(nx.transitivity(G))