1、创建一个无权重的图,并展示
edge_list.csv
a,b,2
a,c,3
b,c,3
d,e,1
d,f,3
e,k,1
r,l,3
t,l,2
import networkx as nx
import matplotlib.pyplot as plt
G =nx.Graph() # 创建无向图
with open('edge_list.csv') as f:for line in f:edge = line.strip().split(',')try:G.add_edge(edge[0], edge[1])except:continue# 计算连通图
connected_components = nx.connected_components(G)
for component in connected_components:print(component)# 绘制图形
nx.draw(G, with_labels=True)# 显示图形
plt.show()
运行结果:
{‘a’, ‘b’, ‘c’}
{‘e’, ‘f’, ‘k’, ‘d’}
{‘t’, ‘r’, ‘l’}
2、创建有权重的图
import matplotlib.pyplot as plt
import networkx as nxG=nx.Graph()with open('edge_list.csv') as f:for line in f:edge = line.strip().split(',')try:G.add_edge(edge[0], edge[1], weight=int(edge[2]))except:continue# 节点位置
pos=nx.spring_layout(G)
# 画出节点位置
nx.draw_networkx_nodes(G,pos,node_size=300)
# 画出边
edge=[(u,v) for (u,v,d) in G.edges(data=True) ]
nx.draw_networkx_edges(G,pos,edgelist=edge,width=6)
# 画出节点的标签labels
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
# nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')plt.axis('off')
plt.savefig("weighted_graph.png") # save as png
plt.show() # display