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

发布于 2020-11-09 21:08:57
不是将标量添加到pos dict中的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.Circle不会离节点太近/太远。(=
https://stackoverflow.com/questions/64751847
复制相似问题