首页 > 解决方案 > Networkx 在节点旁边显示特征向量中心值

问题描述

我有一个圆形布局 networkx 加权图。我想知道在计算特征向量中心性值之后,是否有办法在图形上显示 其各自节点旁边的值?

我正在使用特征向量中心性 numpy 函数

centrality = nx.eigenvector_centrality_numpy(G)

print([f"{node} {centrality[node]:0.3f}" for node in centrality])

标签: pythonmatplotlibnetworkx

解决方案


是的,您可以将结果设置nx.eigenvector_centrality_numpynx.draw函数的节点标签,因为为图中的每个节点nx.eigenvector_centrality_numpy返回一个字典{node: value},它等于nx.draw标签使用的格式:

import networkx as nx

# Create a random graph
G = nx.gnp_random_graph(20, 0.2)

# Calculate centrality
centrality = nx.eigenvector_centrality_numpy(G)

# Create labels dict with fixed digit format
labels = {
    node: '{:.3f}'.format(centrality[node])
    for node in centrality
}

# Draw the graph with labels
nx.draw(
    G,
    with_labels=True,
    labels=labels,
    node_color='#FF0000'
)

在此处输入图像描述


推荐阅读