import networkx as nx
import matplotlib.pyplot as plt
# 无向图网络
G1 = nx.Graph()
G1.add_edge('A', 'B')
G1.add_edge('A', 'C')
G1.add_edge('A', 'D')
G1.add_edge('A', 'E')
G1.add_edge('B', 'C')
G1.add_edge('B', 'D')
G1.add_edge('B', 'E')
G1.add_edge('F', 'C')
nx.spring_layout(G1)
nx.draw_networkx(G1)
plt.show()
print('全部节点为:', G1.nodes())
print('全部边为:', G1.edges())
print('全部边数量:', G1.number_of_edges())
# 有向图网络
G2 = nx.DiGraph()
G2.add_edge('A', 'B')
G2.add_edge('A', 'D')
G2.add_edge('C', 'A')
G2.add_edge('D', 'E')
nx.spring_layout(G2)
nx.draw_networkx(G2)
plt.show()
# 加权图网络
G3 = nx.Graph()
G3.add_edge('A', 'B', weight=25)
G3.add_edge('A', 'C', weight=8)
G3.add_edge('A', 'D', weight=11)
G3.add_edge('A', 'E', weight=1)
G3.add_edge('B', 'C', weight=4)
G3.add_edge('B', 'D', weight=7)
G3.add_edge('B', 'E', weight=1)
G3.add_edge('E', 'C', weight=1)
nx.spring_layout(G3)
nx.draw_networkx(G3)
plt.show()
# 某一点到其他点的BFS图
T = nx.bfs_tree(G3, 'A')
nx.draw_networkx(T)
plt.show()
# 自带的Cycle图
G4 = nx.cycle_graph(50)
pos = nx.spring_layout(G4, iterations=200)
nx.draw(G4, pos, node_color=range(50), node_size=500, font_weight='bold', with_labels=True)
plt.show()
print('G1中A的度数:', nx.degree(G1, 'A'))
print('G1中A的局部聚类系数:', nx.clustering(G1, 'A'))
print('G1中两个点的最短路径:', nx.shortest_path(G1, 'A', 'F'))
print('G3中两个点的最短路径长度:', nx.shortest_path_length(G3, 'D', 'E'))
print('G1的节点离心度:', nx.eccentricity(G1))
# 导入带权图
G = nx.Graph()
G.add_edges_from([('a', 'b', {'weight': 0.6}),
('a', 'c', {'weight': 0.2}),
('a', 'd', {'weight': 0.1}),
('c', 'e', {'weight': 0.7})])
# 对不同权重进行处理,取得相应权重的点集列表,比如weight>0.5的点集列表为[('a', 'b'), ('c', 'e')]
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]
node1 = ['a', 'b']
node2 = ['c', 'd', 'e']
edge = {(u, v): d['weight'] for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5} # 加权处理
# 必须设定一个统一的布局,保证下面分步绘制的图的统一性,而且分步绘制时pos是一个必须参数
pos = nx.spring_layout(G)
# 分步绘制完整的图
# (1)绘制点,必须参数(G,pos),还可以指定点集(列表或optional)(默认全点集),形状,大小,透明度,等
nx.draw_networkx_nodes(G, pos=pos, nodelist=node1) # > 0.5
nx.draw_networkx_nodes(G, pos=pos, nodelist=node2, node_shape='*', node_color='r', node_size=700)
# (2)绘制边,必须参数(G,pos, 还可以指定边集(边的元组集合(列表))(默认全边集),形状,大小,透明度,等
nx.draw_networkx_edges(G, pos=pos, edgelist=elarge)
nx.draw_networkx_edges(G, pos=pos, edgelist=esmall, edge_color='b', style='dashed', width=3)
# (3)绘制部分节点的标签,必须参数(G,pos),还可以指定点集(字典(值)或optional)(默认全点集),形状,大小,透明度,等
nx.draw_networkx_labels(G, pos=pos, labels={'a': 'a', 'b':'b', 'c': 'c', 'd': 'd', 'e': 'e'}, font_size=18, font_color='b', font_family='sans-serif')
# (4)绘制边的标签,必须参数(G,pos),还可以指定边集(字典:键是边的元组,值是边的某个属性值)(默认全边集),形状,大小,透明度,等
# 根据字典,通过键给边添加值的标签,{('a', 'b'): 0.6, ('c', 'e'): 0.7}
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge, font_size=7, font_color='black', font_family='sans-serif')
# 显示
plt.axis('off')
plt.show()