You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中含自环的网络可视化异常问题求助

解决NetworkX绘制带自环邻接数组时出现额外节点的问题

问题描述

使用NetworkX绘制包含自环的二维邻接数组时,绘图结果出现额外节点异常。示例代码如下:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

A = np.array([[4, 5, 6],[2, 1, 3],[5, 10, 3]])
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
layout = nx.spring_layout(G)
nx.draw_circular(G, with_labels=True)

for edge in G.edges(data="weight"): # edges thickness to be based on the weight
    nx.draw_networkx_edges(G, layout, edgelist=[edge], width=edge[2])

plt.show()

绘图结果中同一个节点被绘制在两个不同位置,看起来像是出现了额外节点,同时边的显示也混乱。

问题原因

代码混用了两种节点布局:调用nx.draw_circular()时用了圆形布局,但后续绘制边时用的是spring_layout()生成的布局。两种布局下节点位置完全不同,导致视觉上出现“额外节点”的假象。

解决方法

统一使用同一种布局,确保节点位置一致。以下是两种修正后的代码示例:

方案1:统一使用圆形布局

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

A = np.array([[4, 5, 6],[2, 1, 3],[5, 10, 3]])
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
# 统一生成圆形布局
layout = nx.circular_layout(G)
# 使用该布局绘制节点和标签
nx.draw(G, layout, with_labels=True)

# 按权重绘制所有边(包括自环)
for edge in G.edges(data="weight"):
    nx.draw_networkx_edges(G, layout, edgelist=[edge], width=edge[2])

plt.show()

方案2:统一使用弹簧布局

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

A = np.array([[4, 5, 6],[2, 1, 3],[5, 10, 3]])
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
# 统一生成弹簧布局
layout = nx.spring_layout(G)
# 使用该布局绘制节点和标签
nx.draw(G, layout, with_labels=True)

# 按权重绘制所有边(包括自环)
for edge in G.edges(data="weight"):
    nx.draw_networkx_edges(G, layout, edgelist=[edge], width=edge[2])

plt.show()

额外优化:自环显示调整

如果自环显示不够清晰,可添加connectionstyle参数调整弧度,让自环更易区分:

nx.draw_networkx_edges(G, layout, edgelist=[edge], width=edge[2], connectionstyle='arc3,rad=0.1')

内容的提问来源于stack exchange,提问作者statwoman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:05:39