微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在NetworkX中的节点外部显示尺寸可变的圆

如何解决在NetworkX中的节点外部显示尺寸可变的圆

我想在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()

enter image description here

解决方法

您可以将它们乘以标量,而不是将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)

resulting graph

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。