Networkx Graph图节点权重

时间:2019-05-24 14:30:34

标签: python python-3.x matplotlib graph networkx

我想为无向图中的每个节点分配节点权重。我使用以下MWE:

import sys
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(0)
G.add_node(1, weight=2)
G.add_node(2, weight=3)
nx.draw(G, with_labels=True)
plt.show()

然后我有一个以下形式的图形: enter image description here

我想在节点旁边绘制一个以新颜色给出的权重的图形,例如: enter image description here

最简单的方法是什么?在SO上,材料主要用于边缘权重或节点尺寸w.r.t.节点权重。

1 个答案:

答案 0 :(得分:1)

您可以将labels属性与相应的字典一起使用,并将node_color属性与相应的列表一起使用。对于此代码:

G = nx.Graph()
G.add_node(0, weight=8)
G.add_node(1, weight=5)
G.add_node(2, weight=3)
labels = {n: G.nodes[n]['weight'] for n in G.nodes}
colors = [G.nodes[n]['weight'] for n in G.nodes]
nx.draw(G, with_labels=True, labels=labels, node_color=colors)

Networkx将绘制:

enter image description here

如果要同时绘制节点ID及其权重,则可以编写如下内容:

labels = {n: str(n) + '; ' + str(G.nodes[n]['weight']) for n in G.nodes}


如果节点中缺少weight属性并想要绘制它们,则可以使用以下代码:

labels = {
    n: str(n) + '\nweight=' + str(G.nodes[n]['weight']) if 'weight' in G.nodes[n] else str(n)
    for n in G.nodes
}

我认为几乎不可能在个节点上绘制具有不同颜色的权重。这是我最好的建议。