【问题标题】:Display variable sized circles outside of nodes in NetworkX在 NetworkX 中的节点外显示可变大小的圆圈
【发布时间】:2020-11-09 12:39:38
【问题描述】:

我想在我的 NetworkX 圆形布局图中的节点外部显示特征向量值大小的圆圈。到目前为止,我能够在每个节点的顶​​部显示圆圈;但是,我想要每个节点外侧的圆圈。

对于左侧的节点,圆圈将位于节点的左侧。对于右侧的节点,在节点右侧圈出。节点在底部,圆圈将在节点下方。节点在顶部,圆圈将在节点的顶部。

我的代码:

import networkx as nx
import matplotlib.pyplot as plt

# 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.circular_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.25
    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()

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    您可以将它们乘以一个标量,而不是在您的 pos 字典中的 x、y 位置添加一个标量,以使负值更负,正值更正,从而扩大圆的半径节点使。你可以用这个替换你的 for 循环(注意包含改变节点位置的 shift 变量)。

    shift = 1.1 # multiplicative scalar to put the eigenvalue circles outside the original nodes
    
    for node, (x, y) in pos.items():
        rad = centrality[node] * 0.25
        circle = plt.Circle((shift*x, shift*y), radius=rad, color='orange') # multiply shift by x and y
        plt.text(shift*x -.02, shift*y, node, fontsize=16, weight="bold") # multiply shift by x and y
        ax.add_artist(circle)
    

    两个警告,这不会使节点/特征值圆圈接触,并且这可能不是所有图形和特征值的通用解决方案,因此您必须使用 shift 值来制作确保plt.Circles 离您的节点不太近/太远。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2015-05-12
      • 2013-05-10
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多