NetworkX中MultiDiGraph创建求助:双向边未正常显示
在NetworkX中正确创建并绘制MultiDiGraph的解决方法
你的代码核心问题是:创建MultiDiGraph实例后,又通过nx.from_edgelist(edgelist)重新给变量G赋值,而这个方法默认生成的是无向Graph对象——这会让(2,3)和(3,2)被判定为同一条边,绘图自然只显示一条,且你最初创建的MultiDiGraph会被完全覆盖,根本没发挥作用。
以下是两种修正方案:
方案一:直接向MultiDiGraph添加边
import networkx as nx import matplotlib.pyplot as plt # 创建MultiDiGraph实例 G = nx.MultiDiGraph() # 添加节点与边 G.add_nodes_from(range(1, 11)) edgelist = [(1, 2), (2, 3), (3, 2), (3, 9), (9, 4), (4, 5), (5, 7), (7, 6), (6, 4), (7, 8), (7, 10), (10, 11), (11, 5)] G.add_edges_from(edgelist) # 调整布局避免边重叠,k值越小节点间距越大 pos = nx.spring_layout(G, k=0.3) nx.draw_networkx(G, pos=pos, with_labels=True, arrows=True, arrowstyle='->', node_size=100, node_color='yellow', edge_color='black', width=3, arrowsize=10) plt.show()
方案二:用from_edgelist直接创建MultiDiGraph
import networkx as nx import matplotlib.pyplot as plt edgelist = [(1, 2), (2, 3), (3, 2), (3, 9), (9, 4), (4, 5), (5, 7), (7, 6), (6, 4), (7, 8), (7, 10), (10, 11), (11, 5)] # 指定create_using参数,直接生成MultiDiGraph G = nx.from_edgelist(edgelist, create_using=nx.MultiDiGraph()) # 补充添加未在边列表中出现的节点 G.add_nodes_from(range(1, 11)) # 绘制图形 pos = nx.spring_layout(G, k=0.3) nx.draw_networkx(G, pos=pos, with_labels=True, arrows=True, arrowstyle='->', node_size=100, node_color='yellow', edge_color='black', width=3, arrowsize=10) plt.show()
额外优化:区分双向边
如果想更清晰地区分(2,3)和(3,2),可以给两条边设置不同颜色单独绘制:
# 先绘制节点和标签 nx.draw_networkx_nodes(G, pos, node_size=100, node_color='yellow') nx.draw_networkx_labels(G, pos) # 单独绘制双向边 nx.draw_networkx_edges(G, pos, edgelist=[(2,3)], edge_color='red', width=3, arrows=True, arrowsize=10) nx.draw_networkx_edges(G, pos, edgelist=[(3,2)], edge_color='blue', width=3, arrows=True, arrowsize=10) # 绘制其余边 other_edges = [e for e in edgelist if e not in [(2,3), (3,2)]] nx.draw_networkx_edges(G, pos, edgelist=other_edges, edge_color='black', width=3, arrows=True, arrowsize=10) plt.show()
内容的提问来源于stack exchange,提问作者runiedKing
相关产品推荐
相关产品推荐

