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

如何获取NetworkX布局后图中各边的长度?

解决NetworkX布局后计算边长度的方法

因为NetworkX的布局函数返回的是节点坐标字典(键为节点ID,值为(x,y)坐标对),你可以基于这个字典手动计算每条边的欧氏距离,具体实现如下:

1. 实现边长度计算函数

遍历图中的每条边,取出两端节点的坐标,用欧氏距离公式计算视觉长度:

import numpy as np

def calculate_edge_length(G, node_pos):
    edge_lengths = {}
    for u, v in G.edges():
        # 获取两个节点的布局坐标
        pos_u = node_pos[u]
        pos_v = node_pos[v]
        # 计算欧氏距离(即画布上边的实际长度)
        length = np.linalg.norm(np.array(pos_u) - np.array(pos_v))
        edge_lengths[(u, v)] = length
    return edge_lengths

2. 将长度添加为图的边属性(可选)

如果需要把长度作为边的永久属性存入图中,方便后续调用,可以执行:

edge_lengths = calculate_edge_length(G, node_pos)
nx.set_edge_attributes(G, edge_lengths, "length")

之后你可以通过G.edges[u, v]["length"]随时获取这条边的视觉长度。

3. 结合你现有代码的完整示例

替换原代码中的calculate_edge_length()调用部分,完整代码如下:

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

data = pd.read_csv('data\\email-dept3.csv')
edges = [edge for edge in zip(data['source'],data['target'])]
print(len(edges))
G = nx.Graph()
G.add_edges_from(edges)

node_pos = nx.kamada_kawai_layout(G)

# 实现并调用边长度计算函数
def calculate_edge_length(G, node_pos):
    edge_lengths = {}
    for u, v in G.edges():
        pos_u = node_pos[u]
        pos_v = node_pos[v]
        length = np.linalg.norm(np.array(pos_u) - np.array(pos_v))
        edge_lengths[(u, v)] = length
    return edge_lengths

edge_lengths = calculate_edge_length(G, node_pos)
# 可选:将长度设为边属性
nx.set_edge_attributes(G, edge_lengths, "length")

# 绘制节点(这里假设你已定义options字典)
options = {"node_color": "skyblue", "node_size": 300}
nx.draw_networkx_nodes(G, node_pos, **options)
# 绘制边(保留你原有的alpha逻辑,假设cent是你定义的边中心性字典)
for key, value in cent.items():
    nx.draw_networkx_edges(G, node_pos, edgelist=[key], alpha=np.amin([1, value*100]), width=2)

plt.show()

补充说明

  • 欧氏距离对应布局后画布上边的实际视觉长度,完全匹配你的需求;
  • 若不需要永久存储边属性,直接使用edge_lengths字典即可获取每条边的长度;
  • 无向图中,NetworkX的边是无序的,遍历G.edges()只会得到每条边一次,无需重复处理反向边。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:36:54