在NetworkX中的节点顶部显示可变大小的圆圈

2024-06-02 07:53:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个加权networkx图。我已经计算了图上的特征向量中心值;然而,我还想在每个节点的顶部添加圆圈,直观地表示特定节点的特征向量值。根据各个节点的特征向量值,圆圈的大小会有所不同。(值越大,节点顶部的圆越大)

我正在使用以下代码:

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'
)

Tags: networkxnodeformatlabels节点createwithrandom
1条回答
网友
1楼 · 发布于 2024-06-02 07:53:31

你可以用^{}^{}得到你想要的东西。您可能希望进行稍微不同的调整,但希望这可以作为一个良好的起点:

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
}

plt.figure(figsize=(20,20))
ax = plt.gca()
ax.set_aspect('equal')

pos = nx.spring_layout(G)
nx.draw(G, 
        pos=pos,
        node_color='lightblue', 
        labels=labels,
        with_labels=True)

for node, (x,y) in pos.items():
    rad = centrality[node]*0.16
    circle = plt.Circle((x,y+rad), radius=rad, color='orange')
    plt.text(x-.012, y+rad, node, fontsize=16, weight="bold")
    ax.add_artist(circle)
    
plt.show()

enter image description here

相关问题 更多 >