python无向图可视化

文章目录

  • 背景
  • 完整代码
    • 示例一
    • 效果一
    • 示例二
    • 效果二

背景

刷到leetcode上一些使用并查集的图的题,难度不小,将其中间过程可视化是一个不错的debug方法

完整代码

示例一

import networkx as nx
import matplotlib.pyplot as plt
 
nodes=[
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
    '13',
]

edges=[
    ('1','3'),
    ('2','5'),
    ('3','11'),
    ('4','2'),
    ('5','13'),
    ('6','7'),
    ('7','8'),
    ('8','4'),
    ('9','12'),
    ('10','9'),
    ('11','6'),
    ('13','10')
]

G=nx.Graph()

for node in nodes:
    G.add_node(node)

G.add_edges_from(edges)

# # 计算最短路径
# shortest_way=nx.shortest_path(G,"1","13")
# print(shortest_way)
 
nx.draw(G, with_labels=True,node_color='y')
plt.show()

效果一

效果如下
python无向图可视化_第1张图片

示例二

给个更复杂的无向图,只需替换点和edges就可以:

nodes=[
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
    '13',
]
edges=[
    ('1','2'),
    ('1','13'),
    ('1','10'),
    ('1','11'),
    ('1','8'),
    ('1','5'),
    ('1','12'),
    ('1','9'),
    ('1','3'),
    ('1','7'),
    ('2','1'),
    ('2','4'),
    ('2','5'),
    ('2','6'),
    ('2','13'),
    ('2','8'),
    ('2','11'),
    ('2','12'),
    ('2','9'),
    ('3','13'),
    ('3','7'),
    ('3','12'),
    ('3','8'),
    ('3','11'),
    ('3','4'),
    ('3','10'),
    ('3','1'),
    ('4','2'),
    ('4','10'),
    ('4','12'),
    ('4','13'),
    ('4','11'),
    ('4','3'),
    ('4','6'),
    ('4','9'),
    ('5','2'),
    ('5','12'),
    ('5','13'),
    ('5','11'),
    ('5','1'),
    ('5','10'),
    ('6','2'),
    ('6','7'),
    ('6','9'),
    ('6','8'),
    ('6','13'),
    ('6','12'),
    ('6','10'),
    ('6','4'),
    ('6','11'),
    ('7','6'),
    ('7','8'),
    ('7','3'),
    ('7','11'),
    ('7','10'),
    ('7','12'),
    ('7','13'),
    ('7','1'),
    ('8','7'),
    ('8','6'),
    ('8','9'),
    ('8','3'),
    ('8','1'),
    ('8','13'),
    ('8','2'),
    ('9','6'),
    ('9','12'),
    ('9','8'),
    ('9','13'),
    ('9','1'),
    ('9','10'),
    ('9','4'),
    ('9','2'),
    ('10','4'),
    ('10','1'),
    ('10','13'),
    ('10','7'),
    ('10','11'),
    ('10','5'),
    ('10','9'),
    ('10','3'),
    ('10','6'),
    ('10','12'),
    ('11','7'),
    ('11','1'),
    ('11','5'),
    ('11','3'),
    ('11','10'),
    ('11','4'),
    ('11','13'),
    ('11','6'),
    ('11','2'),
    ('12','5'),
    ('12','9'),
    ('12','4'),
    ('12','3'),
    ('12','7'),
    ('12','1'),
    ('12','6'),
    ('12','10'),
    ('12','2'),
    ('13','3'),
    ('13','5'),
    ('13','6'),
    ('13','1'),
    ('13','9'),
    ('13','10'),
    ('13','4'),
    ('13','8'),
    ('13','2'),
    ('13','7'),
    ('13','11')
]

效果二

python无向图可视化_第2张图片

你可能感兴趣的:(计算机科学与技术,数据可视化,python,无向图,networkx,最短路径)