在 NetworkX 中的节点外显示可变大小的圆圈
Display variable sized circles outside of nodes in 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()
不是向 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)
两个注意事项,这不会使 nodes/eigenvalue 圆接触,并且这可能不是所有图形和特征值的通用解决方案,因此您必须尝试使用 shift
值,以确保 plt.Circle
s 与您的节点不太 close/far。
我想在我的 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()
不是向 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)
两个注意事项,这不会使 nodes/eigenvalue 圆接触,并且这可能不是所有图形和特征值的通用解决方案,因此您必须尝试使用 shift
值,以确保 plt.Circle
s 与您的节点不太 close/far。