在 NetworkX 中的节点顶部显示可变大小的圆圈
Display variable sized circles on top of nodes in NetworkX
我有一个加权的 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
and 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()
我有一个加权的 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
and 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()