1. 根据网络的接邻矩阵生成图
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_excel("C:\\Users\\Administrator\\Desktop\\network.xlsx", header=None, index_col=None)
G = nx.from_pandas_adjacency(df)
nx.draw(G, node_size=500)
plt.show()
注意excel文件路径中的“\”要改为“\\"
2.构建图
import networkx as nx
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 21, 22, 23])
G.add_edges_from([(1, 2), (1, 6), (2, 3), (2, 7), (3, 4), (3, 8), (4, 5), (4, 9), (5, 10), (6, 7), (6, 11), (7, 8), (7, 12), (8, 9), (8, 13), (9, 10), (11, 12), (11, 16), (12, 13), (16, 21), (21, 22), (22, 23)])
nx.draw(G, node_size=500, with_labels=True)
import matplotlib.pyplot as plt
plt.show()
3.平均聚类系数
print(nx.average_clustering(G))
“G”为矩阵的名字
4.网络效率
print(nx.global_efficiency(G))
5.最大连通子图的相对大小
print(nx.is_connected(G))
print(nx.number_connected_components(G))
Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
largest_cc = G.subgraph(Gcc[0])
a = largest_cc.number_of_nodes()
b = G.number_of_nodes()
print(a/b)
“a”为最大联通子图节点数目,“b”为网络节点数目
6.平均度
d = dict(nx.degree(G))
print(d)
print("平均度为:", sum(d.values())/len(G.nodes))