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)
# 绘制图形
colors = ['#008B8B','r','b','orange','y','c','DeepPink','#838B8B','purple','olive','#A0CBE2','#4EEE94']*50
colors = colors[0:len(G.nodes())]
nx.draw_networkx(G,
pos = nx.spring_layout(G),
node_color = colors,
edge_color = colors,
#font_color = colors,
node_size = 200,
font_size = 5,
alpha = 0.99,
width = 1,
font_weight=1
)
plt.axis('off')
plt.show()
运行结果:
{‘a’, ‘b’, ‘c’}
{‘e’, ‘f’, ‘k’, ‘d’}
{‘t’, ‘r’, ‘l’}
2、创建有权重的图
import matplotlib.pyplot as plt
import networkx as nx
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], 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