简体   繁体   English

Networkx Graph图节点权重

[英]Networkx Graph plot node weights

I would like to assign node weights to each node in an undirected graph. 我想为无向图中的每个节点分配节点权重。 I use the following MWE: 我使用以下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()

Then I have a figure of the following form: 然后,我得到了以下形式的图形: 在此处输入图片说明

I would like to plot a graph with the weights given in a new color next to the nodes, such as: 我想在节点旁边绘制一个以新颜色给出的权重的图形,例如: 在此处输入图片说明

What is the easiest way to implement this? 实现此目的最简单的方法是什么? On SO the materials are mostly for edge weights, or changing node sizes wrt the node weights. 在SO上,材料主要用于边缘权重,或用于更改节点权重的节点大小。

You can use labels attribute with corresponding dict and node_color attribute with corresponding list. 您可以将labels属性与相应的dict和node_color属性与相应的列表一起使用。 For this code: 对于此代码:

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 will draw: Networkx将绘制:

在此处输入图片说明

If you want to draw both node ID and its weight, you can write something like this: 如果要绘制节点ID及其权重,则可以编写如下内容:

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


If you have missing weight attributes in nodes and want to draw them, you can use this code: 如果您在节点中缺少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
}

I think it is nearly impossible to draw weights near nodes with different color. 我认为几乎不可能具有不同颜色的节点附近绘制权重。 It is the best I can suggest to you. 这是我可以向您推荐的最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM