如何在Python中使用Networkx和matplotlib绘制自环

1 投票
1 回答
1642 浏览
提问于 2025-04-18 07:33

我正在使用networkx这个库,想要在图中找到循环。我写了以下代码:

import networkx as nx
import matplotlib.pyplot as plt
import pylab

tg = nx.Graph()

h_lat_dir = {1: [("A", "A"), ("B", "B"), ("A", "B")], 2: [("C", "D")],
    3: [("C", "F")], 4: [("F", "F")], 5: [("C", "C"), ("C", "E"), ("D", "E"), ("E", "E")],
    6: [("D", "D")]}

for wght, edgelist in h_lat_dir.iteritems():
    tg.add_edges_from(edgelist, weight=wght)

print nx.cycle_basis(tg)


nx.write_dot(tg, 'multi.dot')
nx.draw_graphviz(tg)
pylab.show()

结果是

[['A'], ['B'], ['C'], ['F'], ['E', 'D', 'C'], ['D'], ['E']]

还有这个图:

enter image description here

我为什么看不到自环呢?(每个顶点都有一个自环)有没有办法把它们画出来呢?

1 个回答

2

使用NetworkX接口来和Graphviz配合(通过pygraphviz或pydot):

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([(0,1), (0,2), (1,1), (1,2)])
nx.write_dot(G,'graph.dot')

然后运行

dot -Tpng graph.dot > graph.png

在这里输入图片描述

撰写回答