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

标签 python matplotlib 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'
)

最佳答案

您可以通过 matplotlib.pyplot.text 获得您想要的东西和 matplotlib.pyplot.Circle 。您可能希望进行稍微不同的调整,但希望这是一个好的起点:

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

关于python - 在 NetworkX 中的节点顶部显示可变大小的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64727486/

相关文章:

python - 将 pandas 数据框转换为定向 networkx 多图

python - 如何在训练和测试数据之间对齐 pandas get_dummies?

python - 将 Matplotlib 图形嵌入 Tkinter 在 Python 3.5 上崩溃

python - 如何使用 matplotlib.pyplot 更改表格的字体大小

python - 尝试...除了处理 matplotlib 版本

python - 具有随机幂律分布权重的网络

python - 如何实时更新 NetworkX 图?

python - Pandas 多索引数据帧 : 2 values on same level

python - 具有标准 Tensorflow 的 Tensorflow Lite 模型

python - pyparsing 带引号的字符串