Skip to main content
 首页 » 编程设计

python之如何在 python 中的 networkx 中绘制具有重复边的图形

2025年05月04日16rubylouvre

我需要绘制一个具有重复边的图(即,2 个节点之间有多个边)。我试过:

import networkx as nx 
edges = [(0, 1), (0, 1)] 
 
G = nx.DiGraph () 
G.add_edges_from (edges) 
 
print G.edges () 
#[(0, 1)] 

重复的条目被简单地丢弃。有什么办法吗?

请您参考如下方法:

我也不是 networkx 方面的专家,但是根据文档 here :

Multigraphs NetworkX provides classes for graphs which allow multiple edges between any pair of nodes. The MultiGraph and MultiDiGraph classes allow you to add the same edge twice, possibly with different edge data. This can be powerful for some applications, but many algorithms are not well defined on such graphs. Shortest path is one example. Where results are well defined, e.g. MultiGraph.degree() we provide the function. Otherwise you should convert to a standard graph in a way that makes the measurement well defined.

因此,如果进行了一项更改,该示例应该可以正常工作 - 按如下方式创建 G:

G = nx.MultiGraph()